diff --git a/.buildkite/pipelines/pull_request/renovate.yml b/.buildkite/pipelines/pull_request/renovate.yml index 3b441cfe5375..98302a8d7912 100644 --- a/.buildkite/pipelines/pull_request/renovate.yml +++ b/.buildkite/pipelines/pull_request/renovate.yml @@ -1,12 +1,4 @@ steps: - - command: .buildkite/scripts/lifecycle/pre_build.sh - label: Pre-Build - timeout_in_minutes: 10 - agents: - machineType: n2-standard-2 - - - wait - - command: .buildkite/scripts/steps/renovate.sh label: 'Renovate validation' agents: diff --git a/.buildkite/scripts/pipelines/pull_request/pipeline.ts b/.buildkite/scripts/pipelines/pull_request/pipeline.ts index 87ac7096e5a3..51587280c4ed 100644 --- a/.buildkite/scripts/pipelines/pull_request/pipeline.ts +++ b/.buildkite/scripts/pipelines/pull_request/pipeline.ts @@ -39,15 +39,16 @@ const getPipeline = (filename: string, removeSteps = true) => { return; } + pipeline.push(getAgentImageConfig({ returnYaml: true })); + const onlyRunQuickChecks = await areChangesSkippable([/^renovate\.json$/], REQUIRED_PATHS); if (onlyRunQuickChecks) { pipeline.push(getPipeline('.buildkite/pipelines/pull_request/renovate.yml', false)); - pipeline.push(getPipeline('.buildkite/pipelines/pull_request/post_build.yml')); - console.log('Isolated changes to renovate.json. Skipping main PR pipeline.'); + + console.log([...new Set(pipeline)].join('\n')); return; } - pipeline.push(getAgentImageConfig({ returnYaml: true })); pipeline.push(getPipeline('.buildkite/pipelines/pull_request/base.yml', false)); if (await doAnyChangesMatch([/^packages\/kbn-handlebars/])) { @@ -250,7 +251,7 @@ const getPipeline = (filename: string, removeSteps = true) => { /^packages\/kbn-securitysolution-.*/, /^x-pack\/plugins\/alerting/, /^x-pack\/plugins\/data_views\/common/, - /^x-pack\/plugins\/lists/, + /^x-pack\/solutions\/security\/plugins\/lists/, /^x-pack\/plugins\/rule_registry\/common/, /^x-pack\/solutions\/security\/plugins\/security_solution/, /^x-pack\/solutions\/security\/plugins\/security_solution_ess/, @@ -306,10 +307,10 @@ const getPipeline = (filename: string, removeSteps = true) => { /^packages\/kbn-search-types/, /^packages\/kbn-securitysolution-.*/, /^src\/platform\/packages\/shared\/kbn-securitysolution-ecs/, - /^packages\/kbn-securitysolution-io-ts-alerting-types/, - /^packages\/kbn-securitysolution-io-ts-list-types/, - /^packages\/kbn-securitysolution-list-hooks/, - /^packages\/kbn-securitysolution-t-grid/, + /^x-pack\/solutions\/security\/packages\/kbn-securitysolution-io-ts-alerting-types/, + /^x-pack\/solutions\/security\/packages\/kbn-securitysolution-io-ts-list-types/, + /^x-pack\/solutions\/security\/packages\/kbn-securitysolution-list-hooks/, + /^x-pack\/solutions\/security\/packages\/kbn-securitysolution-t-grid/, /^packages\/kbn-ui-theme/, /^packages\/kbn-utility-types/, /^packages\/react/, @@ -335,7 +336,7 @@ const getPipeline = (filename: string, removeSteps = true) => { /^x-pack\/plugins\/cases/, /^x-pack\/plugins\/data_views\/common/, /^x-pack\/solutions\/security\/plugins\/elastic_assistant/, - /^x-pack\/plugins\/lists/, + /^x-pack\/solutions\/security\/plugins\/lists/, /^x-pack\/plugins\/rule_registry\/common/, /^x-pack\/solutions\/security\/plugins\/security_solution/, /^x-pack\/solutions\/security\/plugins\/security_solution_ess/, diff --git a/.buildkite/scripts/steps/code_generation/security_solution_codegen.sh b/.buildkite/scripts/steps/code_generation/security_solution_codegen.sh index db7131d12785..5f140efc5db8 100755 --- a/.buildkite/scripts/steps/code_generation/security_solution_codegen.sh +++ b/.buildkite/scripts/steps/code_generation/security_solution_codegen.sh @@ -7,16 +7,16 @@ source .buildkite/scripts/common/util.sh echo --- Security Solution OpenAPI Code Generation echo -e "\n[Security Solution OpenAPI Code Generation] OpenAPI Common Package\n" -(cd packages/kbn-openapi-common && yarn openapi:generate) +(cd src/platform/packages/shared/kbn-openapi-common && yarn openapi:generate) echo -e "\n[Security Solution OpenAPI Code Generation] Lists Common Package\n" -(cd packages/kbn-securitysolution-lists-common && yarn openapi:generate) +(cd x-pack/solutions/security/packages/kbn-securitysolution-lists-common && yarn openapi:generate) echo -e "\n[Security Solution OpenAPI Code Generation] Exceptions Common Package\n" -(cd packages/kbn-securitysolution-exceptions-common && yarn openapi:generate) +(cd x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common && yarn openapi:generate) echo -e "\n[Security Solution OpenAPI Code Generation] Endpoint Exceptions Common Package\n" -(cd packages/kbn-securitysolution-endpoint-exceptions-common && yarn openapi:generate) +(cd x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common && yarn openapi:generate) echo -e "\n[Security Solution OpenAPI Code Generation] Security Solution Plugin\n" (cd x-pack/solutions/security/plugins/security_solution && yarn openapi:generate) diff --git a/.buildkite/scripts/steps/openapi_bundling/security_solution_openapi_bundling.sh b/.buildkite/scripts/steps/openapi_bundling/security_solution_openapi_bundling.sh index 18d2c963b3c2..4dd23435e351 100755 --- a/.buildkite/scripts/steps/openapi_bundling/security_solution_openapi_bundling.sh +++ b/.buildkite/scripts/steps/openapi_bundling/security_solution_openapi_bundling.sh @@ -16,13 +16,13 @@ echo -e "\n[Security Solution OpenAPI Bundling] Entity Analytics API\n" (cd x-pack/solutions/security/plugins/security_solution && yarn openapi:bundle:entity-analytics) echo -e "\n[Security Solution OpenAPI Bundling] Lists API\n" -(cd packages/kbn-securitysolution-lists-common && yarn openapi:bundle) +(cd x-pack/solutions/security/packages/kbn-securitysolution-lists-common && yarn openapi:bundle) echo -e "\n[Security Solution OpenAPI Bundling] Exceptions API\n" -(cd packages/kbn-securitysolution-exceptions-common && yarn openapi:bundle) +(cd x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common && yarn openapi:bundle) echo -e "\n[Security Solution OpenAPI Bundling] Endpoint Exceptions API\n" -(cd packages/kbn-securitysolution-endpoint-exceptions-common && yarn openapi:bundle) +(cd x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common && yarn openapi:bundle) echo -e "\n[Security Solution OpenAPI Bundling] Endpoint Management API\n" (cd x-pack/solutions/security/plugins/security_solution && yarn openapi:bundle:endpoint-management) diff --git a/.eslintrc.js b/.eslintrc.js index 6bf88444aaf7..93e3dabf3b86 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1343,8 +1343,8 @@ module.exports = { { // front end and common typescript and javascript files only files: [ - 'x-pack/plugins/lists/public/**/*.{js,mjs,ts,tsx}', - 'x-pack/plugins/lists/common/**/*.{js,mjs,ts,tsx}', + 'x-pack/solutions/security/plugins/lists/public/**/*.{js,mjs,ts,tsx}', + 'x-pack/solutions/security/plugins/lists/common/**/*.{js,mjs,ts,tsx}', ], rules: { 'import/no-nodejs-modules': 'error', @@ -1360,14 +1360,20 @@ module.exports = { }, { // typescript for /public and /common - files: ['x-pack/plugins/lists/public/*.{ts,tsx}', 'x-pack/plugins/lists/common/*.{ts,tsx}'], + files: [ + 'x-pack/solutions/security/plugins/lists/public/*.{ts,tsx}', + 'x-pack/solutions/security/plugins/lists/common/*.{ts,tsx}', + ], rules: { '@typescript-eslint/no-for-in-array': 'error', }, }, { // typescript for /public and /common - files: ['x-pack/plugins/lists/public/*.{ts,tsx}', 'x-pack/plugins/lists/common/*.{ts,tsx}'], + files: [ + 'x-pack/solutions/security/plugins/lists/public/*.{ts,tsx}', + 'x-pack/solutions/security/plugins/lists/common/*.{ts,tsx}', + ], plugins: ['react'], env: { jest: true, @@ -1425,7 +1431,7 @@ module.exports = { }, }, { - files: ['x-pack/plugins/lists/public/**/!(*.test).{js,mjs,ts,tsx}'], + files: ['x-pack/solutions/security/plugins/lists/public/**/!(*.test).{js,mjs,ts,tsx}'], plugins: ['react-perf'], rules: { 'react-perf/jsx-no-new-object-as-prop': 'error', @@ -1436,7 +1442,7 @@ module.exports = { }, { // typescript and javascript for front and back - files: ['x-pack/plugins/lists/**/*.{js,mjs,ts,tsx}'], + files: ['x-pack/solutions/security/plugins/lists/**/*.{js,mjs,ts,tsx}'], plugins: ['eslint-plugin-node'], env: { jest: true, diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 627579d513e9..4943b4279c39 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -395,7 +395,6 @@ packages/kbn-monaco @elastic/appex-sharedux packages/kbn-object-versioning @elastic/appex-sharedux packages/kbn-object-versioning-utils @elastic/appex-sharedux packages/kbn-openapi-bundler @elastic/security-detection-rule-management -packages/kbn-openapi-common @elastic/security-detection-rule-management packages/kbn-openapi-generator @elastic/security-detection-rule-management packages/kbn-optimizer @elastic/kibana-operations packages/kbn-optimizer-webpack-helpers @elastic/kibana-operations @@ -454,24 +453,6 @@ packages/kbn-search-index-documents @elastic/search-kibana packages/kbn-search-response-warnings @elastic/kibana-data-discovery packages/kbn-search-types @elastic/kibana-data-discovery packages/kbn-security-hardening @elastic/kibana-security -packages/kbn-securitysolution-autocomplete @elastic/security-detection-engine -packages/kbn-securitysolution-endpoint-exceptions-common @elastic/security-detection-engine -packages/kbn-securitysolution-es-utils @elastic/security-detection-engine -packages/kbn-securitysolution-exception-list-components @elastic/security-detection-engine -packages/kbn-securitysolution-exceptions-common @elastic/security-detection-engine -packages/kbn-securitysolution-hook-utils @elastic/security-detection-engine -packages/kbn-securitysolution-io-ts-alerting-types @elastic/security-detection-engine -packages/kbn-securitysolution-io-ts-list-types @elastic/security-detection-engine -packages/kbn-securitysolution-io-ts-types @elastic/security-detection-engine -packages/kbn-securitysolution-io-ts-utils @elastic/security-detection-engine -packages/kbn-securitysolution-list-api @elastic/security-detection-engine -packages/kbn-securitysolution-list-constants @elastic/security-detection-engine -packages/kbn-securitysolution-list-hooks @elastic/security-detection-engine -packages/kbn-securitysolution-list-utils @elastic/security-detection-engine -packages/kbn-securitysolution-lists-common @elastic/security-detection-engine -packages/kbn-securitysolution-rules @elastic/security-detection-engine -packages/kbn-securitysolution-t-grid @elastic/security-detection-engine -packages/kbn-securitysolution-utils @elastic/security-detection-engine packages/kbn-server-http-tools @elastic/kibana-core packages/kbn-set-map @elastic/kibana-operations packages/kbn-shared-svg @elastic/obs-ux-infra_services-team @@ -517,7 +498,6 @@ packages/kbn-whereis-pkg-cli @elastic/kibana-operations packages/kbn-xstate-utils @elastic/obs-ux-logs-team packages/kbn-yarn-lock-validator @elastic/kibana-operations packages/kbn-zod @elastic/kibana-core -packages/kbn-zod-helpers @elastic/security-detection-rule-management packages/presentation/presentation_containers @elastic/kibana-presentation packages/presentation/presentation_publishing @elastic/kibana-presentation packages/react/kibana_context/common @elastic/appex-sharedux @@ -613,8 +593,13 @@ src/platform/packages/shared/kbn-management/settings/components/field_row @elast src/platform/packages/shared/kbn-management/settings/field_definition @elastic/kibana-management src/platform/packages/shared/kbn-management/settings/types @elastic/kibana-management src/platform/packages/shared/kbn-management/settings/utilities @elastic/kibana-management +src/platform/packages/shared/kbn-openapi-common @elastic/security-detection-rule-management src/platform/packages/shared/kbn-osquery-io-ts-types @elastic/security-asset-management src/platform/packages/shared/kbn-securitysolution-ecs @elastic/security-threat-hunting-explore +src/platform/packages/shared/kbn-securitysolution-es-utils @elastic/security-detection-engine +src/platform/packages/shared/kbn-securitysolution-io-ts-types @elastic/security-detection-engine +src/platform/packages/shared/kbn-securitysolution-io-ts-utils @elastic/security-detection-engine +src/platform/packages/shared/kbn-securitysolution-rules @elastic/security-detection-engine src/platform/packages/shared/kbn-server-route-repository @elastic/obs-knowledge-team src/platform/packages/shared/kbn-server-route-repository-client @elastic/obs-knowledge-team src/platform/packages/shared/kbn-server-route-repository-utils @elastic/obs-knowledge-team @@ -623,6 +608,7 @@ src/platform/packages/shared/kbn-sse-utils-client @elastic/obs-knowledge-team src/platform/packages/shared/kbn-sse-utils-server @elastic/obs-knowledge-team src/platform/packages/shared/kbn-typed-react-router-config @elastic/obs-knowledge-team @elastic/obs-ux-infra_services-team src/platform/packages/shared/kbn-unsaved-changes-prompt @elastic/kibana-management +src/platform/packages/shared/kbn-zod-helpers @elastic/security-detection-rule-management src/platform/packages/shared/serverless/settings/security_project @elastic/security-solution @elastic/kibana-management src/platform/plugins/shared/ai_assistant_management/selection @elastic/obs-ai-assistant src/platform/plugins/shared/console @elastic/kibana-management @@ -878,6 +864,7 @@ x-pack/platform/plugins/shared/license_management @elastic/kibana-management x-pack/platform/plugins/shared/ml @elastic/ml-ui x-pack/platform/plugins/shared/observability_solution/observability_ai_assistant @elastic/obs-ai-assistant x-pack/platform/plugins/shared/osquery @elastic/security-defend-workflows +x-pack/platform/plugins/shared/screenshotting @elastic/kibana-reporting-services x-pack/platform/plugins/shared/searchprofiler @elastic/kibana-management x-pack/plugins/actions @elastic/response-ops x-pack/plugins/alerting @elastic/response-ops @@ -909,7 +896,6 @@ x-pack/plugins/graph @elastic/kibana-visualizations x-pack/plugins/index_management @elastic/kibana-management x-pack/plugins/lens @elastic/kibana-visualizations x-pack/plugins/licensing @elastic/kibana-core -x-pack/plugins/lists @elastic/security-detection-engine x-pack/plugins/logstash @elastic/logstash x-pack/plugins/maps @elastic/kibana-presentation x-pack/plugins/monitoring @elastic/stack-monitoring @@ -935,7 +921,6 @@ x-pack/plugins/observability_solution/profiling_data_access @elastic/obs-ux-infr x-pack/plugins/reporting @elastic/appex-sharedux x-pack/plugins/rule_registry @elastic/response-ops @elastic/obs-ux-management-team x-pack/plugins/saved_objects_tagging @elastic/appex-sharedux -x-pack/plugins/screenshotting @elastic/kibana-reporting-services x-pack/plugins/search_assistant @elastic/search-kibana x-pack/plugins/search_connectors @elastic/search-kibana x-pack/plugins/search_homepage @elastic/search-kibana @@ -953,7 +938,7 @@ x-pack/plugins/stack_connectors @elastic/response-ops x-pack/plugins/task_manager @elastic/response-ops x-pack/plugins/telemetry_collection_xpack @elastic/kibana-core x-pack/plugins/triggers_actions_ui @elastic/response-ops -x-pack/plugins/upgrade_assistant @elastic/kibana-management +x-pack/plugins/upgrade_assistant @elastic/kibana-core x-pack/solutions/observability/packages/alert_details @elastic/obs-ux-management-team x-pack/solutions/observability/packages/alerting_test_data @elastic/obs-ux-management-team x-pack/solutions/observability/packages/get_padded_alert_time_range_util @elastic/obs-ux-management-team @@ -986,6 +971,20 @@ x-pack/solutions/security/packages/features @elastic/security-threat-hunting-exp x-pack/solutions/security/packages/index-adapter @elastic/security-threat-hunting x-pack/solutions/security/packages/kbn-cloud-security-posture/graph @elastic/kibana-cloud-security-posture x-pack/solutions/security/packages/kbn-cloud-security-posture/public @elastic/kibana-cloud-security-posture +x-pack/solutions/security/packages/kbn-securitysolution-autocomplete @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-hook-utils @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-list-api @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-list-constants @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-list-hooks @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-list-utils @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-lists-common @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-t-grid @elastic/security-detection-engine +x-pack/solutions/security/packages/kbn-securitysolution-utils @elastic/security-detection-engine x-pack/solutions/security/packages/navigation @elastic/security-threat-hunting-explore x-pack/solutions/security/packages/side_nav @elastic/security-threat-hunting-explore x-pack/solutions/security/packages/storybook/config @elastic/security-threat-hunting-explore @@ -996,6 +995,7 @@ x-pack/solutions/security/plugins/cloud_security_posture @elastic/kibana-cloud-s x-pack/solutions/security/plugins/ecs_data_quality_dashboard @elastic/security-threat-hunting-explore x-pack/solutions/security/plugins/elastic_assistant @elastic/security-generative-ai x-pack/solutions/security/plugins/kubernetes_security @elastic/kibana-cloud-security-posture +x-pack/solutions/security/plugins/lists @elastic/security-detection-engine x-pack/solutions/security/plugins/security_solution @elastic/security-solution x-pack/solutions/security/plugins/security_solution_ess @elastic/security-solution x-pack/solutions/security/plugins/security_solution_serverless @elastic/security-solution @@ -2638,7 +2638,14 @@ oas_docs/kibana.info.yaml @elastic/platform-docs # Plugin manifests /src/plugins/**/kibana.jsonc @elastic/kibana-core +/src/platform/plugins/shared/**/kibana.jsonc @elastic/kibana-core +/src/platform/plugins/private/**/kibana.jsonc @elastic/kibana-core /x-pack/plugins/**/kibana.jsonc @elastic/kibana-core +/x-pack/platform/plugins/shared/**/kibana.jsonc @elastic/kibana-core +/x-pack/platform/plugins/private/**/kibana.jsonc @elastic/kibana-core +/x-pack//solutions/observability/plugins/**/kibana.jsonc @elastic/kibana-core +/x-pack//solutions/search/plugins/**/kibana.jsonc @elastic/kibana-core +/x-pack//solutions/security/plugins/**/kibana.jsonc @elastic/kibana-core # Temporary Encrypted Saved Objects (ESO) guarding # This additional code-ownership is meant to be a temporary precaution to notify the Kibana platform security team @@ -3354,20 +3361,20 @@ x-pack/solutions/security/packages/kbn-cloud-security-posture/public @elastic/ki x-pack/solutions/security/packages/data-stream-adapter @elastic/security-threat-hunting x-pack/solutions/security/packages/expandable-flyout @elastic/security-threat-hunting-investigations x-pack/solutions/security/packages/index-adapter @elastic/security-threat-hunting -x-pack/solutions/security/packages/kbn-securitysolution-autocomplete @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-hook-utils @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-list-api @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-list-constants @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-list-hooks @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-list-utils @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-lists-common @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-t-grid @elastic/security-detection-engine -x-pack/solutions/security/packages/kbn-securitysolution-utils @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-list-api @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-list-constants @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-list-utils @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-lists-common @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-t-grid @elastic/security-detection-engine +x-pack/solutions/security/x-pack/solutions/security/packages/kbn-securitysolution-utils @elastic/security-detection-engine x-pack/solutions/security/packages/navigation @elastic/security-threat-hunting-explore x-pack/solutions/security/packages/side_nav @elastic/security-threat-hunting-explore x-pack/solutions/security/packages/upselling @elastic/security-threat-hunting-explore @@ -3377,7 +3384,7 @@ x-pack/solutions/security/plugins/cloud_security_posture @elastic/kibana-cloud-s x-pack/solutions/security/plugins/ecs_data_quality_dashboard @elastic/security-threat-hunting-explore x-pack/solutions/security/plugins/elastic_assistant @elastic/security-generative-ai x-pack/solutions/security/plugins/kubernetes_security @elastic/kibana-cloud-security-posture -x-pack/solutions/security/plugins/lists @elastic/security-detection-engine +x-pack/solutions/security/solutions/security/plugins/lists @elastic/security-detection-engine x-pack/solutions/security/solutions/security/plugins/security_solution @elastic/security-solution x-pack/solutions/security/solutions/security/plugins/security_solution_ess @elastic/security-solution x-pack/solutions/security/solutions/security/plugins/security_solution_serverless @elastic/security-solution diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml index 8ad946732714..3077ac0f5167 100644 --- a/.github/codeql/codeql-config.yml +++ b/.github/codeql/codeql-config.yml @@ -78,8 +78,8 @@ paths-ignore: - x-pack/solutions/security/plugins/elastic_assistant/scripts - x-pack/plugins/event_log/scripts - x-pack/plugins/fleet/scripts - - x-pack/plugins/lists/scripts - - x-pack/plugins/lists/server/scripts + - x-pack/solutions/security/plugins/lists/scripts + - x-pack/solutions/security/plugins/lists/server/scripts - x-pack/plugins/observability_solution/*/scripts - x-pack/platform/plugins/shared/osquery/scripts - x-pack/plugins/rule_registry/scripts diff --git a/.i18nrc.json b/.i18nrc.json index 63cbc62d1365..0e167c2b08b5 100644 --- a/.i18nrc.json +++ b/.i18nrc.json @@ -6,7 +6,7 @@ "alertsUIShared": "packages/kbn-alerts-ui-shared/src", "alertingTypes": "packages/kbn-alerting-types", "apmOss": "src/plugins/apm_oss", - "autocomplete": "packages/kbn-securitysolution-autocomplete/src", + "autocomplete": "x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src", "avcBanner": "src/platform/packages/shared/kbn-avc-banner/src", "bfetch": "src/plugins/bfetch", "bfetchError": "packages/kbn-bfetch-error", @@ -25,12 +25,13 @@ "data": "src/plugins/data", "observabilityAlertDetails": "x-pack/solutions/observability/packages/alert_details", "dataViews": "src/plugins/data_views", - "defaultNavigation": [ - "packages/default-nav", - "src/platform/packages/private/default-nav" - ], + "defaultNavigation": ["packages/default-nav", "src/platform/packages/private/default-nav"], "devTools": "src/platform/plugins/shared/dev_tools", - "discover": ["src/plugins/discover", "packages/kbn-discover-utils", "packages/kbn-discover-contextual-components"], + "discover": [ + "src/plugins/discover", + "packages/kbn-discover-utils", + "packages/kbn-discover-contextual-components" + ], "savedSearch": "src/plugins/saved_search", "embeddableApi": "src/plugins/embeddable", "presentationPanel": "src/plugins/presentation_panel", @@ -87,8 +88,8 @@ "kibana-react": "src/plugins/kibana_react", "kibanaOverview": "src/plugins/kibana_overview", "lensFormulaDocs": "packages/kbn-lens-formula-docs", - "lists": "packages/kbn-securitysolution-list-utils/src", - "exceptionList-components": "packages/kbn-securitysolution-exception-list-components/src", + "lists": "x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src", + "exceptionList-components": "x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src", "management": [ "src/platform/plugins/shared/management", "src/platform/packages/private/kbn-management", @@ -120,11 +121,15 @@ "searchResponseWarnings": "packages/kbn-search-response-warnings", "searchTypes": "packages/kbn-search-types", "securitySolutionPackages": [ - "x-pack/solutions/security/packages" - ], - "sharedPlatformPackages": [ - "x-pack/platform/packages/shared/kbn-cloud-security-posture" + "x-pack/solutions/security/packages/data_table", + "x-pack/solutions/security/packages/ecs_data_quality_dashboard", + "x-pack/solutions/security/packages/features", + "x-pack/solutions/security/packages/kbn-cloud-security-posture", + "x-pack/solutions/security/packages/navigation", + "x-pack/solutions/security/packages/side_nav", + "x-pack/solutions/security/packages/upselling" ], + "sharedPlatformPackages": ["x-pack/platform/packages/shared/kbn-cloud-security-posture"], "serverlessPackages": "packages/serverless", "sse": ["src/platform/packages/shared/kbn-sse-utils"], "coloring": "packages/kbn-coloring/src", @@ -140,7 +145,7 @@ "uiActionsExamples": "examples/ui_action_examples", "usageCollection": "src/plugins/usage_collection", "userProfileComponents": "packages/kbn-user-profile-components", - "utils": "packages/kbn-securitysolution-utils/src", + "utils": "x-pack/solutions/security/packages/kbn-securitysolution-utils/src", "visDefaultEditor": "src/plugins/vis_default_editor", "visTypeGauge": "src/plugins/vis_types/gauge", "visTypeHeatmap": "src/plugins/vis_types/heatmap", diff --git a/config/serverless.security.yml b/config/serverless.security.yml index 47a67c293565..0e3a0c92f854 100644 --- a/config/serverless.security.yml +++ b/config/serverless.security.yml @@ -106,7 +106,7 @@ xpack.fleet.internal.registry.excludePackages: [ 'dga', # Unsupported in serverless - 'cloud-defend', + 'cloud_defend', ] # fleet_server package installed to publish agent metrics xpack.fleet.packages: diff --git a/dev_docs/key_concepts/building_blocks.mdx b/dev_docs/key_concepts/building_blocks.mdx index 29cf2df7a764..1afac686d1ad 100644 --- a/dev_docs/key_concepts/building_blocks.mdx +++ b/dev_docs/key_concepts/building_blocks.mdx @@ -42,7 +42,7 @@ and . Every feature that is added to a registered (Lens, Maps, Saved Searches and more) will be available automatically, as well as any that are added to the Embeddable context menu panel (for example, drilldowns, custom panel time ranges, and "share to" features). +with the . Every feature that is added to a registered (Lens, Maps, Discover sessions and more) will be available automatically, as well as any that are added to the Embeddable context menu panel (for example, drilldowns, custom panel time ranges, and "share to" features). The Dashboard Embeddable is one of the highest-level UI components you can add to your application. diff --git a/dev_docs/tutorials/performance/adding_custom_performance_metrics.mdx b/dev_docs/tutorials/performance/adding_custom_performance_metrics.mdx index 37322e3f55e0..41570826ad2b 100644 --- a/dev_docs/tutorials/performance/adding_custom_performance_metrics.mdx +++ b/dev_docs/tutorials/performance/adding_custom_performance_metrics.mdx @@ -294,7 +294,63 @@ This event will be indexed with the following structure: } ``` +#### Add time ranges + +The meta field supports telemetry on time ranges, providing calculated metrics for enhanced context. This includes: + +- **Query range in ceconds:** + + - Calculated as the time difference in seconds between `rangeFrom` and `rangeTo`. + +- **Offset calculation:** + - A **negative offset** indicates that `rangeTo` is in the past. + - A **positive offset** indicates that `rangeTo` is in the future. + - An offset of **zero** indicates that `rangeTo` matches `'now'`. + +###### Code example + +``` +onPageReady({ + meta: { + rangeFrom: 'now-15m', + rangeTo: 'now', + } +}); +``` + +This will be indexed as: + +```typescript +{ + "_index": "backing-ebt-kibana-browser-performance-metrics-000001", // Performance metrics are stored in a dedicated simplified index (browser \ server). + "_source": { + "timestamp": "2024-08-13T11:29:58.275Z" + "event_type": "performance_metric", // All performance events share a common event type to simplify mapping + "eventName": 'kibana:plugin_render_time', // Event name as specified when reporting it + "duration": 736, // Event duration as specified when reporting it + "meta": { + "target": '/home', + "query_range_secs": 900 + "query_offset_secs": 0 // now + }, + "context": { // Context holds information identifying the deployment, version, application and page that generated the event + "version": "8.16.0-SNAPSHOT", + "cluster_name": "elasticsearch", + "pageName": "application:home:app", + "applicationId": "home", + "page": "app", + "entityId": "61c58ad0-3dd3-11e8-b2b9-5d5dc1715159", + "branch": "main", + ... + }, + + ... + }, +} +``` + #### Add custom metrics + Having `kibana:plugin_render_time` metric event is not always enough, depending on the use case you would likely need some complementary information to give some sense to the value reported by the metric (e.g. number of hosts, number of services, number of dataStreams, etc). `kibana:plugin_render_time` metric API supports up to 9 numbered free fields that can be used to report numeric metrics that you intend to analyze. Note that they can be used for any type of numeric information you may want to report. @@ -304,10 +360,12 @@ We could make use of these custom metrics using the following format: ... // Call onPageReady once the meaningful data has rendered and visible to the user onPageReady({ - key1: 'datasets', - value1: 5, - key2: 'documents', - value2: 1000, + customMetrics: { + key1: 'datasets', + value1: 5, + key2: 'documents', + value2: 1000, + } }); ... ``` diff --git a/docs/concepts/data-views.asciidoc b/docs/concepts/data-views.asciidoc index 02922b298976..eb090554186a 100644 --- a/docs/concepts/data-views.asciidoc +++ b/docs/concepts/data-views.asciidoc @@ -166,7 +166,7 @@ clusters or indicies from cross-cluster search]. When you delete a {data-source}, you cannot recover the associated field formatters, runtime fields, source filters, and field popularity data. Deleting a {data-source} does not remove any indices or data documents from {es}. -WARNING: Deleting a {data-source} breaks all visualizations, saved searches, and other saved objects that reference the data view. +WARNING: Deleting a {data-source} breaks all visualizations, saved Discover sessions, and other saved objects that reference the data view. . Go to the **Data Views** management page using the navigation menu or the <>. diff --git a/docs/concepts/esql.asciidoc b/docs/concepts/esql.asciidoc index a3a091a4c6d0..0b9af290c2d8 100644 --- a/docs/concepts/esql.asciidoc +++ b/docs/concepts/esql.asciidoc @@ -26,7 +26,7 @@ disabled using the `enableESQL` setting from the {kibana-ref}/advanced-options.html[Advanced Settings]. This will hide the {esql} user interface from various applications. -However, users will be able to access existing {esql} artifacts like saved searches and visualizations. +However, users will be able to access existing {esql} artifacts like saved Discover sessions and visualizations. ==== [float] diff --git a/docs/concepts/save-query.asciidoc b/docs/concepts/save-query.asciidoc index b249f7e9aea2..a4d6dd28ea6e 100644 --- a/docs/concepts/save-query.asciidoc +++ b/docs/concepts/save-query.asciidoc @@ -11,10 +11,10 @@ Save this query, and you can embed the search results in dashboards, use them as a foundation for building a visualization, and share them in a link or CVS form. -Saved queries are different than <>, +Saved queries are different than <>, which include the *Discover* configuration—selected columns in the document table, sort order, and {data-source}—in addition to the query. -Saved searches are primarily used for adding search results to a dashboard. +Discover sessions are primarily used for adding search results to a dashboard. [role="xpack"] ==== Read-only access diff --git a/docs/developer/plugin-list.asciidoc b/docs/developer/plugin-list.asciidoc index f18bafe5221b..80511095a000 100644 --- a/docs/developer/plugin-list.asciidoc +++ b/docs/developer/plugin-list.asciidoc @@ -309,6 +309,7 @@ oss plugins. |{kib-repo}blob/{branch}/src/plugins/saved_search/README.md[savedSearch] |Contains the saved search saved object definition and helpers. +This object is created when a user saves their current session in the Discover app. |{kib-repo}blob/{branch}/src/plugins/screenshot_mode/README.md[screenshotMode] @@ -693,7 +694,7 @@ the infrastructure monitoring use-case within Kibana. |The licensing plugin retrieves license data from Elasticsearch at regular configurable intervals. -|{kib-repo}blob/{branch}/x-pack/plugins/lists/README.md[lists] +|{kib-repo}blob/{branch}/x-pack/solutions/security/plugins/lists/README.md[lists] |README.md for developers working on the backend lists on how to get started using the CURL scripts in the scripts folder. @@ -815,7 +816,7 @@ Elastic. |Add tagging capability to saved objects -|{kib-repo}blob/{branch}/x-pack/plugins/screenshotting/README.md[screenshotting] +|{kib-repo}blob/{branch}/x-pack/platform/plugins/shared/screenshotting/README.md[screenshotting] |This plugin provides functionality to take screenshots of the Kibana pages. It uses Chromium and Puppeteer underneath to run the browser in headless mode. diff --git a/docs/discover/document-explorer.asciidoc b/docs/discover/document-explorer.asciidoc index 47b4a5bc3fcf..d026cf2930f1 100644 --- a/docs/discover/document-explorer.asciidoc +++ b/docs/discover/document-explorer.asciidoc @@ -36,7 +36,7 @@ In the pop-up, drag the column names to their new order. * To resize a column, drag the right edge of the column header until the column is the width that you want. + -Column widths are stored with a saved search. When you visualize saved searches on dashboards, the saved search appears the same as in **Discover**. +Column widths are stored with a Discover session. When you add a Discover session as a dashboard panel, it appears the same as in **Discover**. [float] [[document-explorer-density]] diff --git a/docs/discover/get-started-discover.asciidoc b/docs/discover/get-started-discover.asciidoc index ec44f977f4aa..f3ffcc92b582 100644 --- a/docs/discover/get-started-discover.asciidoc +++ b/docs/discover/get-started-discover.asciidoc @@ -293,24 +293,24 @@ Learn more about how to use ES|QL queries in <>. [float] [[save-discover-search]] -==== Save your search for later use +==== Save your Discover session for later use -Save your search so you can use it later, generate a CSV report, or use it to create visualizations, dashboards, and Canvas workpads. -Saving a search saves the query text, filters, +Save your Discover session so you can use it later, generate a CSV report, or use it to create visualizations, dashboards, and Canvas workpads. +Saving a Discover session saves the query text, filters, and current view of *Discover*, including the columns selected in the document table, the sort order, and the {data-source}. . In the application menu bar, click **Save**. -. Give your search a title and a description. +. Give your session a title and a description. -. Optionally store <> and the time range with the search. +. Optionally store <> and the time range with the session. . Click **Save**. [float] [[share-your-findings]] -==== Share your search +==== Share your Discover session To share your search and **Discover** view with a larger audience, click *Share* in the application menu bar. For detailed information about the sharing options, refer to <>. diff --git a/docs/discover/save-search.asciidoc b/docs/discover/save-search.asciidoc index 024fd97ab107..d661e8c01b83 100644 --- a/docs/discover/save-search.asciidoc +++ b/docs/discover/save-search.asciidoc @@ -1,9 +1,9 @@ [[save-open-search]] -== Save a search for reuse +== Save a Discover session for reuse -A saved search is a convenient way to reuse a search +A saved Discover session is a convenient way to reuse a search that you've created in *Discover*. -Saved searches are good for adding search results to a dashboard, +Discover sessions are good for saving a configured view of Discover to use later or adding search results to a dashboard, and can also serve as a foundation for building visualizations. [role="xpack"] @@ -16,27 +16,27 @@ displayed and the *Save* button is not visible. For more information, refer to < [role="screenshot"] image::discover/images/read-only-badge.png[Example of Discover's read only access indicator in Kibana's header] [float] -=== Save a search +=== Save a Discover session -By default, a saved search stores the query text, filters, and +By default, a Discover session stores the query text, filters, and current view of *Discover*, including the columns and sort order in the document table, and the {data-source}. -. Once you've created a search worth saving, click *Save* in the toolbar. -. Enter a name for the search. -. Optionally store <> and the time range with the search. +. Once you've created a view worth saving, click *Save* in the toolbar. +. Enter a name for the session. +. Optionally store <> and the time range with the session. . Click *Save*. -. To reload your search results in *Discover*, click *Open* in the toolbar, and select the saved search. +. To reload your search results in *Discover*, click *Open* in the toolbar, and select the saved Discover session. + -If the saved search is associated with a different {data-source} than is currently -selected, opening the saved search changes the selected {data-source}. The query language -used for the saved search is also automatically selected. +If the saved Discover session is associated with a different {data-source} than is currently +selected, opening the saved Discover session changes the selected {data-source}. The query language +used for the saved Discover session is also automatically selected. [float] -=== Duplicate a search -. In **Discover**, open the search that you want to duplicate. +=== Duplicate a Discover session +. In **Discover**, open the Discover session that you want to duplicate. . In the toolbar, click *Save*. -. Give the search a new name. -. Turn on **Save as new search**. +. Give the session a new name. +. Turn on **Save as new Discover session**. . Click *Save*. @@ -46,5 +46,5 @@ used for the saved search is also automatically selected. . Go to *Dashboards*. . Open or create the dashboard, then click *Edit*. . Click *Add from library*. -. From the *Types* dropdown, select *Saved search*. -. Select the saved search that you want to visualize, then click *X* to close the list. +. From the *Types* dropdown, select *Discover session*. +. Select the Discover session that you want to add, then click *X* to close the list. diff --git a/docs/discover/search-sessions.asciidoc b/docs/discover/search-sessions.asciidoc index fe1e945e676f..5d6b4a2d0043 100644 --- a/docs/discover/search-sessions.asciidoc +++ b/docs/discover/search-sessions.asciidoc @@ -52,7 +52,7 @@ image::images/search-session-awhile.png[Search Session indicator displaying the Once you save a search session, you can start a new search, navigate to a different application, or close the browser. -. To view your saved searches, go to the +. To view your saved search sessions, go to the *Search Sessions* management page using the navigation menu or the <>. For a saved or completed session, you can also open this view from the search sessions popup. diff --git a/docs/discover/search.asciidoc b/docs/discover/search.asciidoc index 439c5c443cc0..c7fde4159ec9 100644 --- a/docs/discover/search.asciidoc +++ b/docs/discover/search.asciidoc @@ -92,10 +92,10 @@ status:[400 TO 499] AND (extension:php OR extension:html) [[save-open-search]] -=== Save a search -A saved search persists your current view of Discover for later retrieval and reuse. You can reload a saved search into Discover, add it to a dashboard, and use it as the basis for a visualization. +=== Save a Discover session +A saved Discover session persists your current view of Discover for later retrieval and reuse. You can reload a saved session into Discover, add it to a dashboard, and use it as the basis for a visualization. -A saved search includes the query text, filters, and optionally, the time filter. A saved search also includes the selected columns in the document table, the sort order, and the current index pattern. +A Discover session includes the query text, filters, and optionally, the time filter. A Discover session also includes the selected columns in the document table, the sort order, and the current {data-source}. [role="xpack"] [[discover-read-only-access]] @@ -107,23 +107,23 @@ Kibana see <>. [role="screenshot"] image::discover/images/read-only-badge.png[Example of Discover's read only access indicator in Kibana's header] -==== Save a search -To save the current search: +==== Save a Discover session +To save the current session: . Click *Save* in the toolbar. -. Enter a name for the search and click *Save*. +. Enter a name for the session and click *Save*. -To import, export, and delete saved searches, go to the *Saved Objects* management page using the navigation menu or the <>. +To import, export, and delete saved Discover sessions, go to the *Saved Objects* management page using the navigation menu or the <>. -==== Open a saved search -To load a saved search into Discover: +==== Open a saved Discover session +To load a saved session into Discover: . Click *Open* in the toolbar. -. Select the search you want to open. +. Select the session you want to open. -If the saved search is associated with a different index pattern than is currently -selected, opening the saved search changes the selected index pattern. The query language -used for the saved search will also be automatically selected. +If the saved Discover session is associated with a different {data-source} than is currently +selected, opening the saved Discover session changes the selected {data-source}. The query language +used for the saved Discover session will also be automatically selected. [[save-load-delete-query]] === Save a query @@ -133,7 +133,7 @@ A saved query is a portable collection of query text and filters that you can re * View the results of the same query in multiple apps * Share your query -Saved queries don't include information specific to Discover, such as the currently selected columns in the document table, the sort order, and the index pattern. If you want to save your current view of Discover for later retrieval and reuse, create a <> instead. +Saved queries don't include information specific to Discover, such as the currently selected columns in the document table, the sort order, and the {data-source}. If you want to save your current view of Discover for later retrieval and reuse, create a <> instead. [role="xpack"] ==== Read-only access diff --git a/docs/fleet/fleet.asciidoc b/docs/fleet/fleet.asciidoc index 52c282555700..366d28fae3f5 100644 --- a/docs/fleet/fleet.asciidoc +++ b/docs/fleet/fleet.asciidoc @@ -18,7 +18,7 @@ It is recommended for advanced users only. [role="screenshot"] image::fleet/images/fleet-start.png[{fleet} app in {kib}] -Most integration content installed by {fleet} isn’t editable. This content is tagged with a **Managed** badge in the {kib} UI. Managed content itself cannot be edited or deleted, however managed visualizations, dashboards, and saved searches can be cloned. +Most integration content installed by {fleet} isn’t editable. This content is tagged with a **Managed** badge in the {kib} UI. Managed content itself cannot be edited or deleted, however managed visualizations, dashboards, and Discover sessions can be cloned. [role="screenshot"] image::fleet/images/system-managed.png[An image of the new managed badge.] @@ -37,7 +37,7 @@ To clone a dashboard: . Click *Save and return* after editing the dashboard. . Click *Save*. -To clone managed content relating to specific visualization editors, such as Lens, TSVB, and Maps, view the visualization in the editor then begin to make edits. Unlike cloning dashboards, and dashboard panels, the cloned content retains the original configurations. Once finished you are prompted to save the edits as a new visualization. The same applies for altering any saved searches in a managed visualization. +To clone managed content relating to specific visualization editors, such as Lens, TSVB, and Maps, view the visualization in the editor then begin to make edits. Unlike cloning dashboards, and dashboard panels, the cloned content retains the original configurations. Once finished you are prompted to save the edits as a new visualization. The same applies for altering any linked Discover sessions in a managed visualization. [float] == Get started diff --git a/docs/management/advanced-options.asciidoc b/docs/management/advanced-options.asciidoc index ef6d6306792b..5f51a86b01ae 100644 --- a/docs/management/advanced-options.asciidoc +++ b/docs/management/advanced-options.asciidoc @@ -311,7 +311,7 @@ Sets the maximum number of rows for the entire document table. This is the maxim [[discover-searchonpageload]]`discover:searchOnPageLoad`:: Controls whether a search is executed when *Discover* first loads. This setting -does not have an effect when loading a saved search. +does not have an effect when loading a saved Discover session. [[discover:showFieldStatistics]]`discover:showFieldStatistics`:: beta[] Enables the Field statistics view. Examine details such as @@ -324,10 +324,10 @@ Controls the display of multi-fields in the expanded document view. The default sort direction for time-based data views. [[doctable-hidetimecolumn]]`doc_table:hideTimeColumn`:: -Hides the "Time" column in *Discover* and in all saved searches on dashboards. +Hides the "Time" column in *Discover* and in all Discover session panels on dashboards. [[doctable-highlight]]`doc_table:highlight`:: -Highlights results in *Discover* and saved searches on dashboards. Highlighting +Highlights search results in *Discover* and Discover session panels on dashboards. Highlighting slows requests when working on big documents. diff --git a/docs/search/playground/index.asciidoc b/docs/search/playground/index.asciidoc index 72d8eccab47c..465637e79bc0 100644 --- a/docs/search/playground/index.asciidoc +++ b/docs/search/playground/index.asciidoc @@ -18,7 +18,16 @@ Refer to the following for more advanced topics: * <> * <> -* <> +* <> + +.🍿 Getting started videos +*********************** +Watch these video tutorials to help you get started: + +* https://www.youtube.com/watch?v=zTHgJ3rhe10[Getting Started] +* https://www.youtube.com/watch?v=ZtxoASFvkno[Using Playground with local LLMs] +*********************** + [float] [[playground-how-it-works]] @@ -259,4 +268,4 @@ Once you've got {x} up and running, and you've tested out the chat interface, yo include::playground-context.asciidoc[] include::playground-query.asciidoc[] -include::playground-troubleshooting.asciidoc[] \ No newline at end of file +include::playground-troubleshooting.asciidoc[] diff --git a/docs/setup/configuring-reporting.asciidoc b/docs/setup/configuring-reporting.asciidoc index bcef6a026625..8711185dbc1b 100644 --- a/docs/setup/configuring-reporting.asciidoc +++ b/docs/setup/configuring-reporting.asciidoc @@ -121,8 +121,8 @@ PUT :/api/security/role/custom_reporting_user // CONSOLE <1> Grants access to generate PNG and PDF reports in *Dashboard*. -<2> Grants access to generate CSV reports from saved search panels in *Dashboard*. -<3> Grants access to generate CSV reports from saved searches in *Discover*. +<2> Grants access to generate CSV reports from saved Discover session panels in *Dashboard*. +<3> Grants access to generate CSV reports from saved Discover sessions in *Discover*. <4> Grants access to generate PDF reports in *Canvas*. <5> Grants access to generate PNG and PDF reports in *Visualize Library*. @@ -157,8 +157,8 @@ PUT localhost:5601/api/security/role/custom_reporting_user --------------------------------------------------------------- // CONSOLE -<1> Grants access to generate CSV reports from saved searches in *Discover*. -<2> Grants access to generate CSV reports from saved search panels in *Dashboard*. +<1> Grants access to generate CSV reports from saved Discover sessions in *Discover*. +<2> Grants access to generate CSV reports from saved Discover session panels in *Dashboard*. [float] [[grant-user-access-external-provider]] diff --git a/docs/user/dashboard/aggregation-based.asciidoc b/docs/user/dashboard/aggregation-based.asciidoc index f27d60928e6f..e3f1f0bea671 100644 --- a/docs/user/dashboard/aggregation-based.asciidoc +++ b/docs/user/dashboard/aggregation-based.asciidoc @@ -7,7 +7,7 @@ With aggregation-based visualizations, you can: * Split charts up to three aggregation levels, which is more than *Lens* and *TSVB* * Create visualization with non-time series data -* Use a <> as an input +* Use a <> as an input * Sort data tables and use the summary row and percentage column features * Assign colors to data series * Extend features with plugins @@ -112,7 +112,7 @@ Choose the type of visualization you want to create, then use the editor to conf .. Select the data source you want to visualize. + -NOTE: There is no performance impact on the data source you select. For example, *Discover* saved searches perform the same as {data-sources}. +NOTE: There is no performance impact on the data source you select. For example, saved Discover sessions perform the same as {data-sources}. . Add the <> you want to visualize using the editor, then click *Update*. + diff --git a/docs/user/dashboard/create-visualizations.asciidoc b/docs/user/dashboard/create-visualizations.asciidoc index 815f46d5711e..f0cf95733a97 100644 --- a/docs/user/dashboard/create-visualizations.asciidoc +++ b/docs/user/dashboard/create-visualizations.asciidoc @@ -163,9 +163,9 @@ To enable series data interactions, configure <> data in *Discover*. +* *Discover session interactions* — Opens <> data in *Discover*. + -To use saved search interactions, open the panel menu, then click *More > View saved search*. +To use saved Discover session interactions, open the panel menu, then click *More > View Discover session*. [[edit-panels]] === Edit panels diff --git a/docs/user/dashboard/lens.asciidoc b/docs/user/dashboard/lens.asciidoc index 3c2a120d167d..525ff8d7bfb6 100644 --- a/docs/user/dashboard/lens.asciidoc +++ b/docs/user/dashboard/lens.asciidoc @@ -668,10 +668,10 @@ For area, line, and bar charts, press Shift, then click the series in the legend [discrete] [[is-it-possible-to-use-saved-serches-in-lens]] -.*How do I visualize saved searches?* +.*How do I visualize saved Discover sessions?* [%collapsible] ==== -Visualizing saved searches in unsupported. +Visualizing saved Discover sessions in unsupported. ==== [discrete] diff --git a/docs/user/dashboard/tsvb.asciidoc b/docs/user/dashboard/tsvb.asciidoc index e8e7cec48800..15433b19b6fc 100644 --- a/docs/user/dashboard/tsvb.asciidoc +++ b/docs/user/dashboard/tsvb.asciidoc @@ -233,7 +233,7 @@ For example `https://example.org/{{key}}` This instructs TSVB to substitute the value from your visualization wherever it sees `{{key}}`. -If your data contain reserved or invalid URL characters such as "#" or "&", you should apply a transform to URL-encode the key like this `{{encodeURIComponent key}}`. If you are dynamically constructing a drilldown to another location in Kibana (for example, clicking a table row takes to you a value-scoped saved search), you will likely want to Rison-encode your key as it may contain invalid Rison characters. (https://github.com/Nanonid/rison#rison---compact-data-in-uris[Rison] is the serialization format many parts of Kibana use to store information in their URL.) +If your data contain reserved or invalid URL characters such as "#" or "&", you should apply a transform to URL-encode the key like this `{{encodeURIComponent key}}`. If you are dynamically constructing a drilldown to another location in Kibana (for example, clicking a table row takes to you a value-scoped Discover session), you will likely want to Rison-encode your key as it may contain invalid Rison characters. (https://github.com/Nanonid/rison#rison---compact-data-in-uris[Rison] is the serialization format many parts of Kibana use to store information in their URL.) For example: `discover#/view/0ac50180-82d9-11ec-9f4a-55de56b00cc0?_a=(filters:!((query:(match_phrase:(foo.keyword:{{rison key}})))))` diff --git a/docs/user/management.asciidoc b/docs/user/management.asciidoc index c46786b98829..b503dbdc2d0e 100644 --- a/docs/user/management.asciidoc +++ b/docs/user/management.asciidoc @@ -85,7 +85,7 @@ You can add and remove remote clusters, and check their connectivity. | <> | Monitor the generation of reports—PDF, PNG, and CSV—and download reports that you previously generated. -A report can contain a dashboard, visualization, saved search, or Canvas workpad. +A report can contain a dashboard, visualization, table with Discover search results, or Canvas workpad. | Machine Learning Jobs | View, export, and import your <> and diff --git a/docs/user/ml/index.asciidoc b/docs/user/ml/index.asciidoc index 91227055fa8a..92a28a1fdb0c 100644 --- a/docs/user/ml/index.asciidoc +++ b/docs/user/ml/index.asciidoc @@ -168,7 +168,7 @@ It makes it easy to find and investigate causes of unusual spikes or drops by us Examine the histogram chart of the log rates for a given {data-source}, and find the reason behind a particular change possibly in millions of log events across multiple fields and values. You can find log rate analysis embedded in multiple applications. -In {kib}, you can find it under **{ml-app}** > **AIOps Labs** or by using the <>. Here, you can select the {data-source} or saved search that you want to analyze. +In {kib}, you can find it under **{ml-app}** > **AIOps Labs** or by using the <>. Here, you can select the {data-source} or saved Discover session that you want to analyze. [role="screenshot"] image::user/ml/images/ml-log-rate-analysis-before.png[Log event histogram chart] @@ -203,7 +203,7 @@ and an example document that matches the category. //end::log-pattern-analysis-intro[] You can find log pattern analysis under **{ml-app}** > **AIOps Labs** or by using the <>. -Here, you can select the {data-source} or saved search that you want to analyze, or in +Here, you can select the {data-source} or saved Discover session that you want to analyze, or in **Discover** as an available action for any text field. [role="screenshot"] @@ -228,7 +228,7 @@ to detect distribution changes, trend changes, and other statistically significant change points in a metric of your time series data. You can find change point detection under **{ml-app}** > **AIOps Labs** or by using the <>. -Here, you can select the {data-source} or saved search that you want to analyze. +Here, you can select the {data-source} or saved Discover session that you want to analyze. [role="screenshot"] image::user/ml/images/ml-change-point-detection.png[Change point detection UI] diff --git a/docs/user/reporting/automating-report-generation.asciidoc b/docs/user/reporting/automating-report-generation.asciidoc index b4334b7c7ea8..0b773decd60a 100644 --- a/docs/user/reporting/automating-report-generation.asciidoc +++ b/docs/user/reporting/automating-report-generation.asciidoc @@ -24,7 +24,7 @@ To create the POST URL for CSV reports: . Go to *Discover*. -. Open the saved search you want to share. +. Open the saved Discover session you want to share. . In the toolbar, click *Share > Export > Copy POST URL*. @@ -54,7 +54,7 @@ If you experience issues with the deprecated report URLs after you upgrade {kib} * *Dashboard* reports: `/api/reporting/generate/dashboard/` * *Visualize Library* reports: `/api/reporting/generate/visualization/` -* *Discover* saved search reports: `/api/reporting/generate/search/` +* *Discover* reports: `/api/reporting/generate/search/` IMPORTANT: In earlier {kib} versions, you could use the `&sync` parameter to append to report URLs that held the request open until the document was fully generated. The `&sync` parameter is now unsupported. If you use the `&sync` parameter in Watcher, you must update the parameter. diff --git a/docs/user/reporting/index.asciidoc b/docs/user/reporting/index.asciidoc index 4425cc45d9b4..7a52f5d77b10 100644 --- a/docs/user/reporting/index.asciidoc +++ b/docs/user/reporting/index.asciidoc @@ -4,16 +4,16 @@ [partintro] -- -:frontmatter-description: {kib} provides you with several options to share *Discover* saved searches, dashboards, *Visualize Library* visualizations, and *Canvas* workpads with others, or on a website. +:frontmatter-description: {kib} provides you with several options to share *Discover* sessions, dashboards, *Visualize Library* visualizations, and *Canvas* workpads with others, or on a website. :frontmatter-tags-products: [kibana] -{kib} provides you with several options to share *Discover* saved searches, dashboards, *Visualize Library* visualizations, and *Canvas* workpads. These sharing options are available from the *Share* menu in the toolbar. +{kib} provides you with several options to share *Discover* sessions, dashboards, *Visualize Library* visualizations, and *Canvas* workpads. These sharing options are available from the *Share* menu in the toolbar. [float] [[share-a-direct-link]] == Share with a direct link -You can share direct links to saved searches, dashboards, and visualizations. When clicking **Share**, look for the **Links** tab to get the shareable link and copy it. +You can share direct links to saved Discover sessions, dashboards, and visualizations. When clicking **Share**, look for the **Links** tab to get the shareable link and copy it. TIP: When sharing an object with unsaved changes, you get a temporary link that might break in the future, for example in case of upgrade. Save the object to get a permanent link instead. @@ -29,13 +29,13 @@ image::https://images.contentstack.io/v3/assets/bltefdd0b53724fa2ce/blt49f2b5a80 NOTE: For more information on how to configure reporting in {kib}, refer to <> -Create and download PDF, PNG, or CSV reports of saved searches, dashboards, visualizations, and workpads. +Create and download PDF, PNG, or CSV reports of saved Discover sessions, dashboards, visualizations, and workpads. * *PDF* — Generate and download PDF files of dashboards, visualizations, and *Canvas* workpads. PDF reports are a link:https://www.elastic.co/subscriptions[subscription feature]. * *PNG* — Generate and download PNG files of dashboards and visualizations. PNG reports are a link:https://www.elastic.co/subscriptions[subscription feature]. -* *CSV Reports* — Generate CSV reports of saved searches. <>. +* *CSV Reports* — Generate CSV reports of saved Discover sessions. <>. * *CSV Download* — Generate and download CSV files of *Lens* visualizations. @@ -44,7 +44,7 @@ Create and download PDF, PNG, or CSV reports of saved searches, dashboards, visu [[reporting-layout-sizing]] The layout and size of the report depends on what you are sharing. -For saved searches, dashboards, and visualizations, the layout depends on the size of the panels. +For saved Discover sessions, dashboards, and visualizations, the layout depends on the size of the panels. For workpads, the layout depends on the size of the worksheet dimensions. To change the output size, change the size of the browser, which resizes the shareable container before the report generates. It might take some trial and error before you're satisfied. @@ -54,13 +54,13 @@ In the following dashboard, the shareable container is highlighted: [role="screenshot"] image::user/reporting/images/shareable-container.png["Shareable Container"] -. Open the saved search, dashboard, visualization, or workpad you want to share. +. Open the saved Discover session, dashboard, visualization, or workpad you want to share. . From the toolbar, click *Share*, then select the report option. * If you are creating dashboard PDFs, select *For printing* to create printer-friendly PDFs with multiple A4 portrait pages and two visualizations per page. + -NOTE: When you create a dashboard report that includes a data table or saved search, the PDF includes only the visible data. +NOTE: When you create a dashboard report that includes a data table or Discover session, the PDF includes only the visible data. * If you are creating workpad PDFs, select *Full page layout* to create PDFs without margins that surround the workpad. diff --git a/examples/content_management_examples/public/examples/finder/finder_app.tsx b/examples/content_management_examples/public/examples/finder/finder_app.tsx index b8aaa6fe5f34..dda034e71118 100644 --- a/examples/content_management_examples/public/examples/finder/finder_app.tsx +++ b/examples/content_management_examples/public/examples/finder/finder_app.tsx @@ -37,7 +37,7 @@ export const FinderApp = (props: { { type: `search`, getIconForSavedObject: () => 'discoverApp', - name: 'Saved search', + name: 'Discover session', }, { type: 'index-pattern', diff --git a/oas_docs/bundle.json b/oas_docs/bundle.json index 320730edc972..3e3d47df0166 100644 --- a/oas_docs/bundle.json +++ b/oas_docs/bundle.json @@ -39790,7 +39790,7 @@ }, "/api/spaces/_copy_saved_objects": { "post": { - "description": "It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved searches, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.

[Required authorization] Route required privileges: ALL of [copySavedObjectsToSpaces].", + "description": "It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved Discover sessions, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.

[Required authorization] Route required privileges: ALL of [copySavedObjectsToSpaces].", "operationId": "post-spaces-copy-saved-objects", "parameters": [ { diff --git a/oas_docs/output/kibana.yaml b/oas_docs/output/kibana.yaml index f12014443bb0..5845ba56ae89 100644 --- a/oas_docs/output/kibana.yaml +++ b/oas_docs/output/kibana.yaml @@ -37372,7 +37372,7 @@ paths: - roles /api/spaces/_copy_saved_objects: post: - description: 'It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved searches, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.

[Required authorization] Route required privileges: ALL of [copySavedObjectsToSpaces].' + description: 'It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved Discover sessions, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.

[Required authorization] Route required privileges: ALL of [copySavedObjectsToSpaces].' operationId: post-spaces-copy-saved-objects parameters: - description: A required header to protect against CSRF attacks diff --git a/oas_docs/scripts/merge_ess_oas.js b/oas_docs/scripts/merge_ess_oas.js index 3d96ad5b5933..df0b6e5a4ac0 100644 --- a/oas_docs/scripts/merge_ess_oas.js +++ b/oas_docs/scripts/merge_ess_oas.js @@ -27,9 +27,9 @@ const { REPO_ROOT } = require('@kbn/repo-info'); // Security solution `${REPO_ROOT}/x-pack/solutions/security/plugins/security_solution/docs/openapi/ess/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-lists-common/docs/openapi/ess/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/ess/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/*.schema.yaml`, `${REPO_ROOT}/x-pack/platform/packages/shared/kbn-elastic-assistant-common/docs/openapi/ess/*.schema.yaml`, `${REPO_ROOT}/x-pack/platform/plugins/shared/osquery/docs/openapi/ess/*.schema.yaml`, ], diff --git a/oas_docs/scripts/merge_serverless_oas.js b/oas_docs/scripts/merge_serverless_oas.js index 2f92195502db..343487d8fc4f 100644 --- a/oas_docs/scripts/merge_serverless_oas.js +++ b/oas_docs/scripts/merge_serverless_oas.js @@ -25,9 +25,9 @@ const { REPO_ROOT } = require('@kbn/repo-info'); // Security solution `${REPO_ROOT}/x-pack/solutions/security/plugins/security_solution/docs/openapi/serverless/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-lists-common/docs/openapi/serverless/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/*.schema.yaml`, - `${REPO_ROOT}/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/serverless/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/*.schema.yaml`, + `${REPO_ROOT}/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/*.schema.yaml`, `${REPO_ROOT}/x-pack/platform/packages/shared/kbn-elastic-assistant-common/docs/openapi/serverless/*.schema.yaml`, `${REPO_ROOT}/x-pack/platform/plugins/shared/osquery/docs/openapi/serverless/*.schema.yaml`, ], diff --git a/package.json b/package.json index ee007b076af4..a60710029650 100644 --- a/package.json +++ b/package.json @@ -619,7 +619,7 @@ "@kbn/license-management-plugin": "link:x-pack/platform/plugins/shared/license_management", "@kbn/licensing-plugin": "link:x-pack/plugins/licensing", "@kbn/links-plugin": "link:src/plugins/links", - "@kbn/lists-plugin": "link:x-pack/plugins/lists", + "@kbn/lists-plugin": "link:x-pack/solutions/security/plugins/lists", "@kbn/llm-tasks-plugin": "link:x-pack/platform/plugins/shared/ai_infra/llm_tasks", "@kbn/locator-examples-plugin": "link:examples/locator_examples", "@kbn/locator-explorer-plugin": "link:examples/locator_explorer", @@ -713,7 +713,7 @@ "@kbn/observability-utils-server": "link:x-pack/packages/observability/observability_utils/observability_utils_server", "@kbn/oidc-provider-plugin": "link:x-pack/test/security_api_integration/plugins/oidc_provider", "@kbn/open-telemetry-instrumented-plugin": "link:test/common/plugins/otel_metrics", - "@kbn/openapi-common": "link:packages/kbn-openapi-common", + "@kbn/openapi-common": "link:src/platform/packages/shared/kbn-openapi-common", "@kbn/osquery-io-ts-types": "link:src/platform/packages/shared/kbn-osquery-io-ts-types", "@kbn/osquery-plugin": "link:x-pack/platform/plugins/shared/osquery", "@kbn/paertial-results-example-plugin": "link:examples/partial_results_example", @@ -796,7 +796,7 @@ "@kbn/screenshot-mode-example-plugin": "link:examples/screenshot_mode_example", "@kbn/screenshot-mode-plugin": "link:src/plugins/screenshot_mode", "@kbn/screenshotting-example-plugin": "link:x-pack/examples/screenshotting_example", - "@kbn/screenshotting-plugin": "link:x-pack/plugins/screenshotting", + "@kbn/screenshotting-plugin": "link:x-pack/platform/plugins/shared/screenshotting", "@kbn/screenshotting-server": "link:packages/kbn-screenshotting-server", "@kbn/search-api-keys-components": "link:packages/kbn-search-api-keys-components", "@kbn/search-api-keys-server": "link:packages/kbn-search-api-keys-server", @@ -839,26 +839,26 @@ "@kbn/security-solution-upselling": "link:x-pack/solutions/security/packages/upselling", "@kbn/security-test-endpoints-plugin": "link:x-pack/test/security_functional/plugins/test_endpoints", "@kbn/security-ui-components": "link:x-pack/packages/security/ui_components", - "@kbn/securitysolution-autocomplete": "link:packages/kbn-securitysolution-autocomplete", + "@kbn/securitysolution-autocomplete": "link:x-pack/solutions/security/packages/kbn-securitysolution-autocomplete", "@kbn/securitysolution-data-table": "link:x-pack/solutions/security/packages/data_table", "@kbn/securitysolution-ecs": "link:src/platform/packages/shared/kbn-securitysolution-ecs", - "@kbn/securitysolution-endpoint-exceptions-common": "link:packages/kbn-securitysolution-endpoint-exceptions-common", - "@kbn/securitysolution-es-utils": "link:packages/kbn-securitysolution-es-utils", - "@kbn/securitysolution-exception-list-components": "link:packages/kbn-securitysolution-exception-list-components", - "@kbn/securitysolution-exceptions-common": "link:packages/kbn-securitysolution-exceptions-common", - "@kbn/securitysolution-hook-utils": "link:packages/kbn-securitysolution-hook-utils", - "@kbn/securitysolution-io-ts-alerting-types": "link:packages/kbn-securitysolution-io-ts-alerting-types", - "@kbn/securitysolution-io-ts-list-types": "link:packages/kbn-securitysolution-io-ts-list-types", - "@kbn/securitysolution-io-ts-types": "link:packages/kbn-securitysolution-io-ts-types", - "@kbn/securitysolution-io-ts-utils": "link:packages/kbn-securitysolution-io-ts-utils", - "@kbn/securitysolution-list-api": "link:packages/kbn-securitysolution-list-api", - "@kbn/securitysolution-list-constants": "link:packages/kbn-securitysolution-list-constants", - "@kbn/securitysolution-list-hooks": "link:packages/kbn-securitysolution-list-hooks", - "@kbn/securitysolution-list-utils": "link:packages/kbn-securitysolution-list-utils", - "@kbn/securitysolution-lists-common": "link:packages/kbn-securitysolution-lists-common", - "@kbn/securitysolution-rules": "link:packages/kbn-securitysolution-rules", - "@kbn/securitysolution-t-grid": "link:packages/kbn-securitysolution-t-grid", - "@kbn/securitysolution-utils": "link:packages/kbn-securitysolution-utils", + "@kbn/securitysolution-endpoint-exceptions-common": "link:x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common", + "@kbn/securitysolution-es-utils": "link:src/platform/packages/shared/kbn-securitysolution-es-utils", + "@kbn/securitysolution-exception-list-components": "link:x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components", + "@kbn/securitysolution-exceptions-common": "link:x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common", + "@kbn/securitysolution-hook-utils": "link:x-pack/solutions/security/packages/kbn-securitysolution-hook-utils", + "@kbn/securitysolution-io-ts-alerting-types": "link:x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types", + "@kbn/securitysolution-io-ts-list-types": "link:x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types", + "@kbn/securitysolution-io-ts-types": "link:src/platform/packages/shared/kbn-securitysolution-io-ts-types", + "@kbn/securitysolution-io-ts-utils": "link:src/platform/packages/shared/kbn-securitysolution-io-ts-utils", + "@kbn/securitysolution-list-api": "link:x-pack/solutions/security/packages/kbn-securitysolution-list-api", + "@kbn/securitysolution-list-constants": "link:x-pack/solutions/security/packages/kbn-securitysolution-list-constants", + "@kbn/securitysolution-list-hooks": "link:x-pack/solutions/security/packages/kbn-securitysolution-list-hooks", + "@kbn/securitysolution-list-utils": "link:x-pack/solutions/security/packages/kbn-securitysolution-list-utils", + "@kbn/securitysolution-lists-common": "link:x-pack/solutions/security/packages/kbn-securitysolution-lists-common", + "@kbn/securitysolution-rules": "link:src/platform/packages/shared/kbn-securitysolution-rules", + "@kbn/securitysolution-t-grid": "link:x-pack/solutions/security/packages/kbn-securitysolution-t-grid", + "@kbn/securitysolution-utils": "link:x-pack/solutions/security/packages/kbn-securitysolution-utils", "@kbn/server-http-tools": "link:packages/kbn-server-http-tools", "@kbn/server-route-repository": "link:src/platform/packages/shared/kbn-server-route-repository", "@kbn/server-route-repository-client": "link:src/platform/packages/shared/kbn-server-route-repository-client", @@ -1027,7 +1027,7 @@ "@kbn/watcher-plugin": "link:x-pack/platform/plugins/private/watcher", "@kbn/xstate-utils": "link:packages/kbn-xstate-utils", "@kbn/zod": "link:packages/kbn-zod", - "@kbn/zod-helpers": "link:packages/kbn-zod-helpers", + "@kbn/zod-helpers": "link:src/platform/packages/shared/kbn-zod-helpers", "@langchain/aws": "^0.1.2", "@langchain/community": "0.3.14", "@langchain/core": "^0.3.16", diff --git a/packages/core/http/core-http-server-internal/src/http_config.test.ts b/packages/core/http/core-http-server-internal/src/http_config.test.ts index 4ba13489552b..fa2fbe7ad9f3 100644 --- a/packages/core/http/core-http-server-internal/src/http_config.test.ts +++ b/packages/core/http/core-http-server-internal/src/http_config.test.ts @@ -517,9 +517,9 @@ describe('versioned', () => { ).toThrow(/failed validation/); }); - it('defaults version resolution "none" when in dev', () => { + it('defaults version resolution "oldest" when in dev', () => { expect(config.schema.validate({}, { dev: true })).toMatchObject({ - versioned: { versionResolution: 'none' }, + versioned: { versionResolution: 'oldest' }, }); }); }); diff --git a/packages/core/http/core-http-server-internal/src/http_config.ts b/packages/core/http/core-http-server-internal/src/http_config.ts index 11c1afc41033..4ba9bcb9e88b 100644 --- a/packages/core/http/core-http-server-internal/src/http_config.ts +++ b/packages/core/http/core-http-server-internal/src/http_config.ts @@ -213,7 +213,7 @@ const configSchema = schema.object( * Which handler resolution algo to use for public routes: "newest" or "oldest". * * @note Internal routes always require a version to be specified. - * @note in development we have an additional option "none" which is also the default in dev. + * @note in development we have an additional option "none". * This prevents any fallbacks and requires that a version specified. * Useful for ensuring that a given client always specifies a version. */ @@ -221,7 +221,7 @@ const configSchema = schema.object( schema.contextRef('dev'), true, schema.oneOf([schema.literal('newest'), schema.literal('oldest'), schema.literal('none')], { - defaultValue: 'none', + defaultValue: 'oldest', }), schema.oneOf([schema.literal('newest'), schema.literal('oldest')], { defaultValue: 'oldest', diff --git a/packages/core/http/core-http-server-internal/src/http_server.ts b/packages/core/http/core-http-server-internal/src/http_server.ts index 14cc4397ebce..1d80c9c4ab0d 100644 --- a/packages/core/http/core-http-server-internal/src/http_server.ts +++ b/packages/core/http/core-http-server-internal/src/http_server.ts @@ -93,7 +93,11 @@ function startEluMeasurement( if ( eluMonitorOptions.logging.enabled && active >= eluMonitorOptions.logging.threshold.ela && - utilization >= eluMonitorOptions.logging.threshold.elu + utilization >= eluMonitorOptions.logging.threshold.elu && + // static js and js.map assets are generating lots of noise for this + // event loop check, hiding endpoint slowness which are higher priority + // remove this check once endpoints slowness is addressed + !['js', 'js.map'].some((ext) => path.endsWith(ext)) ) { log.warn( `Event loop utilization for ${path} exceeded threshold of ${elaThreshold}ms (${Math.round( diff --git a/packages/kbn-babel-preset/styled_components_files.js b/packages/kbn-babel-preset/styled_components_files.js index 2a74c5b60f18..6f6e1ddbb14a 100644 --- a/packages/kbn-babel-preset/styled_components_files.js +++ b/packages/kbn-babel-preset/styled_components_files.js @@ -16,12 +16,13 @@ module.exports = { /packages[\/\\]kbn-ui-shared-deps-(npm|src)[\/\\]/, /src[\/\\]plugins[\/\\](kibana_react)[\/\\]/, /x-pack[\/\\]solutions[\/\\]observability[\/\\]plugins[\/\\](exploratory_view|investigate|investigate_app|observability|observability_ai_assistant_app|observability_ai_assistant_management|observability_solution|serverless_observability|streams|streams_app|synthetics|uptime|ux)[\/\\]/, - /x-pack[\/\\]plugins[\/\\](observability_solution\/apm|beats_management|fleet|lists|observability_solution\/observability|observability_solution\/observability_shared|observability_solution\/exploratory_view|security_solution|timelines|observability_solution\/synthetics|observability_solution\/ux|observability_solution\/uptime)[\/\\]/, - /x-pack[\/\\]solutions[\/\\]security[\/\\]plugins[\/\\](observability_solution\/apm|beats_management|fleet|observability_solution\/infra|lists|observability_solution\/observability|observability_solution\/observability_shared|observability_solution\/exploratory_view|security_solution|timelines|observability_solution\/synthetics|observability_solution\/ux|observability_solution\/uptime)[\/\\]/, + /x-pack[\/\\]plugins[\/\\](beats_management|fleet|observability_solution\/observability|observability_solution\/observability_shared|observability_solution\/exploratory_view|security_solution|timelines|observability_solution\/synthetics|observability_solution\/ux|observability_solution\/uptime)[\/\\]/, + /x-pack[\/\\]solutions[\/\\]security[\/\\]plugins[\/\\](beats_management|fleet|lists|observability_solution\/observability|observability_solution\/observability_shared|observability_solution\/exploratory_view|security_solution|timelines|observability_solution\/synthetics|observability_solution\/ux|observability_solution\/uptime)[\/\\]/, /x-pack[\/\\]test[\/\\]plugin_functional[\/\\]plugins[\/\\]resolver_test[\/\\]/, /x-pack[\/\\]packages[\/\\]elastic_assistant[\/\\]/, /x-pack[\/\\]solutions[\/\\]security[\/\\]packages[\/\\]ecs_data_quality_dashboard[\/\\]/, /x-pack[\/\\]solutions[\/\\]security[\/\\]plugins[\/\\]security_solution[\/\\]/, /x-pack[\/\\]platform[\/\\]packages[\/\\]shared[\/\\]kbn-elastic-assistant[\/\\]/, + /x-pack[\/\\]solutions[\/\\]security[\/\\]plugins[\/\\]lists/, ], }; diff --git a/packages/kbn-cli-dev-mode/src/watcher.ts b/packages/kbn-cli-dev-mode/src/watcher.ts index 6dc11371d958..193458495aa2 100644 --- a/packages/kbn-cli-dev-mode/src/watcher.ts +++ b/packages/kbn-cli-dev-mode/src/watcher.ts @@ -19,7 +19,7 @@ import { Log } from './log'; const packageMatcher = makeMatcher([ '**/*', '!**/.*', - '!x-pack/plugins/screenshotting/chromium/**', + '!x-pack/platform/plugins/shared/screenshotting/chromium/**', '!x-pack/plugins/canvas/shareable_runtime/**', ]); diff --git a/packages/kbn-openapi-common/jest.config.js b/packages/kbn-openapi-common/jest.config.js deleted file mode 100644 index c8e533f9d7ed..000000000000 --- a/packages/kbn-openapi-common/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test/jest_node', - rootDir: '../..', - roots: ['/packages/kbn-openapi-common'], -}; diff --git a/packages/kbn-openapi-common/scripts/openapi_generate.js b/packages/kbn-openapi-common/scripts/openapi_generate.js deleted file mode 100644 index 07b7c4c0e4a0..000000000000 --- a/packages/kbn-openapi-common/scripts/openapi_generate.js +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { resolve } = require('path'); -const { generate } = require('@kbn/openapi-generator'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await generate({ - title: 'OpenAPI Common Schemas (kbn-openapi-common)', - rootDir: ROOT, - sourceGlob: './schemas/**/*.schema.yaml', - templateName: 'zod_operation_schema', - }); -})(); diff --git a/packages/kbn-openapi-common/tsconfig.json b/packages/kbn-openapi-common/tsconfig.json deleted file mode 100644 index 29a271ba4840..000000000000 --- a/packages/kbn-openapi-common/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "exclude": ["target/**/*"], - "extends": "../../tsconfig.base.json", - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/zod", - "@kbn/zod-helpers", - ] -} diff --git a/packages/kbn-saved-search-component/README.md b/packages/kbn-saved-search-component/README.md index 296ddb9079bc..61ec5a6cd8a9 100644 --- a/packages/kbn-saved-search-component/README.md +++ b/packages/kbn-saved-search-component/README.md @@ -1,6 +1,6 @@ # @kbn/saved-search-component -A component wrapper around Discover's Saved Search embeddable. This can be used in solutions without being within a Dasboard context. +A component wrapper around Discover session embeddable. This can be used in solutions without being within a Dasboard context. This can be used to render a context-aware (logs etc) "document table". diff --git a/packages/kbn-search-api-panels/components/cloud_details.tsx b/packages/kbn-search-api-panels/components/cloud_details.tsx index df2cc6bb6837..0c406b4c3185 100644 --- a/packages/kbn-search-api-panels/components/cloud_details.tsx +++ b/packages/kbn-search-api-panels/components/cloud_details.tsx @@ -97,7 +97,7 @@ export const CloudDetailsPanel = ({ - + { name: 'indexName-name', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: false, }, @@ -103,7 +103,7 @@ describe('createConnectorDocument', () => { name: 'indexName-name', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: false, }, diff --git a/packages/kbn-securitysolution-autocomplete/index.ts b/packages/kbn-securitysolution-autocomplete/index.ts deleted file mode 100644 index e47113719176..000000000000 --- a/packages/kbn-securitysolution-autocomplete/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/check_empty_value'; -export * from './src/es_field_selector'; -export * from './src/field_value_exists'; -export * from './src/field_value_lists'; -export * from './src/field_value_match'; -export * from './src/field_value_match_any'; -export * from './src/field_value_wildcard'; -export * from './src/filter_field_to_list'; -export * from './src/get_generic_combo_box_props'; -export * from './src/get_operators'; -export * from './src/hooks'; -export * from './src/operator'; -export * from './src/param_is_valid'; -export * from './src/param_contains_space'; - -export { default as autoCompletei18n } from './src/translations'; diff --git a/packages/kbn-securitysolution-autocomplete/jest.config.js b/packages/kbn-securitysolution-autocomplete/jest.config.js deleted file mode 100644 index b7d1e59f7786..000000000000 --- a/packages/kbn-securitysolution-autocomplete/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-autocomplete'], -}; diff --git a/packages/kbn-securitysolution-autocomplete/package.json b/packages/kbn-securitysolution-autocomplete/package.json deleted file mode 100644 index f841706e57a7..000000000000 --- a/packages/kbn-securitysolution-autocomplete/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-autocomplete", - "version": "1.0.0", - "description": "Security Solution auto complete", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts b/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts deleted file mode 100644 index 71bfb7f4a67c..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -// Copied from "src/plugins/data/public/mocks.ts" but without any type information -// TODO: Remove this in favor of the data/public/mocks if/when they become available, https://github.com/elastic/kibana/issues/100715 -export const autocompleteStartMock = { - getQuerySuggestions: jest.fn(), - getValueSuggestions: jest.fn(), - hasQuerySuggestions: jest.fn(), -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.ts deleted file mode 100644 index d98feca80b75..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { checkEmptyValue } from '.'; -import { getField } from '../fields/index.mock'; -import * as i18n from '../translations'; - -describe('check_empty_value', () => { - test('returns no errors if no field has been selected', () => { - const isValid = checkEmptyValue('', undefined, true, false); - - expect(isValid).toBeUndefined(); - }); - - test('returns error string if user has touched a required input and left empty', () => { - const isValid = checkEmptyValue(undefined, getField('@timestamp'), true, true); - - expect(isValid).toEqual(i18n.FIELD_REQUIRED_ERR); - }); - - test('returns no errors if required input is empty but user has not yet touched it', () => { - const isValid = checkEmptyValue(undefined, getField('@timestamp'), true, false); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if user has touched an input that is not required and left empty', () => { - const isValid = checkEmptyValue(undefined, getField('@timestamp'), false, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if user has touched an input that is not required and left empty string', () => { - const isValid = checkEmptyValue('', getField('@timestamp'), false, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns null if input value is not empty string or undefined', () => { - const isValid = checkEmptyValue('hellooo', getField('@timestamp'), false, true); - - expect(isValid).toBeNull(); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.ts b/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.ts deleted file mode 100644 index 218b8fee94d1..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewFieldBase } from '@kbn/es-query'; -import * as i18n from '../translations'; - -/** - * Determines if empty value is ok - */ -export const checkEmptyValue = ( - param: string | undefined, - field: DataViewFieldBase | undefined, - isRequired: boolean, - touched: boolean -): string | undefined | null => { - if (isRequired && touched && (param == null || param.trim() === '')) { - return i18n.FIELD_REQUIRED_ERR; - } - - if ( - field == null || - (isRequired && !touched) || - (!isRequired && (param == null || param === '')) - ) { - return undefined; - } - - return null; -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.ts b/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.ts deleted file mode 100644 index 980819d1cedf..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { disabledTypesWithTooltipText } from '../disabled_types_with_tooltip_text'; - -jest.mock('../../translations', () => ({ - BINARY_TYPE_NOT_SUPPORTED: 'Binary fields are currently unsupported', -})); -describe('disabledTypesWithTooltipText', () => { - it('should return Binary fields are currently unsupported for binary type', () => { - const type = 'binary'; - expect(disabledTypesWithTooltipText[type]).toEqual('Binary fields are currently unsupported'); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx deleted file mode 100644 index 1b33b4b29464..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { fireEvent, render, waitFor, within } from '@testing-library/react'; -import '@testing-library/jest-dom'; - -import { EsFieldSelector } from '..'; -import { fields, getField } from '../../fields/index.mock'; - -describe('FieldComponent', () => { - it('should render the component enabled and displays the selected field correctly', () => { - const wrapper = render( - - ); - expect(wrapper.container).toMatchSnapshot(); - const comboBox = wrapper.getByTestId('fieldAutocompleteComboBox'); - const input = within(comboBox).getByRole('combobox'); - expect(input).toHaveAttribute('value', 'machine.os.raw'); - }); - it('should render the component disabled if isDisabled is true', () => { - const wrapper = render( - - ); - expect(wrapper.container).toMatchSnapshot(); - expect(wrapper.getByTestId('fieldAutocompleteComboBox').querySelector('input')).toBeDisabled(); - }); - it('should render the loading spinner if isLoading is true when clicked', () => { - const wrapper = render( - - ); - const fieldAutocompleteComboBox = wrapper.getByTestId('fieldAutocompleteComboBox'); - expect(wrapper.container).toMatchSnapshot(); - fireEvent.click(fieldAutocompleteComboBox); - expect(wrapper.getByRole('progressbar')).toBeInTheDocument(); - }); - it('should allow user to clear values if isClearable is true', () => { - const wrapper = render( - - ); - expect(wrapper.container).toMatchSnapshot(); - expect(wrapper.getByTestId('comboBoxClearButton')).toBeInTheDocument(); - }); - it('should change the selected value', async () => { - const wrapper = render( - - ); - const fieldAutocompleteComboBox = wrapper.getByTestId('comboBoxSearchInput'); - fireEvent.change(fieldAutocompleteComboBox, { target: { value: '_source' } }); - expect(fieldAutocompleteComboBox).toHaveValue('_source'); - }); - - it('it allows custom user input if "acceptsCustomOptions" is "true"', async () => { - const mockOnChange = jest.fn(); - const wrapper = render( - - ); - - const fieldAutocompleteComboBox = wrapper.getByTestId('comboBoxSearchInput'); - fireEvent.change(fieldAutocompleteComboBox, { target: { value: 'custom' } }); - await waitFor(() => - expect(wrapper.getByTestId('fieldAutocompleteComboBox')).toHaveTextContent('custom') - ); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts b/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts deleted file mode 100644 index 422a909bb991..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -interface DisabledTypesTextType { - [typeName: string]: string; -} -import * as i18n from '../translations'; - -export const disabledTypesWithTooltipText: DisabledTypesTextType = { - binary: i18n.BINARY_TYPE_NOT_SUPPORTED, -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx b/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx deleted file mode 100644 index 31efaa23b62d..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx +++ /dev/null @@ -1,109 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { EuiComboBox } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -import { FieldBaseProps } from './types'; -import { useEsField } from './use_es_field'; - -const AS_PLAIN_TEXT = { asPlainText: true }; - -interface EsFieldSelectorProps extends FieldBaseProps { - isClearable?: boolean; - isDisabled?: boolean; - isLoading?: boolean; - placeholder: string; - acceptsCustomOptions?: boolean; - showMappingConflicts?: boolean; - 'aria-label'?: string; -} - -export function EsFieldSelector({ - fieldInputWidth, - fieldTypeFilter = [], - indexPattern, - isClearable = false, - isDisabled = false, - isLoading = false, - isRequired = false, - onChange, - placeholder, - selectedField, - acceptsCustomOptions = false, - showMappingConflicts = false, - 'aria-label': ariaLabel, -}: EsFieldSelectorProps): JSX.Element { - const { - isInvalid, - comboOptions, - selectedComboOptions, - fieldWidth, - renderFields, - handleTouch, - handleValuesChange, - handleCreateCustomOption, - } = useEsField({ - indexPattern, - fieldTypeFilter, - isRequired, - selectedField, - fieldInputWidth, - showMappingConflicts, - onChange, - }); - - if (acceptsCustomOptions) { - return ( - - ); - } - - return ( - - ); -} diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.ts b/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.ts deleted file mode 100644 index b0f1ab56e807..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; -import { FieldConflictsInfo } from '@kbn/securitysolution-list-utils'; -import { GetGenericComboBoxPropsReturn } from '../get_generic_combo_box_props'; - -export interface FieldBaseProps { - indexPattern: DataViewBase | undefined; - fieldTypeFilter?: string[]; - isRequired?: boolean; - selectedField?: DataViewFieldBase | undefined; - fieldInputWidth?: number; - showMappingConflicts?: boolean; - onChange: (a: DataViewFieldBase[]) => void; -} - -export interface ComboBoxFields { - availableFields: DataViewField[]; - selectedFields: DataViewField[]; -} - -export interface GetFieldComboBoxPropsReturn extends GetGenericComboBoxPropsReturn { - disabledLabelTooltipTexts: { [label: string]: string }; - mappingConflictsTooltipInfo: { [label: string]: FieldConflictsInfo[] }; -} - -export interface DataViewField extends DataViewFieldBase { - esTypes?: string[]; -} diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx deleted file mode 100644 index 801f8e2864d5..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { mount } from 'enzyme'; - -import { AutocompleteFieldExistsComponent } from '.'; - -describe('AutocompleteFieldExistsComponent', () => { - test('it renders field disabled', () => { - const wrapper = mount(); - - expect( - wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox existsComboxBox"] input`) - .prop('disabled') - ).toBeTruthy(); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx deleted file mode 100644 index 592886905aae..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow } from '@elastic/eui'; - -const NO_OPTIONS_FOR_EXIST: EuiComboBoxOptionOption[] = []; - -interface AutocompleteFieldExistsProps { - placeholder: string; - rowLabel?: string; - 'aria-label'?: string; -} - -export const AutocompleteFieldExistsComponent: React.FC = ({ - placeholder, - rowLabel, - 'aria-label': ariaLabel, -}): JSX.Element => ( - - - -); - -AutocompleteFieldExistsComponent.displayName = 'AutocompleteFieldExists'; diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx deleted file mode 100644 index b2d8dc0a70be..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx +++ /dev/null @@ -1,270 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { mount } from 'enzyme'; -import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { waitFor } from '@testing-library/react'; -import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { getField } from '../fields/index.mock'; -import { AutocompleteFieldListsComponent } from '.'; -import { - getListResponseMock, - getFoundListsBySizeSchemaMock, - DATE_NOW, - IMMUTABLE, - VERSION, -} from '../list_schema/index.mock'; - -// TODO: Once these mocks are available, use them instead of hand mocking, https://github.com/elastic/kibana/issues/100715 -// const mockKibanaHttpService = coreMock.createStart().http; -// import { coreMock } from '../../../../../../../src/core/public/mocks'; -const mockKibanaHttpService = jest.fn(); -const mockShowValueListModal = jest.fn(); -const MockedShowValueListModal = (props: unknown) => { - mockShowValueListModal(props); - return <>; -}; -const mockStart = jest.fn(); -const mockKeywordList: ListSchema = { - ...getListResponseMock(), - id: 'keyword_list', - name: 'keyword list', - type: 'keyword', -}; -const mockResult = { ...getFoundListsBySizeSchemaMock() }; -mockResult.smallLists = [...mockResult.smallLists, mockKeywordList]; -mockResult.largeLists = []; -jest.mock('@kbn/securitysolution-list-hooks', () => { - const originalModule = jest.requireActual('@kbn/securitysolution-list-hooks'); - - return { - ...originalModule, - useFindListsBySize: () => ({ - error: undefined, - loading: false, - result: mockResult, - start: mockStart.mockReturnValue(mockResult), - }), - }; -}); - -describe('AutocompleteFieldListsComponent', () => { - test('it renders disabled if "isDisabled" is true', async () => { - const wrapper = mount( - - ); - - expect( - wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) - .prop('disabled') - ).toBeTruthy(); - }); - - test('it renders loading if "isLoading" is true', async () => { - const wrapper = mount( - - ); - - wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] button`) - .at(0) - .simulate('click'); - expect( - wrapper - .find( - `EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteComboBox listsComboxBox-optionsList"]` - ) - .prop('isLoading') - ).toBeTruthy(); - }); - - test('it allows user to clear values if "isClearable" is true', async () => { - const wrapper = mount( - - ); - expect( - wrapper - .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') - .prop('options') - ).toEqual([{ label: 'some name', disabled: false }]); - }); - - test('it correctly displays lists that match the selected "keyword" field esType', () => { - const wrapper = mount( - - ); - - wrapper.find('[data-test-subj="comboBoxToggleListButton"] button').simulate('click'); - - expect( - wrapper - .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') - .prop('options') - ).toEqual([{ label: 'keyword list', disabled: false }]); - }); - - test('it correctly displays lists that match the selected "ip" field esType', () => { - const wrapper = mount( - - ); - - wrapper.find('[data-test-subj="comboBoxToggleListButton"] button').simulate('click'); - - expect( - wrapper - .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') - .prop('options') - ).toEqual([{ label: 'some name', disabled: false }]); - }); - - test('it correctly displays selected list', async () => { - const wrapper = mount( - - ); - - expect( - wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) - .at(0) - .props().value - ).toEqual('some name'); - }); - - test('it invokes "onChange" when option selected', async () => { - const mockOnChange = jest.fn(); - const wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: 'some name', disabled: false }]); - - await waitFor(() => { - expect(mockOnChange).toHaveBeenCalledWith({ - '@timestamp': DATE_NOW, - _version: undefined, - created_at: DATE_NOW, - created_by: 'some user', - description: 'some description', - deserializer: undefined, - id: 'some-list-id', - immutable: IMMUTABLE, - meta: {}, - name: 'some name', - serializer: undefined, - tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', - type: 'ip', - updated_at: DATE_NOW, - updated_by: 'some user', - version: VERSION, - }); - }); - }); - - test('it render the value list modal', async () => { - mockShowValueListModal.mockReset(); - mount( - - ); - - expect(mockShowValueListModal).toHaveBeenCalledWith( - expect.objectContaining({ - children: 'Show value list', - listId: 'some-list-id', - shouldShowContentIfModalNotAvailable: false, - }) - ); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx deleted file mode 100644 index c332dde356f2..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { ElementType, useCallback, useEffect, useMemo, useState } from 'react'; -import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow, EuiLink, EuiText } from '@elastic/eui'; -import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { useFindListsBySize } from '@kbn/securitysolution-list-hooks'; -import { DataViewFieldBase } from '@kbn/es-query'; -import { getDocLinks } from '@kbn/doc-links'; - -import { filterFieldToList } from '../filter_field_to_list'; -import { getGenericComboBoxProps } from '../get_generic_combo_box_props'; - -// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 -// import { HttpStart } from '@kbn/core/public'; -type HttpStart = any; - -import * as i18n from '../translations'; - -const SINGLE_SELECTION = { asPlainText: true }; - -interface AutocompleteFieldListsProps { - httpService: HttpStart; - isClearable: boolean; - isDisabled: boolean; - isLoading: boolean; - onChange: (arg: ListSchema) => void; - placeholder: string; - rowLabel?: string; - selectedField: DataViewFieldBase | undefined; - selectedValue: string | undefined; - allowLargeValueLists?: boolean; - 'aria-label'?: string; - showValueListModal: ElementType; -} - -export interface AutocompleteListsData { - smallLists: ListSchema[]; - largeLists: ListSchema[]; -} - -export const AutocompleteFieldListsComponent: React.FC = ({ - httpService, - isClearable = false, - isDisabled = false, - isLoading = false, - onChange, - placeholder, - rowLabel, - selectedField, - selectedValue, - allowLargeValueLists = false, - 'aria-label': ariaLabel, - showValueListModal, -}): JSX.Element => { - const [error, setError] = useState(undefined); - const [listData, setListData] = useState({ - smallLists: [], - largeLists: [], - }); - const { loading, result, start } = useFindListsBySize(); - const getLabel = useCallback(({ name }: ListSchema) => name, []); - - const optionsMemo = useMemo( - () => filterFieldToList(listData, selectedField), - [listData, selectedField] - ); - const selectedOptionsMemo = useMemo(() => { - if (selectedValue != null) { - const combinedLists = [...listData.smallLists, ...listData.largeLists]; - const list = combinedLists.filter(({ id }) => id === selectedValue); - return list ?? []; - } else { - return []; - } - }, [selectedValue, listData]); - const { comboOptions, labels, selectedComboOptions } = useMemo( - () => - getGenericComboBoxProps({ - getLabel, - options: [...optionsMemo.smallLists, ...optionsMemo.largeLists], - selectedOptions: selectedOptionsMemo, - disabledOptions: allowLargeValueLists ? undefined : optionsMemo.largeLists, // Disable large lists if the rule type doesn't allow it - }), - [optionsMemo, selectedOptionsMemo, getLabel, allowLargeValueLists] - ); - - const handleValuesChange = useCallback( - (newOptions: EuiComboBoxOptionOption[]) => { - const combinedLists = [...optionsMemo.smallLists, ...optionsMemo.largeLists]; - const [newValue] = newOptions.map(({ label }) => combinedLists[labels.indexOf(label)]); - onChange(newValue ?? ''); - }, - [labels, optionsMemo, onChange] - ); - - const setIsTouchedValue = useCallback((): void => { - setError(selectedValue == null ? i18n.FIELD_REQUIRED_ERR : undefined); - }, [selectedValue]); - - useEffect(() => { - if (result != null) { - setListData(result); - } - }, [result]); - - useEffect(() => { - if (selectedField != null && httpService != null) { - start({ - http: httpService, - pageIndex: 1, - pageSize: 500, - }); - } - }, [selectedField, start, httpService]); - - const isLoadingState = useMemo((): boolean => isLoading || loading, [isLoading, loading]); - const ShowValueListModal = showValueListModal; - - const helpText = useMemo(() => { - return ( - <> - {selectedValue && ( - - {i18n.SHOW_VALUE_LIST_MODAL} - - )} - {!allowLargeValueLists && ( - - {i18n.LISTS_TOOLTIP_INFO}{' '} - - {i18n.SEE_DOCUMENTATION} - - - )} - - ); - }, [allowLargeValueLists, selectedValue, ShowValueListModal]); - return ( - - - - ); -}; - -AutocompleteFieldListsComponent.displayName = 'AutocompleteFieldList'; diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx deleted file mode 100644 index e83d79b180e9..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx +++ /dev/null @@ -1,631 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { ReactWrapper, mount } from 'enzyme'; -import { - EuiComboBox, - EuiComboBoxOptionOption, - EuiFormHelpText, - EuiSuperSelect, -} from '@elastic/eui'; -import { act, waitFor } from '@testing-library/react'; -import { AutocompleteFieldMatchComponent } from '.'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { fields, getField } from '../fields/index.mock'; -import { autocompleteStartMock } from '../autocomplete/index.mock'; - -jest.mock('../hooks/use_field_value_autocomplete'); -jest.mock('../translations', () => ({ - FIELD_SPACE_WARNING: 'Warning: there is a space', -})); -describe('AutocompleteFieldMatchComponent', () => { - let wrapper: ReactWrapper; - - const getValueSuggestionsMock = jest - .fn() - .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); - - const findEuiComboBox = () => - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - onSearchChange: (a: string) => void; - onCreateOption: (a: string) => void; - }; - - beforeEach(() => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - ['value 1', 'value 2'], - getValueSuggestionsMock, - ]); - }); - - afterEach(() => { - jest.clearAllMocks(); - wrapper.unmount(); - }); - - test('it renders row label if one passed in', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteMatchLabel"] label').at(0).text() - ).toEqual('Row Label'); - }); - - test('it renders disabled if "isDisabled" is true', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteMatch"] input').prop('disabled') - ).toBeTruthy(); - }); - - test('it renders loading if "isLoading" is true', () => { - wrapper = mount( - - ); - wrapper.find('[data-test-subj="valuesAutocompleteMatch"] button').at(0).simulate('click'); - expect( - wrapper - .find('EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteMatch-optionsList"]') - .prop('isLoading') - ).toBeTruthy(); - }); - - test('it allows user to clear values if "isClearable" is true', () => { - wrapper = mount( - - ); - - expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); - }); - - test('it correctly displays selected value', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteMatch"] input').at(0).props().value - ).toEqual('127.0.0.1'); - }); - - test('it invokes "onChange" when new value created', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - findEuiComboBox().onCreateOption('127.0.0.1'); - - expect(mockOnChange).toHaveBeenCalledWith('127.0.0.1'); - }); - - test('it invokes "onChange" when new value selected', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - findEuiComboBox().onChange([{ label: 'value 1' }]); - - expect(mockOnChange).toHaveBeenCalledWith('value 1'); - }); - - test('it invokes "onChange" with empty value (i.e. clears selection) when new value searched', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - act(() => { - findEuiComboBox().onSearchChange('value 12'); - }); - - expect(mockOnChange).toHaveBeenCalledWith(''); - }); - - test('should show the warning helper text if the new value contains spaces when change', async () => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - [' value 1 ', 'value 2'], - getValueSuggestionsMock, - ]); - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - await waitFor(() => findEuiComboBox().onChange([{ label: ' value 1 ' }])); - wrapper.update(); - expect(mockOnChange).toHaveBeenCalledWith(' value 1 '); - - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - }); - - test('it refreshes autocomplete with search query when new value searched', () => { - wrapper = mount( - - ); - act(() => { - findEuiComboBox().onSearchChange('value 1'); - }); - - expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ - autocompleteService: autocompleteStartMock, - fieldValue: '', - indexPattern: { - fields, - id: '1234', - title: 'logstash-*', - }, - operatorType: 'match', - query: 'value 1', - selectedField: getField('machine.os.raw'), - }); - }); - - test('it refreshes autocomplete with search query when input field is cleared', () => { - wrapper = mount( - - ); - - act(() => { - findEuiComboBox().onSearchChange('value 1'); - }); - act(() => { - findEuiComboBox().onSearchChange(''); - }); - - // 1st call is initial render, 2nd call sets the search query: - expect(useFieldValueAutocomplete).toHaveBeenNthCalledWith(2, { - autocompleteService: autocompleteStartMock, - fieldValue: 'windows', - indexPattern: { fields, id: '1234', title: 'logstash-*' }, - operatorType: 'match', - query: 'value 1', - selectedField: getField('machine.os.raw'), - }); - // last call is the refresh when input field is cleared - expect(useFieldValueAutocomplete).toHaveBeenLastCalledWith({ - autocompleteService: autocompleteStartMock, - fieldValue: 'windows', - indexPattern: { fields, id: '1234', title: 'logstash-*' }, - operatorType: 'match', - query: '', - selectedField: getField('machine.os.raw'), - }); - }); - - test('should show the warning helper text if the new value contains spaces when searching a new query', () => { - wrapper = mount( - - ); - act(() => { - findEuiComboBox().onSearchChange(' value 1'); - }); - - wrapper.update(); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - - test('should show the warning helper text if selectedValue contains spaces when editing', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - - test('should not show the warning helper text if selectedValue is falsy', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeFalsy(); - }); - - describe('boolean type', () => { - const valueSuggestionsMock = jest.fn().mockResolvedValue([false, false, [], jest.fn()]); - - beforeEach(() => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - false, - [], - valueSuggestionsMock, - ]); - }); - - test('it displays only two options - "true" or "false"', () => { - wrapper = mount( - - ); - expect( - wrapper.find('[data-test-subj="valuesAutocompleteMatchBoolean"]').exists() - ).toBeTruthy(); - expect( - wrapper.find('[data-test-subj="valuesAutocompleteMatchBoolean"]').at(0).prop('options') - ).toEqual([ - { - inputDisplay: 'true', - value: 'true', - }, - { - inputDisplay: 'false', - value: 'false', - }, - ]); - }); - - test('it invokes "onChange" with "true" when selected', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiSuperSelect).props() as unknown as { - onChange: (a: string) => void; - } - ).onChange('true'); - - expect(mockOnChange).toHaveBeenCalledWith('true'); - }); - - test('it invokes "onChange" with "false" when selected', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiSuperSelect).props() as unknown as { - onChange: (a: string) => void; - } - ).onChange('false'); - - expect(mockOnChange).toHaveBeenCalledWith('false'); - }); - }); - - describe('number type', () => { - const valueSuggestionsMock = jest.fn().mockResolvedValue([false, false, [], jest.fn()]); - - beforeEach(() => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - false, - [], - valueSuggestionsMock, - ]); - }); - - test('it number input when field type is number', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valueAutocompleteFieldMatchNumber"]').exists() - ).toBeTruthy(); - }); - - test('it invokes "onChange" with numeric value when inputted', () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - wrapper - .find('[data-test-subj="valueAutocompleteFieldMatchNumber"] input') - .at(0) - .simulate('change', { target: { value: '8' } }); - - expect(mockOnChange).toHaveBeenCalledWith('8'); - }); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx deleted file mode 100644 index 5b627451db19..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx +++ /dev/null @@ -1,377 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useCallback, useMemo, useState, useEffect } from 'react'; -import { - EuiSuperSelect, - EuiFormRow, - EuiFieldNumber, - EuiComboBoxOptionOption, - EuiComboBox, -} from '@elastic/eui'; -import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; - -import { uniq } from 'lodash'; - -import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; - -// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 -// import { AutocompleteStart } from '../../../../../../../src/plugins/unified_search/public'; -type AutocompleteStart = any; - -import * as i18n from '../translations'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { - getGenericComboBoxProps, - GetGenericComboBoxPropsReturn, -} from '../get_generic_combo_box_props'; -import { paramIsValid } from '../param_is_valid'; -import { paramContainsSpace } from '../param_contains_space'; - -const BOOLEAN_OPTIONS = [ - { inputDisplay: 'true', value: 'true' }, - { inputDisplay: 'false', value: 'false' }, -]; - -const SINGLE_SELECTION = { asPlainText: true }; - -type Warning = string | React.ReactNode; - -interface AutocompleteFieldMatchProps { - placeholder: string; - selectedField: DataViewFieldBase | undefined; - selectedValue: string | undefined; - indexPattern: DataViewBase | undefined; - isLoading?: boolean; - isDisabled?: boolean; - isClearable?: boolean; - isRequired?: boolean; - fieldInputWidth?: number; - rowLabel?: string; - autocompleteService: AutocompleteStart; - onChange: (arg: string) => void; - onError?: (arg: boolean) => void; - onWarning?: (arg: boolean) => void; - warning?: Warning; - 'aria-label'?: string; -} - -export const AutocompleteFieldMatchComponent: React.FC = ({ - placeholder, - rowLabel, - selectedField, - selectedValue, - indexPattern, - isLoading = false, - isDisabled = false, - isClearable = false, - isRequired = false, - fieldInputWidth, - autocompleteService, - onChange, - onError, - onWarning, - warning, - 'aria-label': ariaLabel, -}): JSX.Element => { - const [searchQuery, setSearchQuery] = useState(''); - const [touched, setIsTouched] = useState(false); - const [error, setError] = useState(undefined); - const [showSpacesWarning, setShowSpacesWarning] = useState(false); - const [isLoadingSuggestions, isSuggestingValues, suggestions] = useFieldValueAutocomplete({ - autocompleteService, - fieldValue: selectedValue, - indexPattern, - operatorType: OperatorTypeEnum.MATCH, - query: searchQuery, - selectedField, - }); - const getLabel = useCallback((option: string): string => option, []); - - const optionsMemo = useMemo((): string[] => { - const valueAsStr = String(selectedValue); - return selectedValue != null && selectedValue.trim() !== '' - ? uniq([valueAsStr, ...suggestions]) - : suggestions; - }, [suggestions, selectedValue]); - - const selectedOptionsMemo = useMemo((): string[] => { - const valueAsStr = String(selectedValue); - return selectedValue ? [valueAsStr] : []; - }, [selectedValue]); - - const handleSpacesWarning = useCallback( - (param: string | undefined) => { - if (!param) return setShowSpacesWarning(false); - setShowSpacesWarning(!!paramContainsSpace(param)); - }, - [setShowSpacesWarning] - ); - - const handleError = useCallback( - (err: string | undefined): void => { - setError((existingErr): string | undefined => { - const oldErr = existingErr != null; - const newErr = err != null; - if (oldErr !== newErr && onError != null) { - onError(newErr); - } - - return err; - }); - }, - [setError, onError] - ); - - const handleWarning = useCallback( - (warn: Warning | undefined): void => { - if (onWarning) { - onWarning(warn !== undefined); - } - }, - [onWarning] - ); - - const { comboOptions, labels, selectedComboOptions } = useMemo( - (): GetGenericComboBoxPropsReturn => - getGenericComboBoxProps({ - getLabel, - options: optionsMemo, - selectedOptions: selectedOptionsMemo, - }), - [optionsMemo, selectedOptionsMemo, getLabel] - ); - - const handleValuesChange = useCallback( - (newOptions: EuiComboBoxOptionOption[]): void => { - const [newValue] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); - - handleSpacesWarning(newValue); - handleError(undefined); - handleWarning(undefined); - onChange(newValue ?? ''); - }, - [handleError, handleWarning, handleSpacesWarning, labels, onChange, optionsMemo] - ); - - const handleSearchChange = useCallback( - (searchVal: string): void => { - if (searchVal !== '' && selectedField != null) { - const err = paramIsValid(searchVal, selectedField, isRequired, touched); - handleError(err); - handleWarning(warning); - - if (!err) handleSpacesWarning(searchVal); - } - - if (searchVal) { - // Clear selected option when user types to allow user to modify value without {backspace} - onChange(''); - } - - // Update search query unconditionally to show correct suggestions even when input is cleared - setSearchQuery(searchVal); - }, - [ - selectedField, - onChange, - isRequired, - touched, - handleError, - handleWarning, - warning, - handleSpacesWarning, - ] - ); - - const handleCreateOption = useCallback( - (option: string): boolean | undefined => { - const err = paramIsValid(option, selectedField, isRequired, touched); - handleError(err); - handleWarning(warning); - - if (err != null) { - // Explicitly reject the user's input - setShowSpacesWarning(false); - return false; - } - - handleSpacesWarning(option); - onChange(option); - return undefined; - }, - [ - isRequired, - onChange, - selectedField, - touched, - handleError, - handleSpacesWarning, - handleWarning, - warning, - ] - ); - - const handleNonComboBoxInputChange = useCallback( - (event: React.ChangeEvent): void => { - const newValue = event.target.value; - onChange(newValue); - }, - [onChange] - ); - - const handleBooleanInputChange = useCallback( - (newOption: string): void => { - onChange(newOption); - }, - [onChange] - ); - - const setIsTouchedValue = useCallback((): void => { - setIsTouched(true); - - const err = paramIsValid(selectedValue, selectedField, isRequired, true); - handleError(err); - handleWarning(warning); - }, [setIsTouched, handleError, selectedValue, selectedField, isRequired, warning, handleWarning]); - - const inputPlaceholder = useMemo((): string => { - if (isLoading || isLoadingSuggestions) { - return i18n.LOADING; - } else if (selectedField == null) { - return i18n.SELECT_FIELD_FIRST; - } else { - return placeholder; - } - }, [isLoading, selectedField, isLoadingSuggestions, placeholder]); - - const isLoadingState = useMemo( - (): boolean => isLoading || isLoadingSuggestions, - [isLoading, isLoadingSuggestions] - ); - - useEffect((): void => { - setError(undefined); - if (onError != null) onError(false); - - handleSpacesWarning(selectedValue); - // Looks like selectedField return new object every time when we for example add "and" entry - // that's why we need to check for name and type here - // Probably we should use some kind of memoization on parent components for entries - }, [selectedField?.name, selectedField?.type, selectedValue, handleSpacesWarning, onError]); - - const defaultInput = useMemo((): JSX.Element => { - return ( - - - - ); - }, [ - rowLabel, - error, - selectedField, - showSpacesWarning, - inputPlaceholder, - isDisabled, - isLoadingState, - isClearable, - comboOptions, - selectedComboOptions, - handleValuesChange, - handleSearchChange, - handleCreateOption, - setIsTouchedValue, - warning, - fieldInputWidth, - ariaLabel, - ]); - - if (!isSuggestingValues && selectedField != null) { - switch (selectedField.type) { - case 'number': - return ( - - 0 - ? parseFloat(selectedValue) - : selectedValue ?? '' - } - onChange={handleNonComboBoxInputChange} - data-test-subj="valueAutocompleteFieldMatchNumber" - style={fieldInputWidth ? { width: `${fieldInputWidth}px` } : {}} - aria-label={ariaLabel} - fullWidth - /> - - ); - case 'boolean': - return ( - - - - ); - default: - return defaultInput; - } - } else { - return defaultInput; - } -}; - -AutocompleteFieldMatchComponent.displayName = 'AutocompleteFieldMatch'; diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx deleted file mode 100644 index 0b73a57814aa..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx +++ /dev/null @@ -1,400 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { ReactWrapper, mount } from 'enzyme'; -import { EuiComboBox, EuiComboBoxOptionOption, EuiFormHelpText } from '@elastic/eui'; -import { act, waitFor } from '@testing-library/react'; - -import { AutocompleteFieldMatchAnyComponent } from '.'; -import { getField, fields } from '../fields/index.mock'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { autocompleteStartMock } from '../autocomplete/index.mock'; - -jest.mock('../hooks/use_field_value_autocomplete', () => { - const actual = jest.requireActual('../hooks/use_field_value_autocomplete'); - return { - ...actual, - useFieldValueAutocomplete: jest.fn(), - }; -}); -jest.mock('../translations', () => ({ - FIELD_SPACE_WARNING: 'Warning: there is a space', -})); - -describe('AutocompleteFieldMatchAnyComponent', () => { - let wrapper: ReactWrapper; - const getValueSuggestionsMock = jest - .fn() - .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); - - beforeEach(() => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - ['value 1', 'value 2'], - getValueSuggestionsMock, - ]); - }); - - afterEach(() => { - jest.clearAllMocks(); - wrapper.unmount(); - }); - - test('it renders disabled if "isDisabled" is true', () => { - wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] input`).prop('disabled') - ).toBeTruthy(); - }); - - test('it renders loading if "isLoading" is true', () => { - wrapper = mount( - - ); - wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] button`).at(0).simulate('click'); - expect( - wrapper - .find(`EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteMatchAny-optionsList"]`) - .prop('isLoading') - ).toBeTruthy(); - }); - - test('it allows user to clear values if "isClearable" is true', () => { - wrapper = mount( - - ); - - expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); - }); - - test('it correctly displays selected value', () => { - wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] EuiComboBoxPill`).at(0).text() - ).toEqual('127.0.0.1'); - }); - - test('it invokes "onChange" when new value created', async () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onCreateOption: (a: string) => void; - } - ).onCreateOption('127.0.0.1'); - - expect(mockOnChange).toHaveBeenCalledWith(['127.0.0.1']); - }); - - test('it invokes "onChange" when new value selected', async () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: 'value 1' }]); - - expect(mockOnChange).toHaveBeenCalledWith(['value 1']); - }); - - test('it refreshes autocomplete with search query when new value searched', () => { - wrapper = mount( - - ); - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onSearchChange: (a: string) => void; - } - ).onSearchChange('value 1'); - }); - expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ - autocompleteService: autocompleteStartMock, - fieldValue: [], - indexPattern: { - fields, - id: '1234', - title: 'logstash-*', - }, - operatorType: 'match_any', - query: 'value 1', - selectedField: getField('machine.os.raw'), - }); - }); - test('should show the warning helper text if the new value contains spaces when change', async () => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - [' value 1 ', 'value 2'], - getValueSuggestionsMock, - ]); - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - await waitFor(() => - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: ' value 1 ' }]) - ); - wrapper.update(); - expect(mockOnChange).toHaveBeenCalledWith([' value 1 ']); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - }); - test('should show the warning helper text if the new value contains spaces when searching a new query', () => { - wrapper = mount( - - ); - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onSearchChange: (a: string) => void; - } - ).onSearchChange(' value 1'); - }); - - wrapper.update(); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - test('should show the warning helper text if selectedValue contains spaces when editing', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - test('should not show the warning helper text if selectedValue is falsy', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeFalsy(); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx deleted file mode 100644 index 761712797c5e..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx +++ /dev/null @@ -1,253 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow } from '@elastic/eui'; -import { uniq } from 'lodash'; -import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; -import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; - -// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 -// import { AutocompleteStart } from '../../../../../../../src/plugins/unified_search/public'; -type AutocompleteStart = any; - -import * as i18n from '../translations'; -import { - getGenericComboBoxProps, - GetGenericComboBoxPropsReturn, -} from '../get_generic_combo_box_props'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { paramIsValid } from '../param_is_valid'; -import { paramContainsSpace } from '../param_contains_space'; - -interface AutocompleteFieldMatchAnyProps { - placeholder: string; - selectedField: DataViewFieldBase | undefined; - selectedValue: string[]; - indexPattern: DataViewBase | undefined; - isLoading: boolean; - isDisabled: boolean; - isClearable: boolean; - isRequired?: boolean; - rowLabel?: string; - autocompleteService: AutocompleteStart; - onChange: (arg: string[]) => void; - onError?: (arg: boolean) => void; - 'aria-label'?: string; -} - -export const AutocompleteFieldMatchAnyComponent: React.FC = ({ - placeholder, - rowLabel, - selectedField, - selectedValue, - indexPattern, - isLoading, - isDisabled = false, - isClearable = false, - isRequired = false, - onChange, - onError, - autocompleteService, - 'aria-label': ariaLabel, -}): JSX.Element => { - const [searchQuery, setSearchQuery] = useState(''); - const [touched, setIsTouched] = useState(false); - const [error, setError] = useState(undefined); - const [showSpacesWarning, setShowSpacesWarning] = useState(false); - const [isLoadingSuggestions, isSuggestingValues, suggestions] = useFieldValueAutocomplete({ - autocompleteService, - fieldValue: selectedValue, - indexPattern, - operatorType: OperatorTypeEnum.MATCH_ANY, - query: searchQuery, - selectedField, - }); - const getLabel = useCallback((option: string): string => option, []); - const optionsMemo = useMemo( - (): string[] => (selectedValue ? uniq([...selectedValue, ...suggestions]) : suggestions), - [suggestions, selectedValue] - ); - const { comboOptions, labels, selectedComboOptions } = useMemo( - (): GetGenericComboBoxPropsReturn => - getGenericComboBoxProps({ - getLabel, - options: optionsMemo, - selectedOptions: selectedValue, - }), - [optionsMemo, selectedValue, getLabel] - ); - const handleSpacesWarning = useCallback( - (params: string[]) => - setShowSpacesWarning(!!params.find((param: string) => paramContainsSpace(param))), - [setShowSpacesWarning] - ); - const handleError = useCallback( - (err: string | undefined): void => { - setError((existingErr): string | undefined => { - const oldErr = existingErr != null; - const newErr = err != null; - if (oldErr !== newErr && onError != null) { - onError(newErr); - } - - return err; - }); - }, - [setError, onError] - ); - - const handleValuesChange = useCallback( - (newOptions: EuiComboBoxOptionOption[]): void => { - const newValues: string[] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); - handleError(undefined); - handleSpacesWarning(newValues); - onChange(newValues); - }, - [handleError, handleSpacesWarning, labels, onChange, optionsMemo] - ); - - const handleSearchChange = useCallback( - (searchVal: string) => { - if (searchVal === '') { - handleError(undefined); - } - - if (searchVal !== '' && selectedField != null) { - const err = paramIsValid(searchVal, selectedField, isRequired, touched); - handleError(err); - - if (!err) handleSpacesWarning([searchVal]); - - setSearchQuery(searchVal); - } - }, - [handleError, handleSpacesWarning, isRequired, selectedField, touched] - ); - - const handleCreateOption = useCallback( - (option: string): boolean => { - const err = paramIsValid(option, selectedField, isRequired, touched); - handleError(err); - - if (err != null) { - // Explicitly reject the user's input - setShowSpacesWarning(false); - return false; - } - - onChange([...(selectedValue || []), option]); - handleSpacesWarning([option]); - return true; - }, - [handleError, handleSpacesWarning, isRequired, onChange, selectedField, selectedValue, touched] - ); - - const setIsTouchedValue = useCallback((): void => { - handleError(selectedComboOptions.length === 0 ? i18n.FIELD_REQUIRED_ERR : undefined); - setIsTouched(true); - }, [setIsTouched, handleError, selectedComboOptions]); - - const inputPlaceholder = useMemo( - (): string => (isLoading || isLoadingSuggestions ? i18n.LOADING : placeholder), - [isLoading, isLoadingSuggestions, placeholder] - ); - - const isLoadingState = useMemo( - (): boolean => isLoading || isLoadingSuggestions, - [isLoading, isLoadingSuggestions] - ); - useEffect((): void => { - handleSpacesWarning(selectedValue); - }, [selectedField, selectedValue, handleSpacesWarning]); - - const defaultInput = useMemo((): JSX.Element => { - return ( - - - - ); - }, [ - rowLabel, - error, - selectedField, - showSpacesWarning, - inputPlaceholder, - isLoadingState, - isClearable, - isDisabled, - comboOptions, - selectedComboOptions, - handleValuesChange, - handleSearchChange, - handleCreateOption, - setIsTouchedValue, - ariaLabel, - ]); - - if (!isSuggestingValues && selectedField != null) { - switch (selectedField.type) { - case 'number': - return ( - - - - ); - default: - return defaultInput; - } - } - - return defaultInput; -}; - -AutocompleteFieldMatchAnyComponent.displayName = 'AutocompleteFieldMatchAny'; diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx deleted file mode 100644 index 2840e428a69e..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx +++ /dev/null @@ -1,516 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { ReactWrapper, mount } from 'enzyme'; -import { EuiComboBox, EuiComboBoxOptionOption, EuiFormHelpText } from '@elastic/eui'; -import { act, waitFor } from '@testing-library/react'; -import { AutocompleteFieldWildcardComponent } from '.'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { fields, getField } from '../fields/index.mock'; -import { autocompleteStartMock } from '../autocomplete/index.mock'; -import { WILDCARD_WARNING, FILEPATH_WARNING } from '@kbn/securitysolution-utils'; - -jest.mock('../hooks/use_field_value_autocomplete'); -jest.mock('../translations', () => ({ - FIELD_SPACE_WARNING: 'Warning: there is a space', -})); -describe('AutocompleteFieldWildcardComponent', () => { - let wrapper: ReactWrapper; - - const getValueSuggestionsMock = jest - .fn() - .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); - - beforeEach(() => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - ['value 1', 'value 2'], - getValueSuggestionsMock, - ]); - }); - - afterEach(() => { - jest.clearAllMocks(); - wrapper.unmount(); - }); - - test('it renders row label if one passed in', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteWildcardLabel"] label').at(0).text() - ).toEqual('Row Label'); - }); - - test('it renders disabled if "isDisabled" is true', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] input').prop('disabled') - ).toBeTruthy(); - }); - - test('it renders loading if "isLoading" is true', () => { - wrapper = mount( - - ); - wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] button').at(0).simulate('click'); - expect( - wrapper - .find('EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteWildcard-optionsList"]') - .prop('isLoading') - ).toBeTruthy(); - }); - - test('it allows user to clear values if "isClearable" is true', () => { - wrapper = mount( - - ); - - expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); - }); - - test('it correctly displays selected value', () => { - wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] input').at(0).props().value - ).toEqual('/opt/*/app.dmg'); - }); - - test('it invokes "onChange" when new value created', async () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onCreateOption: (a: string) => void; - } - ).onCreateOption('/opt/*/app.dmg'); - - expect(mockOnChange).toHaveBeenCalledWith('/opt/*/app.dmg'); - }); - - test('it invokes "onChange" when new value selected', async () => { - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: 'value 1' }]); - - expect(mockOnChange).toHaveBeenCalledWith('value 1'); - }); - - test('it refreshes autocomplete with search query when new value searched', () => { - wrapper = mount( - - ); - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onSearchChange: (a: string) => void; - } - ).onSearchChange('A:\\Some Folder\\inc*.exe'); - }); - - expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ - autocompleteService: autocompleteStartMock, - fieldValue: '', - indexPattern: { - fields, - id: '1234', - title: 'logs-endpoint.events.*', - }, - operatorType: 'wildcard', - query: 'A:\\Some Folder\\inc*.exe', - selectedField: getField('file.path.text'), - }); - }); - - test('it does not invoke "onWarning" when no warning exists', () => { - const mockOnWarning = jest.fn(); - wrapper = mount( - - ); - - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onBlur: () => void; - } - ).onBlur(); - }); - - expect(mockOnWarning).not.toHaveBeenCalledWith(true); - }); - - test('it invokes "onWarning" when warning exists', () => { - const mockOnWarning = jest.fn(); - wrapper = mount( - - ); - - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onBlur: () => void; - } - ).onBlur(); - }); - - expect(mockOnWarning).toHaveBeenCalledWith(true); - expect( - wrapper - .find('[data-test-subj="valuesAutocompleteWildcardLabel"] div.euiFormHelpText') - .at(0) - .text() - ).toEqual(FILEPATH_WARNING); - }); - - test('it invokes "onWarning" when warning exists and is wildcard warning', () => { - const mockOnWarning = jest.fn(); - wrapper = mount( - - ); - - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onBlur: () => void; - } - ).onBlur(); - }); - - expect(mockOnWarning).toHaveBeenCalledWith(true); - const helpText = wrapper - .find('[data-test-subj="valuesAutocompleteWildcardLabel"] div.euiFormHelpText') - .at(0); - expect(helpText.text()).toEqual(WILDCARD_WARNING); - expect(helpText.find('.euiToolTipAnchor')).toBeTruthy(); - }); - test('should show the warning helper text if the new value contains spaces when change', async () => { - (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ - false, - true, - [' value 1 ', 'value 2'], - getValueSuggestionsMock, - ]); - const mockOnChange = jest.fn(); - wrapper = mount( - - ); - - await waitFor(() => - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: ' value 1 ' }]) - ); - wrapper.update(); - expect(mockOnChange).toHaveBeenCalledWith(' value 1 '); - - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - }); - test('should show the warning helper text if the new value contains spaces when searching a new query', () => { - wrapper = mount( - - ); - act(() => { - ( - wrapper.find(EuiComboBox).props() as unknown as { - onSearchChange: (a: string) => void; - } - ).onSearchChange(' value 1'); - }); - - wrapper.update(); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - test('should show the warning helper text if selectedValue contains spaces when editing', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeTruthy(); - expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); - }); - test('should not show the warning helper text if selectedValue is falsy', () => { - wrapper = mount( - - ); - const euiFormHelptext = wrapper.find(EuiFormHelpText); - expect(euiFormHelptext.length).toBeFalsy(); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx deleted file mode 100644 index 5a55b3399a6a..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx +++ /dev/null @@ -1,286 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useCallback, useMemo, useState, useEffect, memo } from 'react'; -import { EuiFormRow, EuiComboBoxOptionOption, EuiComboBox } from '@elastic/eui'; -import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; - -import { uniq } from 'lodash'; - -import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; - -// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 -// import { AutocompleteStart } from '../../../../../../../src/plugins/unified_search/public'; -type AutocompleteStart = any; - -import * as i18n from '../translations'; -import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; -import { - getGenericComboBoxProps, - GetGenericComboBoxPropsReturn, -} from '../get_generic_combo_box_props'; -import { paramIsValid } from '../param_is_valid'; -import { paramContainsSpace } from '../param_contains_space'; - -const SINGLE_SELECTION = { asPlainText: true }; - -type Warning = string | React.ReactNode; -interface AutocompleteFieldWildcardProps { - placeholder: string; - selectedField: DataViewFieldBase | undefined; - selectedValue: string | undefined; - indexPattern: DataViewBase | undefined; - isLoading: boolean; - isDisabled?: boolean; - isClearable?: boolean; - isRequired?: boolean; - fieldInputWidth?: number; - rowLabel?: string; - autocompleteService: AutocompleteStart; - onChange: (arg: string) => void; - onError: (arg: boolean) => void; - onWarning: (arg: boolean) => void; - warning?: Warning; - 'aria-label'?: string; -} - -export const AutocompleteFieldWildcardComponent: React.FC = memo( - ({ - autocompleteService, - placeholder, - rowLabel, - selectedField, - selectedValue, - indexPattern, - isLoading, - isDisabled = false, - isClearable = false, - isRequired = false, - fieldInputWidth, - onChange, - onError, - onWarning, - warning, - 'aria-label': ariaLabel, - }): JSX.Element => { - const [searchQuery, setSearchQuery] = useState(''); - const [touched, setIsTouched] = useState(false); - const [error, setError] = useState(undefined); - const [showSpacesWarning, setShowSpacesWarning] = useState(false); - const [isLoadingSuggestions, , suggestions] = useFieldValueAutocomplete({ - autocompleteService, - fieldValue: selectedValue, - indexPattern, - operatorType: OperatorTypeEnum.WILDCARD, - query: searchQuery, - selectedField, - }); - const getLabel = useCallback((option: string): string => option, []); - const optionsMemo = useMemo((): string[] => { - const valueAsStr = String(selectedValue); - return selectedValue != null && selectedValue.trim() !== '' - ? uniq([valueAsStr, ...suggestions]) - : suggestions; - }, [suggestions, selectedValue]); - const selectedOptionsMemo = useMemo((): string[] => { - const valueAsStr = String(selectedValue); - return selectedValue ? [valueAsStr] : []; - }, [selectedValue]); - - const handleSpacesWarning = useCallback( - (param: string | undefined) => { - if (!param) return setShowSpacesWarning(false); - setShowSpacesWarning(!!paramContainsSpace(param)); - }, - [setShowSpacesWarning] - ); - const handleError = useCallback( - (err: string | undefined): void => { - setError((existingErr): string | undefined => { - const oldErr = existingErr != null; - const newErr = err != null; - if (oldErr !== newErr && onError != null) { - onError(newErr); - } - - return err; - }); - }, - [setError, onError] - ); - - const handleWarning = useCallback( - (warn: Warning | undefined): void => { - onWarning(warn !== undefined); - }, - [onWarning] - ); - - const { comboOptions, labels, selectedComboOptions } = useMemo( - (): GetGenericComboBoxPropsReturn => - getGenericComboBoxProps({ - getLabel, - options: optionsMemo, - selectedOptions: selectedOptionsMemo, - }), - [optionsMemo, selectedOptionsMemo, getLabel] - ); - - const handleValuesChange = useCallback( - (newOptions: EuiComboBoxOptionOption[]): void => { - const [newValue] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); - handleError(undefined); - handleSpacesWarning(newValue); - setShowSpacesWarning(false); - - onChange(newValue ?? ''); - }, - [handleError, handleSpacesWarning, labels, onChange, optionsMemo] - ); - - const handleSearchChange = useCallback( - (searchVal: string): void => { - if (searchVal.trim() !== '' && selectedField != null) { - const err = paramIsValid(searchVal, selectedField, isRequired, touched); - handleError(err); - handleWarning(warning); - if (!err) handleSpacesWarning(searchVal); - - setSearchQuery(searchVal); - } - }, - [handleError, handleSpacesWarning, isRequired, selectedField, touched, warning, handleWarning] - ); - - const handleCreateOption = useCallback( - (option: string): boolean | undefined => { - const err = paramIsValid(option, selectedField, isRequired, touched); - handleError(err); - handleWarning(warning); - - if (err != null) { - // Explicitly reject the user's input - setShowSpacesWarning(false); - return false; - } - - handleSpacesWarning(option); - onChange(option); - return undefined; - }, - [ - isRequired, - handleSpacesWarning, - onChange, - selectedField, - touched, - handleError, - handleWarning, - warning, - ] - ); - - const setIsTouchedValue = useCallback((): void => { - setIsTouched(true); - - const err = paramIsValid(selectedValue, selectedField, isRequired, true); - handleError(err); - handleWarning(warning); - }, [ - setIsTouched, - handleError, - selectedValue, - selectedField, - isRequired, - handleWarning, - warning, - ]); - - const inputPlaceholder = useMemo((): string => { - if (isLoading || isLoadingSuggestions) { - return i18n.LOADING; - } else if (selectedField == null) { - return i18n.SELECT_FIELD_FIRST; - } else { - return placeholder; - } - }, [isLoading, selectedField, isLoadingSuggestions, placeholder]); - - const isLoadingState = useMemo( - (): boolean => isLoading || isLoadingSuggestions, - [isLoading, isLoadingSuggestions] - ); - - useEffect((): void => { - setError(undefined); - if (onError != null) { - onError(false); - } - handleSpacesWarning(selectedValue); - - onWarning(false); - }, [selectedField, selectedValue, onError, onWarning, handleSpacesWarning]); - - const defaultInput = useMemo((): JSX.Element => { - return ( - - - - ); - }, [ - rowLabel, - error, - warning, - showSpacesWarning, - selectedField, - inputPlaceholder, - isDisabled, - isLoadingState, - isClearable, - comboOptions, - selectedComboOptions, - handleValuesChange, - handleSearchChange, - handleCreateOption, - setIsTouchedValue, - fieldInputWidth, - ariaLabel, - ]); - - return defaultInput; - } -); - -AutocompleteFieldWildcardComponent.displayName = 'AutocompleteFieldWildcard'; diff --git a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts b/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts deleted file mode 100644 index dcb719ccdb56..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts +++ /dev/null @@ -1,323 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewFieldBase } from '@kbn/es-query'; - -// Copied from "src/plugins/data/common/index_patterns/fields/fields.mocks.ts" but with the types changed to "DataViewFieldBase" since that type is compatible. -// TODO: This should move out once those mocks are directly useable or in their own package, https://github.com/elastic/kibana/issues/100715 - -export const fields: DataViewFieldBase[] = [ - { - name: 'bytes', - type: 'number', - esTypes: ['long'], - count: 10, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'ssl', - type: 'boolean', - esTypes: ['boolean'], - count: 20, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: '@timestamp', - type: 'date', - esTypes: ['date'], - count: 30, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'time', - type: 'date', - esTypes: ['date'], - count: 30, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: '@tags', - type: 'string', - esTypes: ['keyword'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'utc_time', - type: 'date', - esTypes: ['date'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'phpmemory', - type: 'number', - esTypes: ['integer'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'ip', - type: 'ip', - esTypes: ['ip'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'request_body', - type: 'attachment', - esTypes: ['attachment'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'point', - type: 'geo_point', - esTypes: ['geo_point'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'area', - type: 'geo_shape', - esTypes: ['geo_shape'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'hashed', - type: 'murmur3', - esTypes: ['murmur3'], - count: 0, - scripted: false, - searchable: true, - aggregatable: false, - readFromDocValues: false, - }, - { - name: 'geo.coordinates', - type: 'geo_point', - esTypes: ['geo_point'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'extension', - type: 'string', - esTypes: ['keyword'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'machine.os', - type: 'string', - esTypes: ['text'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'machine.os.raw', - type: 'string', - esTypes: ['keyword'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - subType: { multi: { parent: 'machine.os' } }, - }, - { - name: 'geo.src', - type: 'string', - esTypes: ['keyword'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: '_id', - type: 'string', - esTypes: ['_id'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: '_type', - type: 'string', - esTypes: ['_type'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: '_source', - type: '_source', - esTypes: ['_source'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'non-filterable', - type: 'string', - esTypes: ['text'], - count: 0, - scripted: false, - searchable: false, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'non-sortable', - type: 'string', - esTypes: ['text'], - count: 0, - scripted: false, - searchable: false, - aggregatable: false, - readFromDocValues: false, - }, - { - name: 'custom_user_field', - type: 'conflict', - esTypes: ['long', 'text'], - count: 0, - scripted: false, - searchable: true, - aggregatable: true, - readFromDocValues: true, - }, - { - name: 'script string', - type: 'string', - count: 0, - scripted: true, - script: "'i am a string'", - lang: 'expression', - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'script number', - type: 'number', - count: 0, - scripted: true, - script: '1234', - lang: 'expression', - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'script date', - type: 'date', - count: 0, - scripted: true, - script: '1234', - lang: 'painless', - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'script murmur3', - type: 'murmur3', - count: 0, - scripted: true, - script: '1234', - lang: 'expression', - searchable: true, - aggregatable: true, - readFromDocValues: false, - }, - { - name: 'nestedField.child', - type: 'string', - esTypes: ['text'], - count: 0, - scripted: false, - searchable: true, - aggregatable: false, - readFromDocValues: false, - subType: { nested: { path: 'nestedField' } }, - }, - { - name: 'nestedField.nestedChild.doublyNestedChild', - type: 'string', - esTypes: ['text'], - count: 0, - scripted: false, - searchable: true, - aggregatable: false, - readFromDocValues: false, - subType: { nested: { path: 'nestedField.nestedChild' } }, - }, - { - name: 'file.path.text', - type: 'string', - esTypes: ['text'], - searchable: true, - aggregatable: false, - subType: { multi: { parent: 'file.path' } }, - }, -] as unknown as DataViewFieldBase[]; - -export const getField = (name: string) => fields.find((field) => field.name === name); diff --git a/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts deleted file mode 100644 index be0710bfd1ba..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { filterFieldToList } from '.'; - -import { getListResponseMock } from '../list_schema/index.mock'; -import { DataViewFieldBase } from '@kbn/es-query'; -import { AutocompleteListsData } from '../field_value_lists'; - -const emptyListData: AutocompleteListsData = { smallLists: [], largeLists: [] }; - -describe('#filterFieldToList', () => { - test('it returns empty list data object if given a undefined for field', () => { - const filter = filterFieldToList(emptyListData, undefined); - expect(filter).toEqual(emptyListData); - }); - - test('it returns empty list data object if filed does not contain esTypes', () => { - const field: DataViewFieldBase = { - name: 'some-name', - type: 'some-type', - }; - const filter = filterFieldToList(emptyListData, field); - expect(filter).toEqual(emptyListData); - }); - - test('it returns filtered lists of ip_range -> ip', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['ip'], - name: 'some-name', - type: 'ip', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], - largeLists: [], - }; - const filter = filterFieldToList(listData, field); - const expected = listData; - expect(filter).toEqual(expected); - }); - - test('it returns filtered lists of ip -> ip', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['ip'], - name: 'some-name', - type: 'ip', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'ip' }], - largeLists: [], - }; - const filter = filterFieldToList(listData, field); - const expected = listData; - expect(filter).toEqual(expected); - }); - - test('it returns filtered lists of keyword -> keyword', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['keyword'], - name: 'some-name', - type: 'keyword', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'keyword' }], - largeLists: [], - }; - const filter = filterFieldToList(listData, field); - const expected = listData; - expect(filter).toEqual(expected); - }); - - test('it returns filtered lists of text -> text', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['text'], - name: 'some-name', - type: 'text', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'text' }], - largeLists: [], - }; - const filter = filterFieldToList(listData, field); - const expected = listData; - expect(filter).toEqual(expected); - }); - - test('it returns small and large filtered lists of ip_range -> ip', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['ip'], - name: 'some-name', - type: 'ip', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], - largeLists: [{ ...getListResponseMock(), type: 'ip_range' }], - }; - const filter = filterFieldToList(listData, field); - const expected = listData; - expect(filter).toEqual(expected); - }); - - test('it returns 1 filtered lists of ip_range -> ip if the 2nd is not compatible type', () => { - const field: DataViewFieldBase & { esTypes: string[] } = { - esTypes: ['ip'], - name: 'some-name', - type: 'ip', - }; - const listData: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], - largeLists: [{ ...getListResponseMock(), type: 'text' }], - }; - const filter = filterFieldToList(listData, field); - const expected: AutocompleteListsData = { - smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], - largeLists: [], - }; - expect(filter).toEqual(expected); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts b/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts deleted file mode 100644 index 86d429cc9ef8..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewFieldBase } from '@kbn/es-query'; -import { typeMatch } from '../type_match'; -import { AutocompleteListsData } from '../field_value_lists'; - -/** - * Given an array of lists and optionally a field this will return all - * the lists that match against the field based on the types from the field - * - * NOTE: That we support one additional property from "FieldSpec" located here: - * src/plugins/data/common/index_patterns/fields/types.ts - * This type property is esTypes. If it exists and is on there we will read off the esTypes. - * @param lists The lists to match against the field - * @param field The field to check against the list to see if they are compatible - */ -export const filterFieldToList = ( - lists: AutocompleteListsData, - field?: DataViewFieldBase & { esTypes?: string[] } -): AutocompleteListsData => { - if (field != null) { - const { esTypes = [] } = field; - return { - smallLists: lists.smallLists.filter(({ type }) => - esTypes.some((esType: string) => typeMatch(type, esType)) - ), - largeLists: lists.largeLists.filter(({ type }) => - esTypes.some((esType: string) => typeMatch(type, esType)) - ), - }; - } else { - return { smallLists: [], largeLists: [] }; - } -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx deleted file mode 100644 index 82ca7f60de24..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx +++ /dev/null @@ -1,126 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { getGenericComboBoxProps } from '.'; - -describe('get_generic_combo_box_props', () => { - test('it returns empty arrays if "options" is empty array', () => { - const result = getGenericComboBoxProps({ - options: [], - selectedOptions: ['option1'], - getLabel: (t: string) => t, - }); - - expect(result).toEqual({ comboOptions: [], labels: [], selectedComboOptions: [] }); - }); - - test('it returns formatted props if "options" array is not empty', () => { - const result = getGenericComboBoxProps({ - options: ['option1', 'option2', 'option3'], - selectedOptions: [], - getLabel: (t: string) => t, - }); - - expect(result).toEqual({ - comboOptions: [ - { - label: 'option1', - }, - { - label: 'option2', - }, - { - label: 'option3', - }, - ], - labels: ['option1', 'option2', 'option3'], - selectedComboOptions: [], - }); - }); - - test('it does not return "selectedOptions" items that do not appear in "options"', () => { - const result = getGenericComboBoxProps({ - options: ['option1', 'option2', 'option3'], - selectedOptions: ['option4'], - getLabel: (t: string) => t, - }); - - expect(result).toEqual({ - comboOptions: [ - { - label: 'option1', - }, - { - label: 'option2', - }, - { - label: 'option3', - }, - ], - labels: ['option1', 'option2', 'option3'], - selectedComboOptions: [], - }); - }); - - test('it returns "selectedOptions" items that do appear in "options"', () => { - const result = getGenericComboBoxProps({ - options: ['option1', 'option2', 'option3'], - selectedOptions: ['option2'], - getLabel: (t: string) => t, - }); - - expect(result).toEqual({ - comboOptions: [ - { - label: 'option1', - }, - { - label: 'option2', - }, - { - label: 'option3', - }, - ], - labels: ['option1', 'option2', 'option3'], - selectedComboOptions: [ - { - label: 'option2', - }, - ], - }); - }); - - test('it returns "disabledOptions" items that do appear in "options" as disabled', () => { - const result = getGenericComboBoxProps({ - options: ['option1', 'option2', 'option3'], - selectedOptions: [], - disabledOptions: ['option2'], - getLabel: (t: string) => t, - }); - - expect(result).toEqual({ - comboOptions: [ - { - label: 'option1', - disabled: false, - }, - { - label: 'option2', - disabled: true, - }, - { - label: 'option3', - disabled: false, - }, - ], - labels: ['option1', 'option2', 'option3'], - selectedComboOptions: [], - }); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.ts b/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.ts deleted file mode 100644 index 2f2a6697c422..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EuiComboBoxOptionOption } from '@elastic/eui'; - -export interface GetGenericComboBoxPropsReturn { - comboOptions: EuiComboBoxOptionOption[]; - labels: string[]; - selectedComboOptions: EuiComboBoxOptionOption[]; -} - -/** - * Determines the options, selected values and option labels for EUI combo box - * @param options options user can select from - * @param selectedOptions user selection if any - * @param getLabel helper function to know which property to use for labels - */ -export const getGenericComboBoxProps = ({ - getLabel, - options, - selectedOptions, - disabledOptions, -}: { - getLabel: (value: T) => string; - options: T[]; - selectedOptions: T[]; - disabledOptions?: T[]; -}): GetGenericComboBoxPropsReturn => { - const newLabels = options.map(getLabel); - const disabledLabels = disabledOptions?.map(getLabel); - const newComboOptions: EuiComboBoxOptionOption[] = newLabels.map((label) => ({ - label, - disabled: disabledLabels && disabledLabels.length !== 0 && disabledLabels.includes(label), - })); - const newSelectedComboOptions = selectedOptions - .map(getLabel) - .filter((option) => { - return newLabels.indexOf(option) !== -1; - }) - .map((option) => { - return newComboOptions[newLabels.indexOf(option)]; - }); - - return { - comboOptions: newComboOptions, - labels: newLabels, - selectedComboOptions: newSelectedComboOptions, - }; -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts deleted file mode 100644 index 711e7ea87a8e..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts +++ /dev/null @@ -1,59 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - doesNotExistOperator, - EVENT_FILTERS_OPERATORS, - ALL_OPERATORS, - existsOperator, - isNotOperator, - isOperator, -} from '@kbn/securitysolution-list-utils'; -import { getOperators } from '.'; -import { getField } from '../fields/index.mock'; - -describe('#getOperators', () => { - test('it returns "isOperator" if passed in field is "undefined"', () => { - const operator = getOperators(undefined); - - expect(operator).toEqual([isOperator]); - }); - - test('it returns expected operators when field type is "boolean"', () => { - const operator = getOperators(getField('ssl')); - - expect(operator).toEqual([isOperator, isNotOperator, existsOperator, doesNotExistOperator]); - }); - - test('it returns "isOperator" when field type is "nested"', () => { - const operator = getOperators({ - name: 'nestedField', - scripted: false, - subType: { nested: { path: 'nestedField' } }, - type: 'nested', - }); - - expect(operator).toEqual([isOperator]); - }); - - test('it includes a "matches" operator when field is "file.path.text"', () => { - const operator = getOperators({ - name: 'file.path.text', - type: 'simple', - }); - - expect(operator).toEqual(EVENT_FILTERS_OPERATORS); - }); - - test('it returns all operator types when field type is not null, boolean, or nested', () => { - const operator = getOperators(getField('machine.os.raw')); - - expect(operator).toEqual(ALL_OPERATORS); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/get_operators/index.ts b/packages/kbn-securitysolution-autocomplete/src/get_operators/index.ts deleted file mode 100644 index dbb36fd479df..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/get_operators/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewFieldBase } from '@kbn/es-query'; - -import { - ALL_OPERATORS, - EVENT_FILTERS_OPERATORS, - OperatorOption, - doesNotExistOperator, - existsOperator, - isNotOperator, - isOperator, -} from '@kbn/securitysolution-list-utils'; - -/** - * Returns the appropriate operators given a field type - * - * @param field DataViewFieldBase selected field - * - */ -export const getOperators = (field: DataViewFieldBase | undefined): OperatorOption[] => { - if (field == null) { - return [isOperator]; - } else if (field.type === 'boolean') { - return [isOperator, isNotOperator, existsOperator, doesNotExistOperator]; - } else if (field.type === 'nested') { - return [isOperator]; - } else if (field.name === 'file.path.text') { - return EVENT_FILTERS_OPERATORS; - } else { - return ALL_OPERATORS; - } -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/hooks/index.ts b/packages/kbn-securitysolution-autocomplete/src/hooks/index.ts deleted file mode 100644 index 5aa216af4c67..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/hooks/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './use_field_value_autocomplete'; diff --git a/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts deleted file mode 100644 index 836744f3ede2..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts +++ /dev/null @@ -1,300 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { waitFor, renderHook } from '@testing-library/react'; -import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; - -import { UseFieldValueAutocompleteReturn, useFieldValueAutocomplete } from '.'; -import { getField } from '../../fields/index.mock'; -import { autocompleteStartMock } from '../../autocomplete/index.mock'; -import { DataViewFieldBase } from '@kbn/es-query'; - -// Copied from "src/plugins/data/common/index_patterns/index_pattern.stub.ts" -// TODO: Remove this in favor of the above if/when it is ported, https://github.com/elastic/kibana/issues/100715 -export const stubIndexPatternWithFields = { - id: '1234', - title: 'logstash-*', - fields: [ - { - name: 'response', - type: 'number', - esTypes: ['integer'], - aggregatable: true, - filterable: true, - searchable: true, - }, - ], -}; - -describe('use_field_value_autocomplete', () => { - const onErrorMock = jest.fn(); - const getValueSuggestionsMock = jest.fn().mockResolvedValue(['value 1', 'value 2']); - - afterEach(() => { - onErrorMock.mockClear(); - getValueSuggestionsMock.mockClear(); - }); - - test('initializes hook', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: undefined, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: undefined, - }) - ); - await waitFor(() => expect(result.current).toEqual([false, true, [], result.current[3]])); - }); - - test('does not call autocomplete service if "operatorType" is "exists"', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.EXISTS, - query: '', - selectedField: getField('machine.os'), - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; - - expect(result.current).toEqual(expectedResult); - expect(getValueSuggestionsMock).not.toHaveBeenCalled(); - }); - }); - - test('does not call autocomplete service if "selectedField" is undefined', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.EXISTS, - query: '', - selectedField: undefined, - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; - - expect(result.current).toEqual(expectedResult); - expect(getValueSuggestionsMock).not.toHaveBeenCalled(); - }); - }); - - test('does not call autocomplete service if "indexPattern" is undefined', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: undefined, - operatorType: OperatorTypeEnum.EXISTS, - query: '', - selectedField: getField('machine.os'), - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; - - expect(result.current).toEqual(expectedResult); - expect(getValueSuggestionsMock).not.toHaveBeenCalled(); - }); - }); - - test('it uses full path name for nested fields to fetch suggestions', async () => { - const suggestionsMock = jest.fn().mockResolvedValue([]); - - const selectedField: DataViewFieldBase | undefined = getField('nestedField.child'); - if (selectedField == null) { - throw new TypeError('selectedField for this test should always be defined'); - } - - const { signal } = new AbortController(); - renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: suggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: { ...selectedField, name: 'child' }, - }) - ); - - await waitFor(() => - expect(suggestionsMock).toHaveBeenCalledWith({ - field: { ...getField('nestedField.child'), name: 'nestedField.child' }, - indexPattern: { - fields: [ - { - aggregatable: true, - esTypes: ['integer'], - filterable: true, - name: 'response', - searchable: true, - type: 'number', - }, - ], - id: '1234', - title: 'logstash-*', - }, - query: '', - signal, - useTimeRange: false, - }) - ); - }); - - test('returns "isSuggestingValues" of false if field type is boolean', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: getField('ssl'), - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [false, false, [], result.current[3]]; - - expect(result.current).toEqual(expectedResult); - expect(getValueSuggestionsMock).not.toHaveBeenCalled(); - }); - }); - - test('returns "isSuggestingValues" of false to note that autocomplete service is not in use if no autocomplete suggestions available', async () => { - const suggestionsMock = jest.fn().mockResolvedValue([]); - - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: suggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: getField('bytes'), - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [false, false, [], result.current[3]]; - - expect(suggestionsMock).toHaveBeenCalled(); - expect(result.current).toEqual(expectedResult); - }); - }); - - test('returns suggestions', async () => { - const { signal } = new AbortController(); - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: getField('@tags'), - }) - ); - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [ - false, - true, - ['value 1', 'value 2'], - result.current[3], - ]; - - expect(getValueSuggestionsMock).toHaveBeenCalledWith({ - field: getField('@tags'), - indexPattern: stubIndexPatternWithFields, - query: '', - signal, - useTimeRange: false, - }); - expect(result.current).toEqual(expectedResult); - }); - }); - - test('returns new suggestions on subsequent calls', async () => { - const { result } = renderHook(() => - useFieldValueAutocomplete({ - autocompleteService: { - ...autocompleteStartMock, - getValueSuggestions: getValueSuggestionsMock, - }, - fieldValue: '', - indexPattern: stubIndexPatternWithFields, - operatorType: OperatorTypeEnum.MATCH, - query: '', - selectedField: getField('@tags'), - }) - ); - - await waitFor(() => expect(result.current[3]).not.toBeNull()); - - // Added check for typescripts sake, if null, - // would not reach below logic as test would stop above - if (result.current[3] != null) { - result.current[3]({ - fieldSelected: getField('@tags'), - patterns: stubIndexPatternWithFields, - searchQuery: '', - value: 'hello', - }); - } - - await waitFor(() => { - const expectedResult: UseFieldValueAutocompleteReturn = [ - false, - true, - ['value 1', 'value 2'], - result.current[3], - ]; - - expect(getValueSuggestionsMock).toHaveBeenCalledTimes(2); - expect(result.current).toEqual(expectedResult); - }); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts b/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts deleted file mode 100644 index 9fff2abfd5be..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts +++ /dev/null @@ -1,123 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useEffect, useRef, useState } from 'react'; -import { debounce } from 'lodash'; -import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; -import { DataViewBase, DataViewFieldBase, getDataViewFieldSubtypeNested } from '@kbn/es-query'; - -// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 -// import { AutocompleteStart } from '../../../../../../../../src/plugins/unified_search/public'; -type AutocompleteStart = any; - -interface FuncArgs { - fieldSelected: DataViewFieldBase | undefined; - patterns: DataViewBase | undefined; - searchQuery: string; - value: string | string[] | undefined; -} - -type Func = (args: FuncArgs) => void; - -export type UseFieldValueAutocompleteReturn = [boolean, boolean, string[], Func | null]; - -export interface UseFieldValueAutocompleteProps { - autocompleteService: AutocompleteStart; - fieldValue: string | string[] | undefined; - indexPattern: DataViewBase | undefined; - operatorType: OperatorTypeEnum; - query: string; - selectedField: DataViewFieldBase | undefined; -} -/** - * Hook for using the field value autocomplete service - */ -export const useFieldValueAutocomplete = ({ - selectedField, - operatorType, - fieldValue, - query, - indexPattern, - autocompleteService, -}: UseFieldValueAutocompleteProps): UseFieldValueAutocompleteReturn => { - const [isLoading, setIsLoading] = useState(false); - const [isSuggestingValues, setIsSuggestingValues] = useState(true); - const [suggestions, setSuggestions] = useState([]); - const updateSuggestions = useRef(null); - - useEffect(() => { - let isSubscribed = true; - const abortCtrl = new AbortController(); - - const fetchSuggestions = debounce( - async ({ fieldSelected, patterns, searchQuery }: FuncArgs) => { - try { - if (isSubscribed) { - if (fieldSelected == null || patterns == null) { - return; - } - - if (fieldSelected.type === 'boolean') { - setIsSuggestingValues(false); - return; - } - - setIsLoading(true); - const subTypeNested = getDataViewFieldSubtypeNested(fieldSelected); - const field = subTypeNested - ? { - ...fieldSelected, - name: `${subTypeNested.nested.path}.${fieldSelected.name}`, - } - : fieldSelected; - - const newSuggestions = await autocompleteService.getValueSuggestions({ - field, - indexPattern: patterns, - query: searchQuery, - signal: abortCtrl.signal, - useTimeRange: false, - }); - - if (newSuggestions.length === 0) { - setIsSuggestingValues(false); - } - - setIsLoading(false); - setSuggestions([...newSuggestions]); - } - } catch (error) { - if (isSubscribed) { - setSuggestions([]); - setIsLoading(false); - } - } - }, - 500 - ); - - if (operatorType !== OperatorTypeEnum.EXISTS) { - fetchSuggestions({ - fieldSelected: selectedField, - patterns: indexPattern, - searchQuery: query, - value: fieldValue, - }); - } - - updateSuggestions.current = fetchSuggestions; - - return (): void => { - isSubscribed = false; - abortCtrl.abort(); - }; - }, [selectedField, operatorType, fieldValue, indexPattern, query, autocompleteService]); - - return [isLoading, isSuggestingValues, suggestions, updateSuggestions.current]; -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts b/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts deleted file mode 100644 index e2c2c9b0fe05..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts +++ /dev/null @@ -1,62 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - FoundListSchema, - ListSchema, - FoundListsBySizeSchema, -} from '@kbn/securitysolution-io-ts-list-types'; - -// TODO: Once this mock is available within packages, use it instead, https://github.com/elastic/kibana/issues/100715 -// import { getFoundListSchemaMock } from '../../../../../lists/common/schemas/response/found_list_schema.mock'; -export const getFoundListSchemaMock = (): FoundListSchema => ({ - cursor: '123', - data: [getListResponseMock()], - page: 1, - per_page: 1, - total: 1, -}); - -export const getFoundListsBySizeSchemaMock = (): FoundListsBySizeSchema => ({ - smallLists: [getListResponseMock()], - largeLists: [getListResponseMock()], -}); - -// TODO: Once these mocks are available from packages use it instead, https://github.com/elastic/kibana/issues/100715 -export const DATE_NOW = '2020-04-20T15:25:31.830Z'; -export const USER = 'some user'; -export const IMMUTABLE = false; -export const VERSION = 1; -export const DESCRIPTION = 'some description'; -export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; -export const LIST_ID = 'some-list-id'; -export const META = {}; -export const TYPE = 'ip'; -export const NAME = 'some name'; - -// TODO: Once this mock is available within packages, use it instead, https://github.com/elastic/kibana/issues/100715 -// import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; -export const getListResponseMock = (): ListSchema => ({ - '@timestamp': DATE_NOW, - _version: undefined, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - deserializer: undefined, - id: LIST_ID, - immutable: IMMUTABLE, - meta: META, - name: NAME, - serializer: undefined, - tie_breaker_id: TIE_BREAKER, - type: TYPE, - updated_at: DATE_NOW, - updated_by: USER, - version: VERSION, -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx deleted file mode 100644 index 4d2112d8f31d..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx +++ /dev/null @@ -1,255 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { mount } from 'enzyme'; -import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { isNotOperator, isOperator } from '@kbn/securitysolution-list-utils'; - -import { OperatorComponent } from '.'; -import { getField } from '../fields/index.mock'; - -describe('operator', () => { - test('it renders disabled if "isDisabled" is true', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"] input`).prop('disabled') - ).toBeTruthy(); - }); - - test('it renders loading if "isLoading" is true', () => { - const wrapper = mount( - - ); - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"] button`).at(0).simulate('click'); - expect( - wrapper - .find(`EuiComboBoxOptionsList[data-test-subj="operatorAutocompleteComboBox-optionsList"]`) - .prop('isLoading') - ).toBeTruthy(); - }); - - test('it allows user to clear values if "isClearable" is true', () => { - const wrapper = mount( - - ); - - expect(wrapper.find(`button[data-test-subj="comboBoxClearButton"]`).exists()).toBeTruthy(); - }); - - test('it displays "operatorOptions" if param is passed in with items', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') - ).toEqual([{ label: 'is not' }]); - }); - - test('it does not display "operatorOptions" if param is passed in with no items', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') - ).toEqual([ - { - label: 'is', - }, - { - label: 'is not', - }, - { - label: 'is one of', - }, - { - label: 'is not one of', - }, - { - label: 'exists', - }, - { - label: 'does not exist', - }, - { - label: 'is in list', - }, - { - label: 'is not in list', - }, - { - label: 'matches', - }, - { - label: 'does not match', - }, - ]); - }); - - test('it correctly displays selected operator', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="operatorAutocompleteComboBox"] input').at(0).props().value - ).toEqual('is'); - }); - - test('it only displays subset of operators if field type is nested', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') - ).toEqual([{ label: 'is' }]); - }); - - test('it only displays subset of operators if field type is boolean', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') - ).toEqual([ - { label: 'is' }, - { label: 'is not' }, - { label: 'exists' }, - { label: 'does not exist' }, - ]); - }); - - test('it only displays subset of operators if field name is "file.path.text"', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') - ).toEqual([ - { label: 'is' }, - { label: 'is not' }, - { label: 'is one of' }, - { label: 'is not one of' }, - { label: 'matches' }, - { label: 'does not match' }, - ]); - }); - - test('it invokes "onChange" when option selected', () => { - const mockOnChange = jest.fn(); - const wrapper = mount( - - ); - - ( - wrapper.find(EuiComboBox).props() as unknown as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - } - ).onChange([{ label: 'is not' }]); - - expect(mockOnChange).toHaveBeenCalledWith([ - { message: 'is not', operator: 'excluded', type: 'match', value: 'is_not' }, - ]); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx deleted file mode 100644 index c3d91c16eae9..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx +++ /dev/null @@ -1,101 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useCallback, useMemo } from 'react'; -import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { OperatorOption } from '@kbn/securitysolution-list-utils'; -import { DataViewFieldBase } from '@kbn/es-query'; - -import { getOperators } from '../get_operators'; -import { - getGenericComboBoxProps, - GetGenericComboBoxPropsReturn, -} from '../get_generic_combo_box_props'; - -const AS_PLAIN_TEXT = { asPlainText: true }; - -interface OperatorState { - isClearable: boolean; - isDisabled: boolean; - isLoading: boolean; - onChange: (arg: OperatorOption[]) => void; - operator: OperatorOption; - operatorInputWidth?: number; - operatorOptions?: OperatorOption[]; - placeholder: string; - selectedField: DataViewFieldBase | undefined; - 'aria-label'?: string; -} - -export const OperatorComponent: React.FC = ({ - isClearable = false, - isDisabled = false, - isLoading = false, - onChange, - operator, - operatorOptions, - operatorInputWidth = 150, - placeholder, - selectedField, - 'aria-label': ariaLabel, -}): JSX.Element => { - const getLabel = useCallback(({ message }: OperatorOption): string => message, []); - const optionsMemo = useMemo( - (): OperatorOption[] => - operatorOptions != null && operatorOptions.length > 0 - ? operatorOptions - : getOperators(selectedField), - [operatorOptions, selectedField] - ); - const selectedOptionsMemo = useMemo( - (): OperatorOption[] => (operator ? [operator] : []), - [operator] - ); - const { comboOptions, labels, selectedComboOptions } = useMemo( - (): GetGenericComboBoxPropsReturn => - getGenericComboBoxProps({ - getLabel, - options: optionsMemo, - selectedOptions: selectedOptionsMemo, - }), - [optionsMemo, selectedOptionsMemo, getLabel] - ); - - const handleValuesChange = useCallback( - (newOptions: EuiComboBoxOptionOption[]): void => { - const newValues: OperatorOption[] = newOptions.map( - ({ label }) => optionsMemo[labels.indexOf(label)] - ); - onChange(newValues); - }, - [labels, onChange, optionsMemo] - ); - - const inputWidth = useMemo(() => { - return { width: `${operatorInputWidth}px` }; - }, [operatorInputWidth]); - - return ( - - ); -}; - -OperatorComponent.displayName = 'Operator'; diff --git a/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts deleted file mode 100644 index aef6fc4acffa..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { paramContainsSpace } from '.'; - -describe('param_contains_space', () => { - test('should return true if leading spaces were found', () => { - expect(paramContainsSpace(' test')).toBeTruthy(); - }); - test('should return true if trailing spaces were found', () => { - expect(paramContainsSpace('test ')).toBeTruthy(); - }); - test('should return true if both trailing and leading spaces were found', () => { - expect(paramContainsSpace(' test ')).toBeTruthy(); - }); - test('should return true if tabs was found', () => { - expect(paramContainsSpace('\ttest')).toBeTruthy(); - }); - test('should return false if no spaces were found', () => { - expect(paramContainsSpace('test test')).toBeFalsy(); - }); - test('should return false if param is falsy', () => { - expect(paramContainsSpace('')).toBeFalsy(); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.ts b/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.ts deleted file mode 100644 index 996167f20536..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const paramContainsSpace = (param: string) => param && param.trim().length !== param.length; diff --git a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts deleted file mode 100644 index c530bca356cb..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { paramIsValid } from '.'; -import { getField } from '../fields/index.mock'; -import * as i18n from '../translations'; -import moment from 'moment'; - -describe('params_is_valid', () => { - beforeEach(() => { - // Disable momentJS deprecation warning and it looks like it is not typed either so - // we have to disable the type as well and cannot extend it easily. - ( - moment as unknown as { - suppressDeprecationWarnings: boolean; - } - ).suppressDeprecationWarnings = true; - }); - - afterEach(() => { - // Re-enable momentJS deprecation warning and it looks like it is not typed either so - // we have to disable the type as well and cannot extend it easily. - ( - moment as unknown as { - suppressDeprecationWarnings: boolean; - } - ).suppressDeprecationWarnings = false; - }); - - test('returns no errors if no field has been selected', () => { - const isValid = paramIsValid('', undefined, true, false); - - expect(isValid).toBeUndefined(); - }); - - test('returns error string if user has touched a required input and left empty', () => { - const isValid = paramIsValid(undefined, getField('@timestamp'), true, true); - - expect(isValid).toEqual(i18n.FIELD_REQUIRED_ERR); - }); - - test('returns no errors if required input is empty but user has not yet touched it', () => { - const isValid = paramIsValid(undefined, getField('@timestamp'), true, false); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if user has touched an input that is not required and left empty', () => { - const isValid = paramIsValid(undefined, getField('@timestamp'), false, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if user has touched an input that is not required and left empty string', () => { - const isValid = paramIsValid('', getField('@timestamp'), false, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if field is of type date and value is valid', () => { - const isValid = paramIsValid('1994-11-05T08:15:30-05:00', getField('@timestamp'), false, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns errors if filed is of type date and value is not valid', () => { - const isValid = paramIsValid('1593478826', getField('@timestamp'), false, true); - - expect(isValid).toEqual(i18n.DATE_ERR); - }); - - test('returns no errors if field is of type number and value is an integer', () => { - const isValid = paramIsValid('4', getField('bytes'), true, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if field is of type number and value is a float', () => { - const isValid = paramIsValid('4.3', getField('bytes'), true, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns no errors if field is of type number and value is a long', () => { - const isValid = paramIsValid('-9223372036854775808', getField('bytes'), true, true); - - expect(isValid).toBeUndefined(); - }); - - test('returns errors if field is of type number and value is "hello"', () => { - const isValid = paramIsValid('hello', getField('bytes'), true, true); - - expect(isValid).toEqual(i18n.NUMBER_ERR); - }); - - test('returns errors if field is of type number and value is "123abc"', () => { - const isValid = paramIsValid('123abc', getField('bytes'), true, true); - - expect(isValid).toEqual(i18n.NUMBER_ERR); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.ts b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.ts deleted file mode 100644 index 5abde0b36c4c..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import dateMath from '@kbn/datemath'; -import { DataViewFieldBase } from '@kbn/es-query'; -import { checkEmptyValue } from '../check_empty_value'; - -import * as i18n from '../translations'; - -/** - * Very basic validation for values - * @param param the value being checked - * @param field the selected field - * @param isRequired whether or not an empty value is allowed - * @param touched has field been touched by user - * @returns undefined if valid, string with error message if invalid - */ -export const paramIsValid = ( - param: string | undefined, - field: DataViewFieldBase | undefined, - isRequired: boolean, - touched: boolean -): string | undefined => { - if (field == null) { - return undefined; - } - - const emptyValueError = checkEmptyValue(param, field, isRequired, touched); - if (emptyValueError !== null) { - return emptyValueError; - } - - switch (field.type) { - case 'date': - const moment = dateMath.parse(param ?? ''); - const isDate = Boolean(moment && moment.isValid()); - return isDate ? undefined : i18n.DATE_ERR; - case 'number': - const isNum = param != null && param.trim() !== '' && !isNaN(+param); - return isNum ? undefined : i18n.NUMBER_ERR; - default: - return undefined; - } -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/translations/index.ts b/packages/kbn-securitysolution-autocomplete/src/translations/index.ts deleted file mode 100644 index 01671880d2dc..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/translations/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { i18n } from '@kbn/i18n'; - -export const LOADING = i18n.translate('autocomplete.loadingDescription', { - defaultMessage: 'Loading...', -}); - -export const SELECT_FIELD_FIRST = i18n.translate('autocomplete.selectField', { - defaultMessage: 'Please select a field first...', -}); - -export const FIELD_REQUIRED_ERR = i18n.translate('autocomplete.fieldRequiredError', { - defaultMessage: 'Value cannot be empty', -}); - -export const NUMBER_ERR = i18n.translate('autocomplete.invalidNumberError', { - defaultMessage: 'Not a valid number', -}); - -export const DATE_ERR = i18n.translate('autocomplete.invalidDateError', { - defaultMessage: 'Not a valid date', -}); - -export const BINARY_TYPE_NOT_SUPPORTED = i18n.translate('autocomplete.invalidBinaryType', { - defaultMessage: 'Binary fields are currently unsupported', -}); -export const FIELD_SPACE_WARNING = i18n.translate('autocomplete.fieldSpaceWarning', { - defaultMessage: "Warning: Spaces at the start or end of this value aren't being displayed.", -}); - -export const LISTS_TOOLTIP_INFO = i18n.translate('autocomplete.listsTooltipWarning', { - defaultMessage: "Lists that aren't able to be processed by this rule type will be disabled.", -}); - -export const SEE_DOCUMENTATION = i18n.translate('autocomplete.seeDocumentation', { - defaultMessage: 'See Documentation', -}); - -export const FIELD_CONFLICT_INDICES_WARNING_TITLE = i18n.translate( - 'autocomplete.conflictIndicesWarning.title', - { - defaultMessage: 'Mapping Conflict', - } -); - -export const FIELD_CONFLICT_INDICES_WARNING_DESCRIPTION = i18n.translate( - 'autocomplete.conflictIndicesWarning.description', - { - defaultMessage: - 'This field is defined as different types across the following indices or is unmapped. This can cause unexpected query results.', - } -); - -export const CONFLICT_MULTIPLE_INDEX_DESCRIPTION = (name: string, count: number): string => - i18n.translate('autocomplete.conflictIndicesWarning.index.description', { - defaultMessage: '{name} ({count} indices)', - values: { count, name }, - }); - -export const SHOW_VALUE_LIST_MODAL = i18n.translate('autocomplete.showValueListModal', { - defaultMessage: 'Show value list', -}); - -// eslint-disable-next-line import/no-default-export -export default { - LOADING, - SELECT_FIELD_FIRST, - FIELD_REQUIRED_ERR, - NUMBER_ERR, - DATE_ERR, - FIELD_SPACE_WARNING, - BINARY_TYPE_NOT_SUPPORTED, -}; diff --git a/packages/kbn-securitysolution-autocomplete/src/type_match/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/type_match/index.test.ts deleted file mode 100644 index 15c7c3f580da..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/type_match/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { typeMatch } from '.'; - -describe('type_match', () => { - test('ip -> ip is true', () => { - expect(typeMatch('ip', 'ip')).toEqual(true); - }); - - test('keyword -> keyword is true', () => { - expect(typeMatch('keyword', 'keyword')).toEqual(true); - }); - - test('text -> text is true', () => { - expect(typeMatch('text', 'text')).toEqual(true); - }); - - test('ip_range -> ip is true', () => { - expect(typeMatch('ip_range', 'ip')).toEqual(true); - }); - - test('date_range -> date is true', () => { - expect(typeMatch('date_range', 'date')).toEqual(true); - }); - - test('double_range -> double is true', () => { - expect(typeMatch('double_range', 'double')).toEqual(true); - }); - - test('float_range -> float is true', () => { - expect(typeMatch('float_range', 'float')).toEqual(true); - }); - - test('integer_range -> integer is true', () => { - expect(typeMatch('integer_range', 'integer')).toEqual(true); - }); - - test('long_range -> long is true', () => { - expect(typeMatch('long_range', 'long')).toEqual(true); - }); - - test('ip -> date is false', () => { - expect(typeMatch('ip', 'date')).toEqual(false); - }); - - test('long -> float is false', () => { - expect(typeMatch('long', 'float')).toEqual(false); - }); - - test('integer -> long is false', () => { - expect(typeMatch('integer', 'long')).toEqual(false); - }); -}); diff --git a/packages/kbn-securitysolution-autocomplete/src/type_match/index.ts b/packages/kbn-securitysolution-autocomplete/src/type_match/index.ts deleted file mode 100644 index 4d5899a376a0..000000000000 --- a/packages/kbn-securitysolution-autocomplete/src/type_match/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { Type } from '@kbn/securitysolution-io-ts-list-types'; - -/** - * Given an input list type and a string based ES type this will match - * if they're exact or if they are compatible with a range - * @param type The type to match against the esType - * @param esType The ES type to match with - */ -export const typeMatch = (type: Type, esType: string): boolean => { - return ( - type === esType || - (type === 'ip_range' && esType === 'ip') || - (type === 'date_range' && esType === 'date') || - (type === 'double_range' && esType === 'double') || - (type === 'float_range' && esType === 'float') || - (type === 'integer_range' && esType === 'integer') || - (type === 'long_range' && esType === 'long') - ); -}; diff --git a/packages/kbn-securitysolution-autocomplete/tsconfig.json b/packages/kbn-securitysolution-autocomplete/tsconfig.json deleted file mode 100644 index f7df7da6f06a..000000000000 --- a/packages/kbn-securitysolution-autocomplete/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "include": [ - "**/*.ts", - "**/*.tsx", - ], - "kbn_references": [ - "@kbn/datemath", - "@kbn/es-query", - "@kbn/i18n", - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-list-hooks", - "@kbn/securitysolution-list-utils", - "@kbn/doc-links", - "@kbn/securitysolution-utils", - ], - "exclude": [ - "target/**/*", - ], -} diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.ts b/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.ts deleted file mode 100644 index 42a3b67106c0..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Create endpoint list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { EndpointList } from '../model/endpoint_list_common.gen'; - -export type CreateEndpointListResponse = z.infer; -export const CreateEndpointListResponse = EndpointList; diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml b/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml deleted file mode 100644 index b2ca0f563617..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml +++ /dev/null @@ -1,45 +0,0 @@ -openapi: 3.0.0 -info: - title: Create endpoint list API endpoint - version: '2023-10-31' -paths: - /api/endpoint_list: - post: - x-labels: [serverless, ess] - x-codegen-enabled: true - operationId: CreateEndpointList - summary: Create an endpoint exception list - description: Create an endpoint exception list, which groups endpoint exception list items. If an endpoint exception list already exists, an empty response is returned. - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointList' - 400: - description: Invalid input data - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Insufficient privileges - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 500: - description: Internal server error - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml b/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml deleted file mode 100644 index 69db50616918..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml +++ /dev/null @@ -1,64 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete endpoint list item API endpoint - version: '2023-10-31' -paths: - /api/endpoint_list/items: - delete: - x-labels: [serverless, ess] - x-codegen-enabled: true - operationId: DeleteEndpointListItem - summary: Delete an endpoint exception list item - description: Delete an endpoint exception list item using the `id` or `item_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' - - name: item_id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' - 400: - description: Invalid input data - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Insufficient privileges - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Endpoint list item not found - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml b/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml deleted file mode 100644 index 6dc2fcaa7e87..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml +++ /dev/null @@ -1,113 +0,0 @@ -openapi: 3.0.0 -info: - title: Find endpoint list items API endpoint - version: '2023-10-31' -paths: - /api/endpoint_list/items/_find: - get: - x-labels: [serverless, ess] - x-codegen-enabled: true - operationId: FindEndpointListItems - summary: Get endpoint exception list items - description: Get a list of all endpoint exception list items. - parameters: - - name: filter - in: query - required: false - description: | - Filters the returned results according to the value of the specified field, - using the `:` syntax. - schema: - $ref: '#/components/schemas/FindEndpointListItemsFilter' - - name: page - in: query - required: false - description: The page number to return - schema: - type: integer - minimum: 0 - - name: per_page - in: query - required: false - description: The number of exception list items to return per page - schema: - type: integer - minimum: 0 - - name: sort_field - in: query - required: false - description: Determines which field is used to sort the results - schema: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - name: sort_order - in: query - required: false - description: Determines the sort order, which can be `desc` or `asc` - schema: - type: string - enum: [desc, asc] - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - data: - type: array - items: - $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' - page: - type: integer - minimum: 0 - per_page: - type: integer - minimum: 0 - total: - type: integer - minimum: 0 - pit: - type: string - required: - - data - - page - - per_page - - total - 400: - description: Invalid input data - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Insufficient privileges - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Endpoint list not found - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - -components: - schemas: - FindEndpointListItemsFilter: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts b/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts deleted file mode 100644 index c71b02c448db..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './create_endpoint_list/create_endpoint_list.gen'; -export * from './create_endpoint_list_item/create_endpoint_list_item.gen'; -export * from './read_endpoint_list_item/read_endpoint_list_item.gen'; -export * from './update_endpoint_list_item/update_endpoint_list_item.gen'; -export * from './delete_endpoint_list_item/delete_endpoint_list_item.gen'; -export * from './find_endpoint_list_item/find_endpoint_list_item.gen'; diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.ts b/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.ts deleted file mode 100644 index 6c8093246b1a..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Common Exception List Attributes - * version: not applicable - */ - -import { z } from '@kbn/zod'; - -import { - ExceptionList, - ExceptionListItem, -} from '@kbn/securitysolution-exceptions-common/api/model/exception_list_common.gen'; - -export type EndpointList = z.infer; -export const EndpointList = z.union([ExceptionList, z.object({}).strict()]); - -export type EndpointListItem = z.infer; -export const EndpointListItem = ExceptionListItem; diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml b/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml deleted file mode 100644 index 8a4e0b291c76..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml +++ /dev/null @@ -1,66 +0,0 @@ -openapi: 3.0.0 -info: - title: Read endpoint list item API endpoint - version: '2023-10-31' -paths: - /api/endpoint_list/items: - get: - x-labels: [serverless, ess] - x-codegen-enabled: true - operationId: ReadEndpointListItem - summary: Get an endpoint exception list item - description: Get the details of an endpoint exception list item using the `id` or `item_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' - - name: item_id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: array - items: - $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' - 400: - description: Invalid input data - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Insufficient privileges - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Endpoint list item not found - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/package.json b/packages/kbn-securitysolution-endpoint-exceptions-common/package.json deleted file mode 100644 index 78470be1d4e4..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "description": "OpenAPI Endpoint Exceptions Common", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "name": "@kbn/securitysolution-endpoint-exceptions-common", - "private": true, - "version": "1.0.0", - "scripts": { - "openapi:generate": "node scripts/openapi_generate", - "openapi:bundle": "node scripts/openapi_bundle" - } -} diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js b/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js deleted file mode 100644 index e5a02965593c..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { bundle } = require('@kbn/openapi-bundler'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/serverless/security_solution_endpoint_exceptions_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['serverless'], - prototypeDocument: { - info: { - title: 'Security Endpoint Exceptions API (Elastic Cloud Serverless)', - description: 'Endpoint Exceptions API allow you to manage Endpoint lists.', - }, - tags: [ - { - name: 'Security Endpoint Exceptions API', - 'x-displayName': 'Security endpoint exceptions', - description: - "Endpoint Exceptions API allows you to manage detection rule endpoint exceptions to prevent a rule from generating an alert from incoming events even when the rule's other criteria are met.", - }, - ], - }, - }, - }); - - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/ess/security_solution_endpoint_exceptions_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['ess'], - prototypeDocument: { - info: { - title: 'Security Endpoint Exceptions API (Elastic Cloud and self-hosted)', - description: 'Endpoint Exceptions API allow you to manage Endpoint lists.', - }, - tags: [ - { - name: 'Security Endpoint Exceptions API', - 'x-displayName': 'Security endpoint exceptions', - description: - "Endpoint Exceptions API allows you to manage detection rule endpoint exceptions to prevent a rule from generating an alert from incoming events even when the rule's other criteria are met.", - }, - ], - }, - }, - }); -})(); diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js b/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js deleted file mode 100644 index bca85786a518..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { generate } = require('@kbn/openapi-generator'); -const { REPO_ROOT } = require('@kbn/repo-info'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await generate({ - title: 'OpenAPI Endpoint Exceptions API Schemas', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'zod_operation_schema', - }); - - await generate({ - title: 'Endpoint Exceptions API client for tests', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'api_client_supertest', - skipLinting: true, - bundle: { - outFile: join( - REPO_ROOT, - 'x-pack/test/api_integration/services/security_solution_endpoint_exceptions_api.gen.ts' - ), - }, - }); -})(); diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json b/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json deleted file mode 100644 index 7e3c3fd7396d..000000000000 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "exclude": ["target/**/*"], - "extends": "../../tsconfig.base.json", - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/securitysolution-exceptions-common", - "@kbn/openapi-common", - "@kbn/zod", - ] -} diff --git a/packages/kbn-securitysolution-es-utils/jest.config.js b/packages/kbn-securitysolution-es-utils/jest.config.js deleted file mode 100644 index 5d52b2d390b5..000000000000 --- a/packages/kbn-securitysolution-es-utils/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-es-utils'], -}; diff --git a/packages/kbn-securitysolution-es-utils/tsconfig.json b/packages/kbn-securitysolution-es-utils/tsconfig.json deleted file mode 100644 index e584d504cc9c..000000000000 --- a/packages/kbn-securitysolution-es-utils/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "target/**/*", - ], - "kbn_references": [ - "@kbn/zod-helpers", - "@kbn/zod", - ] -} diff --git a/packages/kbn-securitysolution-exception-list-components/index.ts b/packages/kbn-securitysolution-exception-list-components/index.ts deleted file mode 100644 index 0e11a4694384..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/search_bar'; -export * from './src/empty_viewer_state'; -export * from './src/pagination/pagination'; -// export * from './src/exceptions_utility/exceptions_utility'; -export * from './src/exception_items'; -export * from './src/exception_item_card'; -export * from './src/value_with_space_warning'; -export * from './src/types'; -export * from './src/list_header'; -export * from './src/header_menu'; -export * from './src/generate_linked_rules_menu_item'; -export * from './src/wildcard_with_wrong_operator_callout'; -export * from './src/partial_code_signature_callout'; diff --git a/packages/kbn-securitysolution-exception-list-components/jest.config.js b/packages/kbn-securitysolution-exception-list-components/jest.config.js deleted file mode 100644 index e9d4ad8ad848..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/jest.config.js +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-exception-list-components'], - coverageReporters: ['text', 'html'], - collectCoverageFrom: [ - '/packages/kbn-securitysolution-exception-list-components/**/*.{ts,tsx}', - '!/packages/kbn-securitysolution-exception-list-components/**/*.test', - '!/packages/kbn-securitysolution-exception-list-components/**/types/*', - '!/packages/kbn-securitysolution-exception-list-components/**/*.type', - '!/packages/kbn-securitysolution-exception-list-components/**/*.styles', - '!/packages/kbn-securitysolution-exception-list-components/**/mocks/*', - '!/packages/kbn-securitysolution-exception-list-components/**/*.config', - '!/packages/kbn-securitysolution-exception-list-components/**/translations', - '!/packages/kbn-securitysolution-exception-list-components/**/types/*', - ], - setupFilesAfterEnv: [ - '/packages/kbn-securitysolution-exception-list-components/setup_test.ts', - ], -}; diff --git a/packages/kbn-securitysolution-exception-list-components/package.json b/packages/kbn-securitysolution-exception-list-components/package.json deleted file mode 100644 index 0b99a01c071e..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@kbn/securitysolution-exception-list-components", - "private": true, - "version": "1.0.0", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-exception-list-components/setup_test.ts b/packages/kbn-securitysolution-exception-list-components/setup_test.ts deleted file mode 100644 index 5ebc6d3dac1c..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/setup_test.ts +++ /dev/null @@ -1,11 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -// eslint-disable-next-line import/no-extraneous-dependencies -import '@testing-library/jest-dom'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts b/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts deleted file mode 100644 index aa99593b9e87..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -declare module '*.svg' { - const content: string; - // eslint-disable-next-line import/no-default-export - export default content; -} diff --git a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx deleted file mode 100644 index e9996e814c34..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useMemo } from 'react'; -import type { FC } from 'react'; -import { css } from '@emotion/react'; -import { - EuiSkeletonText, - EuiImage, - EuiEmptyPrompt, - EuiButton, - useEuiTheme, - EuiPanel, -} from '@elastic/eui'; -import type { ExpressionColor } from '@elastic/eui/src/components/expression/expression'; -import type { EuiFacetGroupLayout } from '@elastic/eui/src/components/facet/facet_group'; -import { euiThemeVars } from '@kbn/ui-theme'; -import { ListTypeText, ViewerStatus } from '../types'; -import * as i18n from '../translations'; -import illustration from '../assets/images/illustration_product_no_results_magnifying_glass.svg'; - -interface EmptyViewerStateProps { - title?: string; - body?: string; - buttonText?: string; - listType?: ListTypeText; - isReadOnly: boolean; - viewerStatus: ViewerStatus; - onEmptyButtonStateClick?: () => void | null; -} - -const panelCss = css` - margin: ${euiThemeVars.euiSizeL} 0; - padding: ${euiThemeVars.euiSizeL} 0; -`; -const EmptyViewerStateComponent: FC = ({ - title, - body, - buttonText, - listType, - isReadOnly, - viewerStatus, - onEmptyButtonStateClick, -}) => { - const { euiTheme } = useEuiTheme(); - - const euiEmptyPromptProps = useMemo(() => { - switch (viewerStatus) { - case ViewerStatus.ERROR: { - return { - color: 'danger' as ExpressionColor, - iconType: 'error', - title: ( -

{title || i18n.EMPTY_VIEWER_STATE_ERROR_TITLE}

- ), - body:

{body || i18n.EMPTY_VIEWER_STATE_ERROR_BODY}

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

{title || i18n.EMPTY_VIEWER_STATE_EMPTY_TITLE}

- ), - body:

{body || i18n.EMPTY_VIEWER_STATE_EMPTY_BODY}

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

- {title || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE} -

- ), - body: ( -

- {body || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY} -

- ), - 'data-test-subj': 'emptySearchViewerState', - }; - } - }, [ - viewerStatus, - euiTheme.colors.darkestShade, - title, - body, - onEmptyButtonStateClick, - isReadOnly, - buttonText, - listType, - ]); - - return ( - - - - - - ); -}; - -export const EmptyViewerState = React.memo(EmptyViewerStateComponent); - -EmptyViewerState.displayName = 'EmptyViewerState'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx deleted file mode 100644 index d2e5ac0577af..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo } from 'react'; -import type { EuiCommentProps } from '@elastic/eui'; -import { EuiAccordion, EuiCommentList, EuiFlexItem, EuiPanel, EuiText } from '@elastic/eui'; -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; -import * as i18n from '../translations'; - -const accordionCss = css` - color: ${euiThemeVars.euiColorPrimary}; -`; - -export interface ExceptionItemCardCommentsProps { - comments: EuiCommentProps[]; - dataTestSubj?: string; -} - -export const ExceptionItemCardComments = memo( - ({ comments, dataTestSubj }) => { - if (!comments.length) return null; - return ( - - - {i18n.exceptionItemCardCommentsAccordion(comments.length)} - - } - arrowDisplay="none" - data-test-subj="exceptionItemCardComments" - > - - - - - - ); - } -); - -ExceptionItemCardComments.displayName = 'ExceptionItemCardComments'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx deleted file mode 100644 index 8a089df54f2f..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { cx } from '@emotion/css'; -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; - -// TODO check font Roboto Mono -export const nestedGroupSpaceCss = css` - margin-left: ${euiThemeVars.euiSizeXL}; - margin-bottom: ${euiThemeVars.euiSizeXS}; - padding-top: ${euiThemeVars.euiSizeXS}; -`; - -export const borderCss = cx( - 'eui-xScroll', - ` - border: 1px; - border-color: #d3dae6; - border-style: solid; -` -); - -export const valueContainerCss = css` - display: flex; - align-items: center; - margin-left: ${euiThemeVars.euiSizeS}; -`; -export const expressionContainerCss = css` - display: flex; - align-items: center; -`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx deleted file mode 100644 index b765439116ce..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx +++ /dev/null @@ -1,83 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { ElementType, FC, memo } from 'react'; -import { EuiExpression, EuiToken, EuiFlexGroup } from '@elastic/eui'; -import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; -import { - nestedGroupSpaceCss, - valueContainerCss, - expressionContainerCss, -} from '../conditions.styles'; -import type { Entry } from '../types'; -import * as i18n from '../../translations'; -import { getValue, getValueExpression } from './entry_content.helper'; - -interface EntryContentProps { - entry: Entry; - index: number; - isNestedEntry?: boolean; - dataTestSubj?: string; - showValueListModal: ElementType; -} - -export const EntryContent: FC = memo( - ({ entry, index, isNestedEntry = false, dataTestSubj, showValueListModal }) => { - const { field, type } = entry; - const value = getValue(entry); - const operator = 'operator' in entry ? entry.operator : ''; - - const entryKey = `${field}${type}${value}${index}`; - return ( -
-
- {isNestedEntry ? ( - - - -
- - {getValueExpression( - type as ListOperatorTypeEnum, - operator, - value, - showValueListModal - )} -
-
- ) : ( - <> - - - {getValueExpression( - type as ListOperatorTypeEnum, - operator, - value, - showValueListModal - )} - - )} -
-
- ); - } -); -EntryContent.displayName = 'EntryContent'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx deleted file mode 100644 index f472402adddc..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx +++ /dev/null @@ -1,59 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo } from 'react'; -import { EuiPanel } from '@elastic/eui'; - -import { borderCss } from './conditions.styles'; -import { EntryContent } from './entry_content'; -import { OsCondition } from './os_conditions'; -import type { CriteriaConditionsProps, Entry } from './types'; - -export const ExceptionItemCardConditions = memo( - ({ os, entries, dataTestSubj, showValueListModal }) => { - return ( - - {os?.length ? : null} - {entries.map((entry: Entry, index: number) => { - const nestedEntries = 'entries' in entry ? entry.entries : []; - return ( -
- - {nestedEntries?.length - ? nestedEntries.map((nestedEntry: Entry, nestedIndex: number) => ( - - )) - : null} -
- ); - })} -
- ); - } -); -ExceptionItemCardConditions.displayName = 'ExceptionItemCardConditions'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx deleted file mode 100644 index 0d8285924c31..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx +++ /dev/null @@ -1,39 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo, useMemo } from 'react'; -import { EuiExpression } from '@elastic/eui'; - -import { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { OS_LABELS } from '../conditions.config'; -import * as i18n from '../../translations'; - -export interface OsConditionsProps { - dataTestSubj?: string; - os: ExceptionListItemSchema['os_types']; -} - -export const OsCondition = memo(({ os, dataTestSubj }) => { - const osLabel = useMemo(() => { - return os.map((osValue) => OS_LABELS[osValue] ?? osValue).join(', '); - }, [os]); - return osLabel ? ( -
- - - - -
- ) : null; -}); -OsCondition.displayName = 'OsCondition'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts deleted file mode 100644 index 0400ca6548d9..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { - EntryExists, - EntryList, - EntryMatch, - EntryMatchAny, - EntryMatchWildcard, - EntryNested, - ExceptionListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { ElementType } from 'react'; - -export type Entry = - | EntryExists - | EntryList - | EntryMatch - | EntryMatchAny - | EntryMatchWildcard - | EntryNested; - -export type Entries = ExceptionListItemSchema['entries']; -export interface CriteriaConditionsProps { - entries: Entries; - dataTestSubj: string; - os?: ExceptionListItemSchema['os_types']; - showValueListModal: ElementType; -} diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx deleted file mode 100644 index 72b02cc79a79..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo } from 'react'; -import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; -import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { HeaderMenu } from '../../header_menu'; - -export interface ExceptionItemCardHeaderProps { - item: ExceptionListItemSchema; - actions: Array<{ key: string; icon: string; label: string | boolean; onClick: () => void }>; - disableActions?: boolean; - dataTestSubj: string; -} - -export const ExceptionItemCardHeader = memo( - ({ item, actions, disableActions = false, dataTestSubj }) => { - return ( - - - -

{item.name}

-
-
- - - -
- ); - } -); - -ExceptionItemCardHeader.displayName = 'ExceptionItemCardHeader'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts deleted file mode 100644 index 26af37709233..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './conditions'; -export * from './header'; -export * from './meta'; -export * from './comments'; -export * from './exception_item_card'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx deleted file mode 100644 index cbb48e172322..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx +++ /dev/null @@ -1,39 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { render } from '@testing-library/react'; -import { MetaInfoDetails } from '.'; - -describe('MetaInfoDetails', () => { - it('should render lastUpdate as string', () => { - const wrapper = render( - - ); - expect(wrapper.container).toMatchSnapshot(); - expect(wrapper.getByTestId('MetaInfoDetailslastUpdate')).toHaveTextContent('last update'); - }); - it('should render lastUpdate as JSX Element', () => { - const wrapper = render( - Last update value

} - lastUpdateValue="value" - /> - ); - expect(wrapper.container).toMatchSnapshot(); - expect(wrapper.getByTestId('MetaInfoDetailslastUpdate')).toHaveTextContent('Last update value'); - }); -}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx deleted file mode 100644 index cc9eaa813aa9..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo } from 'react'; -import { EuiBadge, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; -import * as i18n from '../../translations'; - -interface MetaInfoDetailsProps { - label: string; - lastUpdate: JSX.Element | string; - lastUpdateValue?: string; - dataTestSubj?: string; -} - -const euiBadgeFontFamily = css` - font-family: ${euiThemeVars.euiFontFamily}; -`; -export const MetaInfoDetails = memo( - ({ label, lastUpdate, lastUpdateValue, dataTestSubj }) => { - return ( - - - - {label} - - - - - {lastUpdate} - - - {lastUpdateValue != null && ( - <> - - - {i18n.EXCEPTION_ITEM_CARD_META_BY} - - - - - - - {lastUpdateValue} - - - - - - )} - - ); - } -); - -MetaInfoDetails.displayName = 'MetaInfoDetails'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx deleted file mode 100644 index d9c0f84b02d0..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { memo, useMemo } from 'react'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; -import * as i18n from '../translations'; -import type { Rule } from '../../types'; -import { MetaInfoDetails } from './details_info'; -import { HeaderMenu } from '../../header_menu'; -import { generateLinkedRulesMenuItems } from '../../generate_linked_rules_menu_item'; - -const itemCss = css` - border-right: 1px solid #d3dae6; - padding: ${euiThemeVars.euiSizeS} ${euiThemeVars.euiSizeM} ${euiThemeVars.euiSizeS} 0; -`; - -export interface ExceptionItemCardMetaInfoProps { - item: ExceptionListItemSchema; - rules: Rule[]; - dataTestSubj: string; - formattedDateComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common -} - -export const ExceptionItemCardMetaInfo = memo( - ({ item, rules, dataTestSubj, securityLinkAnchorComponent, formattedDateComponent }) => { - const FormattedDateComponent = formattedDateComponent; - - const referencedLinks = useMemo( - () => - generateLinkedRulesMenuItems({ - dataTestSubj, - linkedRules: rules, - securityLinkAnchorComponent, - }), - [dataTestSubj, rules, securityLinkAnchorComponent] - ); - - const isExpired = useMemo( - () => (item.expire_time ? new Date(item.expire_time) <= new Date() : false), - [item] - ); - - return ( - - {FormattedDateComponent !== null && ( - <> - - - } - lastUpdateValue={item.created_by} - dataTestSubj={`${dataTestSubj || ''}CreatedBy`} - /> - - - - - } - lastUpdateValue={item.updated_by} - dataTestSubj={`${dataTestSubj || ''}UpdatedBy`} - /> - - {item.expire_time != null && ( - <> - - - } - dataTestSubj={`${dataTestSubj || ''}ExpireTime`} - /> - - - )} - - )} - - - - - ); - } -); -ExceptionItemCardMetaInfo.displayName = 'ExceptionItemCardMetaInfo'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts b/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts deleted file mode 100644 index 78a0dac775cf..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts +++ /dev/null @@ -1,181 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { i18n } from '@kbn/i18n'; - -export const exceptionItemCardEditButton = (listType: string) => - i18n.translate('exceptionList-components.exceptions.exceptionItem.card.editItemButton', { - values: { listType }, - defaultMessage: 'Edit {listType} exception', - }); - -export const exceptionItemCardDeleteButton = (listType: string) => - i18n.translate('exceptionList-components.exceptions.exceptionItem.card.deleteItemButton', { - values: { listType }, - defaultMessage: 'Delete {listType} exception', - }); - -export const EXCEPTION_ITEM_CARD_CREATED_LABEL = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.createdLabel', - { - defaultMessage: 'Created', - } -); - -export const EXCEPTION_ITEM_CARD_UPDATED_LABEL = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.updatedLabel', - { - defaultMessage: 'Updated', - } -); - -export const EXCEPTION_ITEM_CARD_EXPIRES_LABEL = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.expiresLabel', - { - defaultMessage: 'Expires at', - } -); - -export const EXCEPTION_ITEM_CARD_EXPIRED_LABEL = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.expiredLabel', - { - defaultMessage: 'Expired at', - } -); - -export const EXCEPTION_ITEM_CARD_META_BY = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.metaDetailsBy', - { - defaultMessage: 'by', - } -); - -export const exceptionItemCardCommentsAccordion = (comments: number) => - i18n.translate('exceptionList-components.exceptions.exceptionItem.card.showCommentsLabel', { - values: { comments }, - defaultMessage: 'Show {comments, plural, =1 {comment} other {comments}} ({comments})', - }); - -export const CONDITION_OPERATOR_TYPE_MATCH = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator', - { - defaultMessage: 'IS', - } -); - -export const CONDITION_OPERATOR_TYPE_NOT_MATCH = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator.not', - { - defaultMessage: 'IS NOT', - } -); - -export const CONDITION_OPERATOR_TYPE_WILDCARD_MATCHES = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardMatchesOperator', - { - defaultMessage: 'MATCHES', - } -); - -export const CONDITION_OPERATOR_TYPE_WILDCARD_DOES_NOT_MATCH = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardDoesNotMatchOperator', - { - defaultMessage: 'DOES NOT MATCH', - } -); - -export const CONDITION_OPERATOR_TYPE_NESTED = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.nestedOperator', - { - defaultMessage: 'has', - } -); - -export const CONDITION_OPERATOR_TYPE_MATCH_ANY = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator', - { - defaultMessage: 'is one of', - } -); - -export const CONDITION_OPERATOR_TYPE_NOT_MATCH_ANY = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator.not', - { - defaultMessage: 'is not one of', - } -); - -export const CONDITION_OPERATOR_TYPE_EXISTS = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator', - { - defaultMessage: 'exists', - } -); - -export const CONDITION_OPERATOR_TYPE_DOES_NOT_EXIST = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator.not', - { - defaultMessage: 'does not exist', - } -); - -export const CONDITION_OPERATOR_TYPE_LIST = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator', - { - defaultMessage: 'included in', - } -); - -export const CONDITION_OPERATOR_TYPE_NOT_IN_LIST = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator.not', - { - defaultMessage: 'is not included in', - } -); - -export const CONDITION_AND = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.and', - { - defaultMessage: 'AND', - } -); - -export const CONDITION_OS = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.os', - { - defaultMessage: 'OS', - } -); - -export const OS_WINDOWS = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.windows', - { - defaultMessage: 'Windows', - } -); - -export const OS_LINUX = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.linux', - { - defaultMessage: 'Linux', - } -); - -export const OS_MAC = i18n.translate( - 'exceptionList-components.exceptions.exceptionItem.card.conditions.macos', - { - defaultMessage: 'Mac', - } -); - -export const AFFECTED_RULES = (numRules: number) => - i18n.translate('exceptionList-components.exceptions.card.exceptionItem.affectedRules', { - values: { numRules }, - defaultMessage: 'Affects {numRules} {numRules, plural, =1 {rule} other {rules}}', - }); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx deleted file mode 100644 index edad9aecdb0d..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx +++ /dev/null @@ -1,155 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { ElementType } from 'react'; -import { css } from '@emotion/react'; -import type { FC } from 'react'; -import { EuiCommentProps, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; - -import type { - CommentsArray, - ExceptionListItemSchema, - ExceptionListTypeEnum, -} from '@kbn/securitysolution-io-ts-list-types'; - -import { euiThemeVars } from '@kbn/ui-theme'; -import { EmptyViewerState, ExceptionItemCard, Pagination, PaginationProps } from '../..'; - -import type { - RuleReferences, - ExceptionListItemIdentifiers, - ViewerStatus, - GetExceptionItemProps, -} from '../types'; - -const exceptionItemCss = css` - margin: ${euiThemeVars.euiSize} 0; - &div:first-child { - margin: ${euiThemeVars.euiSizeXS} 0 ${euiThemeVars.euiSize}; - } -`; - -interface ExceptionItemsProps { - lastUpdated: string | number | null; - viewerStatus: ViewerStatus; - isReadOnly: boolean; - emptyViewerTitle?: string; - emptyViewerBody?: string; - emptyViewerButtonText?: string; - exceptions: ExceptionListItemSchema[]; - listType: ExceptionListTypeEnum; - ruleReferences: RuleReferences; - pagination: PaginationProps['pagination']; - editActionLabel?: string; - deleteActionLabel?: string; - dataTestSubj?: string; - securityLinkAnchorComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - formattedDateComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - exceptionsUtilityComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - getFormattedComments: (comments: CommentsArray) => EuiCommentProps[]; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - onCreateExceptionListItem?: () => void; - onDeleteException: (arg: ExceptionListItemIdentifiers) => void; - onEditExceptionItem: (item: ExceptionListItemSchema) => void; - onPaginationChange: (arg: GetExceptionItemProps) => void; - showValueListModal: ElementType; -} - -const ExceptionItemsComponent: FC = ({ - lastUpdated, - viewerStatus, - isReadOnly, - exceptions, - listType, - ruleReferences, - emptyViewerTitle, - emptyViewerBody, - emptyViewerButtonText, - pagination, - dataTestSubj, - editActionLabel, - deleteActionLabel, - securityLinkAnchorComponent, - exceptionsUtilityComponent, - formattedDateComponent, - getFormattedComments, - onPaginationChange, - onDeleteException, - onEditExceptionItem, - onCreateExceptionListItem, - showValueListModal, -}) => { - const ExceptionsUtility = exceptionsUtilityComponent; - if (!exceptions.length || viewerStatus) - return ( - - ); - const ShowValueListModal = showValueListModal; - return ( - <> - - - - - {exceptions.map((exception) => ( - - - - ))} - - - - - - ); -}; - -ExceptionItemsComponent.displayName = 'ExceptionItemsComponent'; - -export const ExceptionItems = React.memo(ExceptionItemsComponent); - -ExceptionItems.displayName = 'ExceptionsItems'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx deleted file mode 100644 index d68ac8f114a0..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { ElementType, ReactElement } from 'react'; -import { EuiContextMenuItem, EuiFlexGroup, EuiFlexItem, EuiIcon, IconType } from '@elastic/eui'; -import { Rule } from '../types'; -import { itemContentCss, containerCss } from './menu_link.styles'; - -interface MenuItemLinkedRulesProps { - leftIcon?: IconType; - dataTestSubj?: string; - linkedRules: Rule[]; - securityLinkAnchorComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common -} - -export const generateLinkedRulesMenuItems = ({ - dataTestSubj, - linkedRules, - securityLinkAnchorComponent, - leftIcon = '', -}: MenuItemLinkedRulesProps): ReactElement[] | null => { - if (!linkedRules.length || securityLinkAnchorComponent === null) return null; - - const SecurityLinkAnchor = securityLinkAnchorComponent; - return linkedRules.map((rule) => { - return ( - 1 ? containerCss : ''} - data-test-subj={`${dataTestSubj || ''}ActionItem${rule.id}`} - key={rule.id} - > - - {leftIcon ? ( - - - - ) : null} - - - - - - ); - }); -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.ts b/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.ts deleted file mode 100644 index 42f470ce39dd..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; - -export const containerCss = css` - border-bottom: 1px solid ${euiThemeVars.euiColorLightShade}; -`; - -export const itemContentCss = css` - color: ${euiThemeVars.euiColorPrimary}; - flex-basis: content; -`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx deleted file mode 100644 index 2f39959c33fe..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx +++ /dev/null @@ -1,139 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { FC, ReactElement, useMemo, useState } from 'react'; -import { - EuiButtonEmpty, - EuiButtonEmptyProps, - EuiButtonIcon, - EuiContextMenuItem, - EuiContextMenuPanel, - EuiFlexGroup, - EuiPopover, - PanelPaddingSize, - PopoverAnchorPosition, -} from '@elastic/eui'; - -import { css } from '@emotion/react'; - -export interface Action { - key: string; - icon: string; - label: string | boolean; - disabled?: boolean; - onClick: (e: React.MouseEvent) => void; -} - -interface HeaderMenuComponentProps { - disableActions: boolean; - actions: Action[] | ReactElement[] | null; - text?: string; - iconType?: EuiButtonEmptyProps['iconType']; - iconSide?: EuiButtonEmptyProps['iconSide']; - dataTestSubj?: string; - emptyButton?: boolean; - useCustomActions?: boolean; - anchorPosition?: PopoverAnchorPosition; - panelPaddingSize?: PanelPaddingSize; -} - -const popoverHeightStyle = css` - max-height: 300px; - height: 100%; - overflow-x: hidden; - overflow-y: auto; -`; -const HeaderMenuComponent: FC = ({ - text, - dataTestSubj, - actions, - disableActions, - emptyButton, - useCustomActions, - iconType, - iconSide = 'left', - anchorPosition = 'downCenter', - panelPaddingSize = 's', -}) => { - const [isPopoverOpen, setIsPopoverOpen] = useState(false); - - const onAffectedRulesClick = () => setIsPopoverOpen((isOpen) => !isOpen); - const onClosePopover = () => setIsPopoverOpen(false); - - const itemActions = useMemo(() => { - if (useCustomActions || actions === null) return actions; - return (actions as Action[]).map((action) => ( - { - onClosePopover(); - if (typeof action.onClick === 'function') action.onClick(e); - }} - > - {action.label} - - )); - }, [actions, dataTestSubj, useCustomActions]); - - return ( - - - {text} - - ) : ( - - {text} - - ) - } - onClick={(e) => e.stopPropagation()} - panelPaddingSize={panelPaddingSize} - isOpen={isPopoverOpen} - closePopover={onClosePopover} - anchorPosition={anchorPosition} - data-test-subj={`${dataTestSubj || ''}Items`} - > - {!itemActions ? null : ( - - )} - - - ); -}; -HeaderMenuComponent.displayName = 'HeaderMenuComponent'; - -export const HeaderMenu = React.memo(HeaderMenuComponent); - -HeaderMenu.displayName = 'HeaderMenu'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx deleted file mode 100644 index 82aec99bebb3..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { FC } from 'react'; -import { - EuiButton, - EuiButtonEmpty, - EuiFieldText, - EuiForm, - EuiFormRow, - EuiModal, - EuiModalBody, - EuiModalFooter, - EuiModalHeader, - EuiModalHeaderTitle, - EuiTextArea, - EuiProgress, -} from '@elastic/eui'; -import * as i18n from '../../translations'; -import { ListDetails } from '../../types'; -import { useEditModal } from './use_edit_modal'; - -interface EditModalProps { - listDetails: ListDetails; - onSave: (newListDetails: ListDetails) => void; - onCancel: () => void; -} - -const EditModalComponent: FC = ({ listDetails, onSave, onCancel }) => { - const { error, modalFormId, newListDetails, showProgress, onBlur, onSubmit, onChange } = - useEditModal({ - listDetails, - onSave, - }); - return ( - - {showProgress && ( - - )} - - - {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_TITLE(listDetails.name)} - - - - - - - - - - - - - - - - - - {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_CANCEL_BUTTON} - - - - {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_SAVE_BUTTON} - - - - ); -}; -EditModalComponent.displayName = 'EditModalComponent'; - -export const EditModal = React.memo(EditModalComponent); - -EditModal.displayName = 'EditModal'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx deleted file mode 100644 index 849dd4ef1ba8..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx +++ /dev/null @@ -1,138 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import type { FC } from 'react'; -import { EuiIcon, EuiPageHeader, EuiText } from '@elastic/eui'; -import * as i18n from '../translations'; -import { textCss, descriptionContainerCss, backTextCss } from './list_header.styles'; -import { MenuItems } from './menu_items'; -import { TextWithEdit } from '../text_with_edit'; -import { EditModal } from './edit_modal'; -import { ListDetails, Rule } from '../types'; -import { useExceptionListHeader } from './use_list_header'; -import { textWithEditContainerCss } from '../text_with_edit/text_with_edit.styles'; - -interface ExceptionListHeaderComponentProps { - name: string; - description?: string; - listId: string; - isReadonly: boolean; - linkedRules: Rule[]; - dataTestSubj?: string; - backOptions: BackOptions; - canUserEditList?: boolean; - securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - onEditListDetails: (listDetails: ListDetails) => void; - onDeleteList: () => void; - onManageRules: () => void; - onExportList: () => void; - onDuplicateList: () => void; -} - -export interface BackOptions { - pageId: string; - path: string; - dataTestSubj?: string; - onNavigate: (path: string) => void; -} -const ExceptionListHeaderComponent: FC = ({ - name, - description, - listId, - linkedRules, - isReadonly, - dataTestSubj, - securityLinkAnchorComponent, - backOptions, - canUserEditList = true, - onEditListDetails, - onDeleteList, - onManageRules, - onExportList, - onDuplicateList, -}) => { - const { isModalVisible, listDetails, onEdit, onSave, onCancel } = useExceptionListHeader({ - name, - description, - onEditListDetails, - }); - return ( -
- - } - responsive - data-test-subj={`${dataTestSubj || ''}PageHeader`} - description={ -
- -
- {i18n.EXCEPTION_LIST_HEADER_LIST_ID}: - {listId} -
-
- } - rightSideItems={[ - , - ]} - breadcrumbs={[ - { - text: ( -
- - {i18n.EXCEPTION_LIST_HEADER_BREADCRUMB} -
- ), - color: 'primary', - 'aria-current': false, - href: backOptions.path, - onClick: (e) => { - e.preventDefault(); - backOptions.onNavigate(backOptions.path); - }, - }, - ]} - /> - {isModalVisible && ( - - )} -
- ); -}; - -ExceptionListHeaderComponent.displayName = 'ExceptionListHeaderComponent'; - -export const ExceptionListHeader = React.memo(ExceptionListHeaderComponent); - -ExceptionListHeader.displayName = 'ExceptionListHeader'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.ts b/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.ts deleted file mode 100644 index c3cba9f9dcdb..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; - -export const headerMenuCss = css` - border-right: 1px solid #d3dae6; - padding: ${euiThemeVars.euiSizeXS} ${euiThemeVars.euiSizeL} ${euiThemeVars.euiSizeXS} 0; -`; - -export const noLinkedRulesCss = css` - width: max-content; -`; - -export const textCss = css` - font-size: ${euiThemeVars.euiFontSize}; - color: ${euiThemeVars.euiTextSubduedColor}; - margin-left: ${euiThemeVars.euiSizeXS}; -`; -export const descriptionContainerCss = css` - margin-top: -${euiThemeVars.euiSizeL}; - margin-bottom: -${euiThemeVars.euiSizeL}; -`; - -export const backTextCss = css` - font-size: ${euiThemeVars.euiFontSizeXS}; -`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx deleted file mode 100644 index f0aecf21b6c7..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx +++ /dev/null @@ -1,136 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiTextColor } from '@elastic/eui'; -import React, { FC, useMemo } from 'react'; -import { HeaderMenu } from '../../header_menu'; -import { headerMenuCss, noLinkedRulesCss } from '../list_header.styles'; -import * as i18n from '../../translations'; -import { Rule } from '../../types'; -import { generateLinkedRulesMenuItems } from '../../generate_linked_rules_menu_item'; -interface MenuItemsProps { - isReadonly: boolean; - dataTestSubj?: string; - linkedRules: Rule[]; - canUserEditList?: boolean; - securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common - onDeleteList: () => void; - onManageRules: () => void; - onExportList: () => void; - onDuplicateList: () => void; -} - -const MenuItemsComponent: FC = ({ - dataTestSubj, - linkedRules, - securityLinkAnchorComponent, - isReadonly, - canUserEditList = true, - onDeleteList, - onManageRules, - onExportList, - onDuplicateList, -}) => { - const referencedLinks = useMemo( - () => - generateLinkedRulesMenuItems({ - leftIcon: 'check', - dataTestSubj, - linkedRules, - securityLinkAnchorComponent, - }), - [dataTestSubj, linkedRules, securityLinkAnchorComponent] - ); - return ( - - - {linkedRules.length ? ( - - ) : ( - - {i18n.EXCEPTION_LIST_HEADER_LINKED_RULES(linkedRules.length)} - - )} - - - {canUserEditList && ( - - { - if (typeof onManageRules === 'function') onManageRules(); - }} - > - {i18n.EXCEPTION_LIST_HEADER_LINK_RULES_BUTTON} - - - )} - - { - if (typeof onExportList === 'function') onExportList(); - }, - }, - { - key: '2', - icon: 'copy', - label: i18n.EXCEPTION_LIST_HEADER_DUPLICATE_ACTION, - onClick: () => { - if (typeof onDuplicateList === 'function') onDuplicateList(); - }, - disabled: !canUserEditList, - }, - { - key: '3', - icon: 'trash', - label: i18n.EXCEPTION_LIST_HEADER_DELETE_ACTION, - onClick: () => { - if (typeof onDeleteList === 'function') onDeleteList(); - }, - disabled: !canUserEditList, - }, - ]} - disableActions={isReadonly} - anchorPosition="downCenter" - /> - - - ); -}; - -MenuItemsComponent.displayName = 'MenuItemsComponent'; - -export const MenuItems = React.memo(MenuItemsComponent); - -MenuItems.displayName = 'MenuItems'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts b/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts deleted file mode 100644 index 676dd08a53be..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useState } from 'react'; -import { ListDetails } from '../types'; - -interface UseExceptionListHeaderProps { - name: string; - description?: string; - onEditListDetails: (listDetails: ListDetails) => void; -} -export const useExceptionListHeader = ({ - name, - description, - onEditListDetails, -}: UseExceptionListHeaderProps) => { - const [isModalVisible, setIsModalVisible] = useState(false); - const [listDetails, setListDetails] = useState({ name, description }); - const onEdit = () => { - setIsModalVisible(true); - }; - const onSave = (newListDetails: ListDetails) => { - setListDetails(newListDetails); - if (typeof onEditListDetails === 'function') onEditListDetails(newListDetails); - setTimeout(() => { - setIsModalVisible(false); - }, 200); - }; - const onCancel = () => { - setIsModalVisible(false); - }; - - return { - isModalVisible, - listDetails, - onEdit, - onSave, - onCancel, - }; -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx b/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx deleted file mode 100644 index 4c9b813463ca..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import type { Comment, CommentsArray } from '@kbn/securitysolution-io-ts-list-types'; - -export const getCommentsMock = (): Comment => ({ - comment: 'some old comment', - created_at: '2020-04-20T15:25:31.830Z', - created_by: 'some user', - id: 'uuid_here', -}); - -export const getCommentsArrayMock = (): CommentsArray => [getCommentsMock(), getCommentsMock()]; - -export const mockGetFormattedComments = () => - getCommentsArrayMock().map((comment) => ({ - username: comment.created_by, - children:

{comment.comment}

, - })); diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.ts b/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.ts deleted file mode 100644 index a39fe947caa2..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Entry } from '../exception_item_card/conditions/types'; - -export const includedListTypeEntry: Entry = { - field: '', - operator: 'included', - type: 'list', - list: { id: 'list_id', type: 'boolean' }, -}; - -export const includedMatchTypeEntry: Entry = { - field: '', - operator: 'included', - type: 'match', - value: 'matches value', -}; - -export const includedExistsTypeEntry: Entry = { - field: '', - operator: 'included', - type: 'exists', -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts b/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts deleted file mode 100644 index f9c24d46228c..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -export const getExceptionListItemSchemaMock = ( - overrides?: Partial -): ExceptionListItemSchema => ({ - _version: undefined, - comments: [], - created_at: '2020-04-20T15:25:31.830Z', - created_by: 'some user', - description: 'some description', - entries: [ - { - entries: [ - { field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }, - ], - field: 'some.parentField', - type: 'nested', - }, - { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, - ], - expire_time: undefined, - id: '1', - item_id: 'endpoint_list_item', - list_id: 'endpoint_list_id', - meta: {}, - name: 'some name', - namespace_type: 'single', - os_types: [], - tags: ['user added string for a tag', 'malware'], - tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', - type: 'simple', - updated_at: '2020-04-20T15:25:31.830Z', - updated_by: 'some user', - ...(overrides || {}), -}); diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.ts b/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.ts deleted file mode 100644 index 06aa00b5ff72..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const handleEdit = jest.fn(); -export const handleDelete = jest.fn(); -export const actions = [ - { - key: 'edit', - icon: 'pencil', - label: 'Edit detection exception', - onClick: handleEdit, - }, - { - key: 'delete', - icon: 'trash', - label: 'Delete detection exception', - onClick: handleDelete, - }, -]; -export const actionsWithDisabledDelete = [ - { - key: 'edit', - icon: 'pencil', - label: 'Edit detection exception', - onClick: handleEdit, - }, - { - key: 'delete', - icon: 'trash', - disabled: true, - label: 'Delete detection exception', - onClick: handleDelete, - }, -]; diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.ts b/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.ts deleted file mode 100644 index 3592d5f03cc4..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Rule, RuleReference } from '../types'; - -export const rules: Rule[] = [ - { - exceptions_list: [ - { - id: '123', - list_id: 'i_exist', - namespace_type: 'single', - type: 'detection', - }, - { - id: '456', - list_id: 'i_exist_2', - namespace_type: 'single', - type: 'detection', - }, - ], - id: '1a2b3c', - name: 'Simple Rule Query', - rule_id: 'rule-2', - }, -]; - -export const ruleReference: RuleReference = { - name: 'endpoint list', - id: 'endpoint_list', - referenced_rules: rules, - listId: 'endpoint_list_id', -}; - -export const ruleReferences = { - endpoint_list_id: ruleReference, -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx b/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx deleted file mode 100644 index 1ad7d2921c5a..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { ReactElement } from 'react'; -import { generateLinkedRulesMenuItems } from '../generate_linked_rules_menu_item'; -import { rules } from './rule_references.mock'; -export const securityLinkAnchorComponentMock = ({ - referenceName, - referenceId, -}: { - referenceName: string; - referenceId: string; -}) => ( - -); - -export const getSecurityLinkAction = (dataTestSubj: string) => - generateLinkedRulesMenuItems({ - dataTestSubj, - linkedRules: [ - ...rules, - { - exceptions_list: [], - id: '2a2b3c', - name: 'Simple Rule Query 2', - rule_id: 'rule-2', - }, - ], - securityLinkAnchorComponent: securityLinkAnchorComponentMock, - }) as ReactElement[]; diff --git a/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx b/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx deleted file mode 100644 index 930439b577ff..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; - -export const mockShowValueListModal = jest.fn(); -export const MockedShowValueListModal = (props: { children: React.ReactNode }) => { - mockShowValueListModal(props); - return <>{props.children}; -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx b/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx deleted file mode 100644 index 38be3b8474ad..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import type { FC } from 'react'; -import { EuiTablePagination } from '@elastic/eui'; - -import type { PaginationProps } from '../types'; -import { usePagination } from './use_pagination'; - -const PaginationComponent: FC = ({ - dataTestSubj, - ariaLabel, - pagination, - onPaginationChange, -}) => { - const { - pageIndex, - pageCount, - pageSize, - pageSizeOptions, - - handleItemsPerPageChange, - handlePageIndexChange, - } = usePagination({ pagination, onPaginationChange }); - - return ( - - ); -}; - -PaginationComponent.displayName = 'PaginationComponent'; - -export const Pagination = React.memo(PaginationComponent); - -Pagination.displayName = 'Pagination'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx deleted file mode 100644 index 72836fc78fb5..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx +++ /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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { FormattedMessage } from '@kbn/i18n-react'; -import { i18n } from '@kbn/i18n'; - -import { EuiCallOut } from '@elastic/eui'; - -export const PartialCodeSignatureCallout = () => { - return ( - - - - ); -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx deleted file mode 100644 index 0670a2553a69..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx +++ /dev/null @@ -1,124 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { useCallback } from 'react'; -import type { FC } from 'react'; - -import type { EuiSearchBarProps, IconType, SearchFilterConfig } from '@elastic/eui'; -import { EuiFlexGroup, EuiFlexItem, EuiButton, EuiSearchBar } from '@elastic/eui'; -import type { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; -import type { GetExceptionItemProps } from '../types'; - -const ITEMS_SCHEMA = { - strict: true, - fields: { - created_by: { - type: 'string', - }, - description: { - type: 'string', - }, - id: { - type: 'string', - }, - item_id: { - type: 'string', - }, - list_id: { - type: 'string', - }, - name: { - type: 'string', - }, - os_types: { - type: 'string', - }, - tags: { - type: 'string', - }, - }, -}; -interface SearchBarProps { - addExceptionButtonText?: string; - placeholdertext?: string; - canAddException?: boolean; // TODO what is the default value - - // TODO: REFACTOR: not to send the listType and handle it in the Parent - // Exception list type used to determine what type of item is - // being created when "onAddExceptionClick" is invoked - listType: ExceptionListTypeEnum; - isSearching?: boolean; - dataTestSubj?: string; - filters?: SearchFilterConfig[]; // TODO about filters - isButtonFilled?: boolean; - buttonIconType?: IconType; - onSearch: (arg: GetExceptionItemProps) => void; - onAddExceptionClick: (type: ExceptionListTypeEnum) => void; -} -const SearchBarComponent: FC = ({ - addExceptionButtonText, - placeholdertext, - canAddException, - listType, - isSearching, - dataTestSubj, - filters = [], - isButtonFilled = true, - buttonIconType, - onSearch, - onAddExceptionClick, -}) => { - const handleOnSearch = useCallback>( - ({ queryText }): void => { - onSearch({ search: queryText }); - }, - [onSearch] - ); - - const handleAddException = useCallback(() => { - // TODO: ASK YARA why we need to send the listType - onAddExceptionClick(listType); - }, [onAddExceptionClick, listType]); - - return ( - - - - - {!canAddException && ( - - - {addExceptionButtonText} - - - )} - - ); -}; - -SearchBarComponent.displayName = 'SearchBarComponent'; - -export const SearchBar = React.memo(SearchBarComponent); - -SearchBar.displayName = 'SearchBar'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx deleted file mode 100644 index aa5625cfe671..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React, { FC } from 'react'; -import { EuiButtonIcon, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { Interpolation, Theme } from '@emotion/react'; -import { textWithEditContainerCss, editIconCss } from './text_with_edit.styles'; -interface TextWithEditProps { - isReadonly: boolean; - dataTestSubj?: string; - text: string; - textCss?: Interpolation; - onEdit?: () => void; -} - -const TextWithEditComponent: FC = ({ - isReadonly, - dataTestSubj, - text, - onEdit, - textCss, -}) => { - return ( - - - - {text} - - - - {isReadonly ? null : ( - (typeof onEdit === 'function' ? onEdit() : null)} - /> - )} - - - ); -}; -TextWithEditComponent.displayName = 'TextWithEditComponent'; - -export const TextWithEdit = React.memo(TextWithEditComponent); - -TextWithEdit.displayName = 'TextWithEdit'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.ts b/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.ts deleted file mode 100644 index e293ea073041..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; - -export const textWithEditContainerCss = css` - display: flex; - width: fit-content; - align-items: baseline; - padding-bottom: ${euiThemeVars.euiSizeS}; - h1 { - margin-bottom: 0; - } -`; -export const editIconCss = css` - button { - margin-left: -${euiThemeVars.euiSizeM}; - } -`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/translations.ts b/packages/kbn-securitysolution-exception-list-components/src/translations.ts deleted file mode 100644 index dff688d156da..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/translations.ts +++ /dev/null @@ -1,156 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { i18n } from '@kbn/i18n'; - -export const EMPTY_VIEWER_STATE_EMPTY_TITLE = i18n.translate( - 'exceptionList-components.empty.viewer.state.empty.title', - { - defaultMessage: 'Add exceptions to this list', - } -); - -export const EMPTY_VIEWER_STATE_EMPTY_BODY = i18n.translate( - 'exceptionList-components.empty.viewer.state.empty.body', - { - defaultMessage: 'There is no exception in your list. Create your first exception.', - } -); -export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE = i18n.translate( - 'exceptionList-components.empty.viewer.state.empty_search.search.title', - { - defaultMessage: 'No results match your search criteria', - } -); - -export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY = i18n.translate( - 'exceptionList-components.empty.viewer.state.empty_search.body', - { - defaultMessage: 'Try modifying your search', - } -); - -export const EMPTY_VIEWER_STATE_EMPTY_VIEWER_BUTTON = (exceptionType: string) => - i18n.translate('exceptionList-components.empty.viewer.state.empty.viewer_button', { - values: { exceptionType }, - defaultMessage: 'Create {exceptionType} exception', - }); - -export const EMPTY_VIEWER_STATE_ERROR_TITLE = i18n.translate( - 'exceptionList-components.empty.viewer.state.error_title', - { - defaultMessage: 'Unable to load exception items', - } -); - -export const EMPTY_VIEWER_STATE_ERROR_BODY = i18n.translate( - 'exceptionList-components.empty.viewer.state.error_body', - { - defaultMessage: - 'There was an error loading the exception items. Contact your administrator for help.', - } -); -export const EXCEPTION_LIST_HEADER_EXPORT_ACTION = i18n.translate( - 'exceptionList-components.exception_list_header_export_action', - { - defaultMessage: 'Export exception list', - } -); -export const EXCEPTION_LIST_HEADER_DELETE_ACTION = i18n.translate( - 'exceptionList-components.exception_list_header_delete_action', - { - defaultMessage: 'Delete exception list', - } -); -export const EXCEPTION_LIST_HEADER_DUPLICATE_ACTION = i18n.translate( - 'exceptionList-components.exception_list_header_duplicate_action', - { - defaultMessage: 'Duplicate exception list', - } -); -export const EXCEPTION_LIST_HEADER_LINK_RULES_BUTTON = i18n.translate( - 'exceptionList-components.exception_list_header_link_rules_button', - { - defaultMessage: 'Link rules', - } -); - -export const EXCEPTION_LIST_HEADER_LINKED_RULES = (noOfRules: number) => - i18n.translate('exceptionList-components.exception_list_header_linked_rules', { - values: { noOfRules }, - defaultMessage: 'Linked to {noOfRules} rules', - }); - -export const EXCEPTION_LIST_HEADER_BREADCRUMB = i18n.translate( - 'exceptionList-components.exception_list_header_breadcrumb', - { - defaultMessage: 'Shared Exception Lists', - } -); - -export const EXCEPTION_LIST_HEADER_LIST_ID = i18n.translate( - 'exceptionList-components.exception_list_header_list_id', - { - defaultMessage: 'List ID', - } -); - -export const EXCEPTION_LIST_HEADER_NAME = i18n.translate( - 'exceptionList-components.exception_list_header_name', - { - defaultMessage: 'Add a name', - } -); - -export const EXCEPTION_LIST_HEADER_DESCRIPTION = i18n.translate( - 'exceptionList-components.exception_list_header_description', - { - defaultMessage: 'Add a description', - } -); - -export const EXCEPTION_LIST_HEADER_EDIT_MODAL_TITLE = (listName: string) => - i18n.translate('exceptionList-components.exception_list_header_edit_modal_name', { - defaultMessage: 'Edit {listName}', - values: { listName }, - }); - -export const EXCEPTION_LIST_HEADER_EDIT_MODAL_SAVE_BUTTON = i18n.translate( - 'exceptionList-components.exception_list_header_edit_modal_save_button', - { - defaultMessage: 'Save', - } -); - -export const EXCEPTION_LIST_HEADER_EDIT_MODAL_CANCEL_BUTTON = i18n.translate( - 'exceptionList-components.exception_list_header_edit_modal_cancel_button', - { - defaultMessage: 'Cancel', - } -); -export const EXCEPTION_LIST_HEADER_NAME_TEXTBOX = i18n.translate( - 'exceptionList-components.exception_list_header_Name_textbox', - { - defaultMessage: 'Name', - } -); - -export const EXCEPTION_LIST_HEADER_DESCRIPTION_TEXTBOX = i18n.translate( - 'exceptionList-components.exception_list_header_description_textbox', - { - defaultMessage: 'Description (optional)', - } -); - -export const LIST_NAME_REQUIRED_ERROR = i18n.translate( - 'exceptionList-components.exception_list_header_description_textboxexceptionList-components.exception_list_header_name_required_eror', - { - defaultMessage: 'List name cannot be empty', - } -); diff --git a/packages/kbn-securitysolution-exception-list-components/src/types/index.ts b/packages/kbn-securitysolution-exception-list-components/src/types/index.ts deleted file mode 100644 index 57a0ee3901ba..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/types/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ListArray } from '@kbn/securitysolution-io-ts-list-types'; - -import type { Pagination } from '@elastic/eui'; -import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; - -export interface GetExceptionItemProps { - pagination?: PaginationProps['pagination']; - search?: string; - filters?: string; -} - -export interface PaginationProps { - dataTestSubj?: string; - ariaLabel?: string; - pagination: Pagination & { pageSize: number }; - onPaginationChange: (arg: GetExceptionItemProps) => void; -} - -export enum ViewerStatus { - ERROR = 'error', - EMPTY = 'empty', - EMPTY_SEARCH = 'empty_search', - LOADING = 'loading', - SEARCHING = 'searching', - DELETING = 'deleting', -} - -export interface ExceptionListSummaryProps { - pagination: Pagination; - // Corresponds to last time exception items were fetched - lastUpdated: string | number | null; -} - -export type ViewerFlyoutName = 'addException' | 'editException' | null; - -export interface RuleReferences { - [key: string]: RuleReference; -} - -export interface ExceptionListItemIdentifiers { - id: string; - name: string; - namespaceType: NamespaceType; -} - -export enum ListTypeText { - ENDPOINT = 'endpoint', - DETECTION = 'empty', - RULE_DEFAULT = 'empty_search', -} -export interface Rule { - name: string; - id: string; - rule_id: string; - exceptions_list?: ListArray; -} - -export interface RuleReference { - name: string; - id: string; - referenced_rules: Rule[]; - listId?: string; -} - -export interface ListDetails { - name: string; - description?: string; -} diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts deleted file mode 100644 index 5a0843be833f..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export { ValueWithSpaceWarning } from './value_with_space_warning'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts b/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts deleted file mode 100644 index d5a6392815a7..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { paramContainsSpace, autoCompletei18n } from '@kbn/securitysolution-autocomplete'; - -interface UseValueWithSpaceWarningResult { - showSpaceWarningIcon: boolean; - warningText: string; -} -interface UseValueWithSpaceWarningProps { - value: string | string[]; - tooltipIconText?: string; -} - -export const useValueWithSpaceWarning = ({ - value, - tooltipIconText, -}: UseValueWithSpaceWarningProps): UseValueWithSpaceWarningResult => { - const showSpaceWarningIcon = Array.isArray(value) - ? value.find(paramContainsSpace) - : paramContainsSpace(value); - - return { - showSpaceWarningIcon: !!showSpaceWarningIcon, - warningText: tooltipIconText || autoCompletei18n.FIELD_SPACE_WARNING, - }; -}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx b/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx deleted file mode 100644 index d68782b4c17f..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import React from 'react'; -import { FormattedMessage } from '@kbn/i18n-react'; -import { i18n } from '@kbn/i18n'; - -import { EuiCallOut } from '@elastic/eui'; - -export const WildCardWithWrongOperatorCallout = () => { - return ( - -

- - {i18n.translate( - 'exceptionList-components.wildcardWithWrongOperatorCallout.changeTheOperator', - { defaultMessage: 'Change the operator' } - )} - - ), - matches: ( - - {i18n.translate( - 'exceptionList-components.wildcardWithWrongOperatorCallout.matches', - { defaultMessage: 'matches' } - )} - - ), - }} - /> -

-
- ); -}; diff --git a/packages/kbn-securitysolution-exception-list-components/tsconfig.json b/packages/kbn-securitysolution-exception-list-components/tsconfig.json deleted file mode 100644 index b3df3a2aa208..000000000000 --- a/packages/kbn-securitysolution-exception-list-components/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node", - "react", - "@emotion/react/types/css-prop" - ] - }, - "include": [ - "**/*.ts", - "**/*.tsx", - "**/*.d.ts" - ], - "kbn_references": [ - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-autocomplete", - "@kbn/ui-theme", - "@kbn/i18n", - "@kbn/i18n-react", - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts b/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts deleted file mode 100644 index aedd1f5fc5cc..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts +++ /dev/null @@ -1,39 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Create shared exception list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { - ExceptionListName, - ExceptionListDescription, - ExceptionList, -} from '../model/exception_list_common.gen'; - -export type CreateSharedExceptionListRequestBody = z.infer< - typeof CreateSharedExceptionListRequestBody ->; -export const CreateSharedExceptionListRequestBody = z.object({ - name: ExceptionListName, - description: ExceptionListDescription, -}); -export type CreateSharedExceptionListRequestBodyInput = z.input< - typeof CreateSharedExceptionListRequestBody ->; - -export type CreateSharedExceptionListResponse = z.infer; -export const CreateSharedExceptionListResponse = ExceptionList; diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml deleted file mode 100644 index c4cee089e583..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml +++ /dev/null @@ -1,68 +0,0 @@ -openapi: 3.0.0 -info: - title: Create shared exception list API endpoint - version: '2023-10-31' -paths: - /api/exceptions/shared: - post: - x-labels: [serverless, ess] - operationId: CreateSharedExceptionList - x-codegen-enabled: true - summary: Create a shared exception list - description: | - An exception list groups exception items and can be associated with detection rules. A shared exception list can apply to multiple detection rules. - > info - > All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - name: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListName' - description: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListDescription' - required: - - name - - description - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 409: - description: Exception list already exists response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml deleted file mode 100644 index 92afc3232efe..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml +++ /dev/null @@ -1,70 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete exception list API endpoint - version: '2023-10-31' -paths: - /api/exception_lists: - delete: - x-labels: [serverless, ess] - operationId: DeleteExceptionList - x-codegen-enabled: true - summary: Delete an exception list - description: Delete an exception list using the `id` or `list_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `list_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' - - name: list_id - in: query - required: false - description: Either `id` or `list_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' - - name: namespace_type - in: query - required: false - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - default: single - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml deleted file mode 100644 index 9f57afcd5ab1..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml +++ /dev/null @@ -1,70 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete exception list item API endpoint - version: '2023-10-31' -paths: - /api/exception_lists/items: - delete: - x-labels: [serverless, ess] - operationId: DeleteExceptionListItem - x-codegen-enabled: true - summary: Delete an exception list item - description: Delete an exception list item using the `id` or `item_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' - - name: item_id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' - - name: namespace_type - in: query - required: false - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - default: single - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml deleted file mode 100644 index 758171327ee4..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml +++ /dev/null @@ -1,71 +0,0 @@ -openapi: 3.0.0 -info: - title: Duplicate exception list API endpoint - version: '2023-10-31' -paths: - /api/exception_lists/_duplicate: - post: - x-labels: [serverless, ess] - operationId: DuplicateExceptionList - x-codegen-enabled: true - summary: Duplicate an exception list - description: Duplicate an existing exception list. - parameters: - - name: list_id - in: query - required: true - description: Exception list's human identifier - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' - - name: namespace_type - in: query - required: true - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - - name: include_expired_exceptions - in: query - required: true - description: Determines whether to include expired exceptions in the exported list - schema: - type: string - enum: ['true', 'false'] - default: 'true' - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 405: - description: Exception list to duplicate not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.ts b/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.ts deleted file mode 100644 index 9645b8ac793c..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Export exception list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { - ExceptionListId, - ExceptionListHumanId, - ExceptionNamespaceType, -} from '../model/exception_list_common.gen'; - -export type ExportExceptionListRequestQuery = z.infer; -export const ExportExceptionListRequestQuery = z.object({ - /** - * Exception list's identifier - */ - id: ExceptionListId, - /** - * Exception list's human identifier - */ - list_id: ExceptionListHumanId, - namespace_type: ExceptionNamespaceType, - /** - * Determines whether to include expired exceptions in the exported list - */ - include_expired_exceptions: z.enum(['true', 'false']).default('true'), -}); -export type ExportExceptionListRequestQueryInput = z.input; diff --git a/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml deleted file mode 100644 index 3232f46c238c..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml +++ /dev/null @@ -1,79 +0,0 @@ -openapi: 3.0.0 -info: - title: Export exception list API endpoint - version: '2023-10-31' -paths: - /api/exception_lists/_export: - post: - x-labels: [serverless, ess] - operationId: ExportExceptionList - x-codegen-enabled: true - summary: Export an exception list - description: Export an exception list and its associated items to an NDJSON file. - parameters: - - name: id - in: query - required: true - description: Exception list's identifier - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' - - name: list_id - in: query - required: true - description: Exception list's human identifier - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' - - name: namespace_type - in: query - required: true - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - - name: include_expired_exceptions - in: query - required: true - description: Determines whether to include expired exceptions in the exported list - schema: - type: string - enum: ['true', 'false'] - default: 'true' - responses: - 200: - description: Successful response - content: - application/ndjson: - schema: - type: string - format: binary - description: A `.ndjson` file containing specified exception list and its items - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/index.ts b/packages/kbn-securitysolution-exceptions-common/api/index.ts deleted file mode 100644 index fd6722b67ace..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './model/exception_list_common.gen'; -export * from './model/exception_list_item_entry.gen'; -export * from './create_exception_list_item/create_exception_list_item.gen'; -export * from './create_rule_exceptions/create_rule_exceptions.gen'; -export * from './create_shared_exceptions_list/create_shared_exceptions_list.gen'; -export * from './create_exception_list/create_exception_list.gen'; -export * from './delete_exception_list_item/delete_exception_list_item.gen'; -export * from './delete_exception_list/delete_exception_list.gen'; -export * from './duplicate_exception_list/duplicate_exception_list.gen'; -export * from './export_exception_list/export_exception_list.gen'; -export * from './find_exception_list_items/find_exception_list_items.gen'; -export * from './find_exception_lists/find_exception_lists.gen'; -export * from './import_exceptions/import_exceptions.gen'; -export * from './read_exception_list_item/read_exception_list_item.gen'; -export * from './read_exception_list/read_exception_list.gen'; -export * from './read_exception_list_summary/read_exception_list_summary.gen'; -export * from './update_exception_list_item/update_exception_list_item.gen'; -export * from './update_exception_list/update_exception_list.gen'; diff --git a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml deleted file mode 100644 index 883a62e5bbec..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml +++ /dev/null @@ -1,147 +0,0 @@ -openapi: 3.0.0 -info: - title: Common Exception List Item Entry Attributes - version: 'not applicable' -paths: {} -components: - x-codegen-enabled: true - schemas: - ExceptionListItemEntryOperator: - type: string - enum: [excluded, included] - - ExceptionListItemEntryMatch: - type: object - properties: - type: - type: string - enum: [match] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - value: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - operator: - $ref: '#/components/schemas/ExceptionListItemEntryOperator' - required: - - type - - field - - value - - operator - - ExceptionListItemEntryMatchAny: - type: object - properties: - type: - type: string - enum: [match_any] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - value: - type: array - items: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - minItems: 1 - operator: - $ref: '#/components/schemas/ExceptionListItemEntryOperator' - required: - - type - - field - - value - - operator - - ExceptionListItemEntryList: - type: object - properties: - type: - type: string - enum: [list] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - list: - type: object - properties: - id: - $ref: '../../../kbn-securitysolution-lists-common/api/model/list_common.schema.yaml#/components/schemas/ListId' - type: - $ref: '../../../kbn-securitysolution-lists-common/api/model/list_common.schema.yaml#/components/schemas/ListType' - required: [id, type] - operator: - $ref: '#/components/schemas/ExceptionListItemEntryOperator' - required: - - type - - field - - list - - operator - - ExceptionListItemEntryExists: - type: object - properties: - type: - type: string - enum: [exists] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - operator: - $ref: '#/components/schemas/ExceptionListItemEntryOperator' - required: - - type - - field - - operator - - ExceptionListItemEntryNestedEntryItem: - oneOf: - - $ref: '#/components/schemas/ExceptionListItemEntryMatch' - - $ref: '#/components/schemas/ExceptionListItemEntryMatchAny' - - $ref: '#/components/schemas/ExceptionListItemEntryExists' - - ExceptionListItemEntryNested: - type: object - properties: - type: - type: string - enum: [nested] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - entries: - type: array - items: - $ref: '#/components/schemas/ExceptionListItemEntryNestedEntryItem' - minItems: 1 - required: - - type - - field - - entries - - ExceptionListItemEntryMatchWildcard: - type: object - properties: - type: - type: string - enum: [wildcard] - field: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - value: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - operator: - $ref: '#/components/schemas/ExceptionListItemEntryOperator' - required: - - type - - field - - value - - operator - - ExceptionListItemEntry: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ExceptionListItemEntryMatch' - - $ref: '#/components/schemas/ExceptionListItemEntryMatchAny' - - $ref: '#/components/schemas/ExceptionListItemEntryList' - - $ref: '#/components/schemas/ExceptionListItemEntryExists' - - $ref: '#/components/schemas/ExceptionListItemEntryNested' - - $ref: '#/components/schemas/ExceptionListItemEntryMatchWildcard' - - ExceptionListItemEntryArray: - type: array - items: - $ref: '#/components/schemas/ExceptionListItemEntry' diff --git a/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts b/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts deleted file mode 100644 index 4827baab85e9..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts +++ /dev/null @@ -1,427 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Exceptions API client for quickstart - * version: Bundle (no version) - */ - -import type { KbnClient } from '@kbn/test'; -import { ToolingLog } from '@kbn/tooling-log'; -import { ELASTIC_HTTP_VERSION_HEADER } from '@kbn/core-http-common'; -import { replaceParams } from '@kbn/openapi-common/shared'; -import { catchAxiosErrorFormatAndThrow } from '@kbn/securitysolution-utils'; - -import type { - CreateExceptionListItemRequestBodyInput, - CreateExceptionListItemResponse, -} from './create_exception_list_item/create_exception_list_item.gen'; -import type { - CreateExceptionListRequestBodyInput, - CreateExceptionListResponse, -} from './create_exception_list/create_exception_list.gen'; -import type { - CreateRuleExceptionListItemsRequestParamsInput, - CreateRuleExceptionListItemsRequestBodyInput, - CreateRuleExceptionListItemsResponse, -} from './create_rule_exceptions/create_rule_exceptions.gen'; -import type { - CreateSharedExceptionListRequestBodyInput, - CreateSharedExceptionListResponse, -} from './create_shared_exceptions_list/create_shared_exceptions_list.gen'; -import type { - DeleteExceptionListItemRequestQueryInput, - DeleteExceptionListItemResponse, -} from './delete_exception_list_item/delete_exception_list_item.gen'; -import type { - DeleteExceptionListRequestQueryInput, - DeleteExceptionListResponse, -} from './delete_exception_list/delete_exception_list.gen'; -import type { - DuplicateExceptionListRequestQueryInput, - DuplicateExceptionListResponse, -} from './duplicate_exception_list/duplicate_exception_list.gen'; -import type { ExportExceptionListRequestQueryInput } from './export_exception_list/export_exception_list.gen'; -import type { - FindExceptionListItemsRequestQueryInput, - FindExceptionListItemsResponse, -} from './find_exception_list_items/find_exception_list_items.gen'; -import type { - FindExceptionListsRequestQueryInput, - FindExceptionListsResponse, -} from './find_exception_lists/find_exception_lists.gen'; -import type { - ImportExceptionListRequestQueryInput, - ImportExceptionListResponse, -} from './import_exceptions/import_exceptions.gen'; -import type { - ReadExceptionListItemRequestQueryInput, - ReadExceptionListItemResponse, -} from './read_exception_list_item/read_exception_list_item.gen'; -import type { - ReadExceptionListSummaryRequestQueryInput, - ReadExceptionListSummaryResponse, -} from './read_exception_list_summary/read_exception_list_summary.gen'; -import type { - ReadExceptionListRequestQueryInput, - ReadExceptionListResponse, -} from './read_exception_list/read_exception_list.gen'; -import type { - UpdateExceptionListItemRequestBodyInput, - UpdateExceptionListItemResponse, -} from './update_exception_list_item/update_exception_list_item.gen'; -import type { - UpdateExceptionListRequestBodyInput, - UpdateExceptionListResponse, -} from './update_exception_list/update_exception_list.gen'; - -export interface ClientOptions { - kbnClient: KbnClient; - log: ToolingLog; -} - -export class Client { - readonly kbnClient: KbnClient; - readonly log: ToolingLog; - - constructor(options: ClientOptions) { - this.kbnClient = options.kbnClient; - this.log = options.log; - } - /** - * An exception list groups exception items and can be associated with detection rules. You can assign detection rules with multiple exception lists. -> info -> All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. - - */ - async createExceptionList(props: CreateExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Create an exception item and associate it with the specified exception list. -> info -> Before creating exception items, you must create an exception list. - - */ - async createExceptionListItem(props: CreateExceptionListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateExceptionListItem`); - return this.kbnClient - .request({ - path: '/api/exception_lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Create exception items that apply to a single detection rule. - */ - async createRuleExceptionListItems(props: CreateRuleExceptionListItemsProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateRuleExceptionListItems`); - return this.kbnClient - .request({ - path: replaceParams('/api/detection_engine/rules/{id}/exceptions', props.params), - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * An exception list groups exception items and can be associated with detection rules. A shared exception list can apply to multiple detection rules. -> info -> All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. - - */ - async createSharedExceptionList(props: CreateSharedExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateSharedExceptionList`); - return this.kbnClient - .request({ - path: '/api/exceptions/shared', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Delete an exception list using the `id` or `list_id` field. - */ - async deleteExceptionList(props: DeleteExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API DeleteExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'DELETE', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Delete an exception list item using the `id` or `item_id` field. - */ - async deleteExceptionListItem(props: DeleteExceptionListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API DeleteExceptionListItem`); - return this.kbnClient - .request({ - path: '/api/exception_lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'DELETE', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Duplicate an existing exception list. - */ - async duplicateExceptionList(props: DuplicateExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API DuplicateExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists/_duplicate', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Export an exception list and its associated items to an NDJSON file. - */ - async exportExceptionList(props: ExportExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API ExportExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists/_export', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get a list of all exception list items in the specified list. - */ - async findExceptionListItems(props: FindExceptionListItemsProps) { - this.log.info(`${new Date().toISOString()} Calling API FindExceptionListItems`); - return this.kbnClient - .request({ - path: '/api/exception_lists/items/_find', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get a list of all exception lists. - */ - async findExceptionLists(props: FindExceptionListsProps) { - this.log.info(`${new Date().toISOString()} Calling API FindExceptionLists`); - return this.kbnClient - .request({ - path: '/api/exception_lists/_find', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Import an exception list and its associated items from an NDJSON file. - */ - async importExceptionList(props: ImportExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API ImportExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists/_import', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.attachment, - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get the details of an exception list using the `id` or `list_id` field. - */ - async readExceptionList(props: ReadExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API ReadExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get the details of an exception list item using the `id` or `item_id` field. - */ - async readExceptionListItem(props: ReadExceptionListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API ReadExceptionListItem`); - return this.kbnClient - .request({ - path: '/api/exception_lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get a summary of the specified exception list. - */ - async readExceptionListSummary(props: ReadExceptionListSummaryProps) { - this.log.info(`${new Date().toISOString()} Calling API ReadExceptionListSummary`); - return this.kbnClient - .request({ - path: '/api/exception_lists/summary', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update an exception list using the `id` or `list_id` field. - */ - async updateExceptionList(props: UpdateExceptionListProps) { - this.log.info(`${new Date().toISOString()} Calling API UpdateExceptionList`); - return this.kbnClient - .request({ - path: '/api/exception_lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PUT', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update an exception list item using the `id` or `item_id` field. - */ - async updateExceptionListItem(props: UpdateExceptionListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API UpdateExceptionListItem`); - return this.kbnClient - .request({ - path: '/api/exception_lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PUT', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } -} - -export interface CreateExceptionListProps { - body: CreateExceptionListRequestBodyInput; -} -export interface CreateExceptionListItemProps { - body: CreateExceptionListItemRequestBodyInput; -} -export interface CreateRuleExceptionListItemsProps { - params: CreateRuleExceptionListItemsRequestParamsInput; - body: CreateRuleExceptionListItemsRequestBodyInput; -} -export interface CreateSharedExceptionListProps { - body: CreateSharedExceptionListRequestBodyInput; -} -export interface DeleteExceptionListProps { - query: DeleteExceptionListRequestQueryInput; -} -export interface DeleteExceptionListItemProps { - query: DeleteExceptionListItemRequestQueryInput; -} -export interface DuplicateExceptionListProps { - query: DuplicateExceptionListRequestQueryInput; -} -export interface ExportExceptionListProps { - query: ExportExceptionListRequestQueryInput; -} -export interface FindExceptionListItemsProps { - query: FindExceptionListItemsRequestQueryInput; -} -export interface FindExceptionListsProps { - query: FindExceptionListsRequestQueryInput; -} -export interface ImportExceptionListProps { - query: ImportExceptionListRequestQueryInput; - attachment: FormData; -} -export interface ReadExceptionListProps { - query: ReadExceptionListRequestQueryInput; -} -export interface ReadExceptionListItemProps { - query: ReadExceptionListItemRequestQueryInput; -} -export interface ReadExceptionListSummaryProps { - query: ReadExceptionListSummaryRequestQueryInput; -} -export interface UpdateExceptionListProps { - body: UpdateExceptionListRequestBodyInput; -} -export interface UpdateExceptionListItemProps { - body: UpdateExceptionListItemRequestBodyInput; -} diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.ts b/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.ts deleted file mode 100644 index 67a832b01195..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Read exception list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { - ExceptionListId, - ExceptionListHumanId, - ExceptionNamespaceType, - ExceptionList, -} from '../model/exception_list_common.gen'; - -export type ReadExceptionListRequestQuery = z.infer; -export const ReadExceptionListRequestQuery = z.object({ - /** - * Either `id` or `list_id` must be specified - */ - id: ExceptionListId.optional(), - /** - * Either `id` or `list_id` must be specified - */ - list_id: ExceptionListHumanId.optional(), - namespace_type: ExceptionNamespaceType.optional().default('single'), -}); -export type ReadExceptionListRequestQueryInput = z.input; - -export type ReadExceptionListResponse = z.infer; -export const ReadExceptionListResponse = ExceptionList; diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml deleted file mode 100644 index 0bf082c1713b..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml +++ /dev/null @@ -1,70 +0,0 @@ -openapi: 3.0.0 -info: - title: Read exception list API endpoint - version: '2023-10-31' -paths: - /api/exception_lists: - get: - x-labels: [serverless, ess] - operationId: ReadExceptionList - x-codegen-enabled: true - summary: Get exception list details - description: Get the details of an exception list using the `id` or `list_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `list_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' - - name: list_id - in: query - required: false - description: Either `id` or `list_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' - - name: namespace_type - in: query - required: false - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - default: single - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml deleted file mode 100644 index c271016a87eb..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml +++ /dev/null @@ -1,70 +0,0 @@ -openapi: 3.0.0 -info: - title: Read exception list item API endpoint - version: '2023-10-31' -paths: - /api/exception_lists/items: - get: - x-labels: [serverless, ess] - operationId: ReadExceptionListItem - x-codegen-enabled: true - summary: Get an exception list item - description: Get the details of an exception list item using the `id` or `item_id` field. - parameters: - - name: id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' - - name: item_id - in: query - required: false - description: Either `id` or `item_id` must be specified - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' - - name: namespace_type - in: query - required: false - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - default: single - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml b/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml deleted file mode 100644 index b0627111e877..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml +++ /dev/null @@ -1,89 +0,0 @@ -openapi: 3.0.0 -info: - title: Read exception list summary API endpoint - version: '2023-10-31' -paths: - /api/exception_lists/summary: - get: - x-labels: [serverless, ess] - operationId: ReadExceptionListSummary - x-codegen-enabled: true - summary: Get an exception list summary - description: Get a summary of the specified exception list. - parameters: - - name: id - in: query - required: false - description: Exception list's identifier generated upon creation - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' - - name: list_id - in: query - required: false - description: Exception list's human readable identifier - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' - - name: namespace_type - in: query - required: false - schema: - $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' - default: single - - name: filter - in: query - required: false - description: Search filter clause - schema: - type: string - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - windows: - type: integer - minimum: 0 - linux: - type: integer - minimum: 0 - macos: - type: integer - minimum: 0 - total: - type: integer - minimum: 0 - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: Exception list not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/package.json b/packages/kbn-securitysolution-exceptions-common/package.json deleted file mode 100644 index 5148c4d5eedf..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "description": "Security Solution Exceptions common package", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "name": "@kbn/securitysolution-exceptions-common", - "private": true, - "version": "1.0.0", - "scripts": { - "openapi:generate": "node scripts/openapi_generate", - "openapi:bundle": "node scripts/openapi_bundle" - } -} diff --git a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js b/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js deleted file mode 100644 index 70299e56eac2..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { bundle } = require('@kbn/openapi-bundler'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/serverless/security_solution_exceptions_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['serverless'], - prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/exceptions_serverless.info.yaml'), - }, - }); - - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/ess/security_solution_exceptions_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['ess'], - prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/exceptions_ess.info.yaml'), - }, - }); -})(); diff --git a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js b/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js deleted file mode 100644 index 13b260476f3a..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { generate } = require('@kbn/openapi-generator'); -const { REPO_ROOT } = require('@kbn/repo-info'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await generate({ - title: 'OpenAPI Exceptions API Schemas', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'zod_operation_schema', - }); - - await generate({ - title: 'Exceptions API client for tests', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'api_client_supertest', - skipLinting: true, - bundle: { - outFile: join( - REPO_ROOT, - 'x-pack/test/api_integration/services/security_solution_exceptions_api.gen.ts' - ), - }, - }); - - await generate({ - title: 'Exceptions API client for quickstart', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'api_client_quickstart', - skipLinting: true, - bundle: { - outFile: join( - REPO_ROOT, - 'packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts' - ), - }, - }); -})(); diff --git a/packages/kbn-securitysolution-exceptions-common/tsconfig.json b/packages/kbn-securitysolution-exceptions-common/tsconfig.json deleted file mode 100644 index a58753f53a4f..000000000000 --- a/packages/kbn-securitysolution-exceptions-common/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "exclude": ["target/**/*"], - "extends": "../../tsconfig.base.json", - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/openapi-common", - "@kbn/zod-helpers", - "@kbn/securitysolution-lists-common", - "@kbn/test", - "@kbn/tooling-log", - "@kbn/core-http-common", - "@kbn/securitysolution-utils", - "@kbn/zod", - ] -} diff --git a/packages/kbn-securitysolution-hook-utils/index.ts b/packages/kbn-securitysolution-hook-utils/index.ts deleted file mode 100644 index be336bddcf9b..000000000000 --- a/packages/kbn-securitysolution-hook-utils/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/types'; -export * from './src/use_async'; -export * from './src/use_is_mounted'; -export * from './src/use_observable'; -export * from './src/with_optional_signal'; diff --git a/packages/kbn-securitysolution-hook-utils/jest.config.js b/packages/kbn-securitysolution-hook-utils/jest.config.js deleted file mode 100644 index badea193370b..000000000000 --- a/packages/kbn-securitysolution-hook-utils/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-hook-utils'], -}; diff --git a/packages/kbn-securitysolution-hook-utils/package.json b/packages/kbn-securitysolution-hook-utils/package.json deleted file mode 100644 index 71a83ce3ebb4..000000000000 --- a/packages/kbn-securitysolution-hook-utils/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-hook-utils", - "version": "1.0.0", - "description": "Security Solution utilities for React hooks", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-hook-utils/src/types.ts b/packages/kbn-securitysolution-hook-utils/src/types.ts deleted file mode 100644 index 6642afac7381..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/types.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/** - * Represents the state of an asynchronous task, along with an initiator - * function to kick off the work. - */ -export interface Task { - loading: boolean; - error: unknown | undefined; - result: Result | undefined; - start: (...args: Args) => void; -} diff --git a/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts b/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts deleted file mode 100644 index 99417c1fe329..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts +++ /dev/null @@ -1,166 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { waitFor, renderHook, act } from '@testing-library/react'; - -import { useAsync } from '.'; - -interface TestArgs { - n: number; - s: string; -} - -type TestReturn = Promise; - -describe('useAsync', () => { - /** - * Timeout for both jest tests and for the waitFor. - * jest tests default to 5 seconds and waitFor defaults to 1 second. - * 20_0000 = 20,000 milliseconds = 20 seconds - */ - const timeout = 20_000; - - let fn: jest.Mock; - let args: TestArgs; - - beforeEach(() => { - args = { n: 1, s: 's' }; - fn = jest.fn().mockResolvedValue(false); - }); - - it('does not invoke fn if start was not called', () => { - renderHook(() => useAsync(fn)); - expect(fn).not.toHaveBeenCalled(); - }); - - it( - 'invokes the function when start is called', - async () => { - const { result } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - await waitFor(() => expect(fn).toHaveBeenCalled(), { timeout }); - }, - timeout - ); - - it('invokes the function with start args', async () => { - const { result } = renderHook(() => useAsync(fn)); - const expectedArgs = { ...args }; - - act(() => { - result.current.start(args); - }); - await waitFor(() => expect(fn).toHaveBeenCalledWith(expectedArgs), { timeout }); - }); - - it( - 'populates result with the resolved value of the fn', - async () => { - const { result } = renderHook(() => useAsync(fn)); - fn.mockResolvedValue({ resolved: 'value' }); - - act(() => { - result.current.start(args); - }); - await waitFor( - () => { - expect(result.current.result).toEqual({ resolved: 'value' }); - expect(result.current.error).toBeUndefined(); - }, - { timeout } - ); - }, - timeout - ); - - it( - 'populates error if function rejects', - async () => { - fn.mockRejectedValue(new Error('whoops')); - const { result } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - - await waitFor( - () => { - expect(result.current.result).toBeUndefined(); - expect(result.current.error).toEqual(new Error('whoops')); - }, - { timeout } - ); - }, - timeout - ); - - it( - 'populates the loading state while the function is pending', - async () => { - let resolve: () => void; - fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); - - const { result } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => resolve()); - await waitFor(() => expect(result.current.loading).toBe(false), { timeout }); - }, - timeout - ); - - it( - 'multiple start calls reset state', - async () => { - let resolve: (result: string) => void; - fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); - - const { result } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => resolve('result')); - await waitFor( - () => { - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('result'); - }, - { timeout } - ); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - expect(result.current.result).toBe(undefined); - act(() => resolve('result')); - await waitFor( - () => { - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('result'); - }, - { timeout } - ); - }, - timeout - ); -}); diff --git a/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts b/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts deleted file mode 100644 index 2c695b26acdd..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts +++ /dev/null @@ -1,56 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback, useState } from 'react'; - -import { Task } from '../types'; -import { useIsMounted } from '../use_is_mounted'; - -/** - * - * This hook wraps a promise-returning thunk (task) in order to conditionally - * initiate the work, and automatically provide state corresponding to the - * task's status. - * - * In order to function properly and not rerender unnecessarily, ensure that - * your task is a stable function reference. - * - * @param fn a function returning a promise. - * - * @returns An {@link Task} containing the task's current state along with a - * start callback - */ -export const useAsync = ( - fn: (...args: Args) => Promise -): Task => { - const isMounted = useIsMounted(); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(); - const [result, setResult] = useState(); - - const start = useCallback( - (...args: Args) => { - setLoading(true); - setResult(undefined); - setError(undefined); - fn(...args) - .then((r) => isMounted() && setResult(r)) - .catch((e) => isMounted() && setError(e)) - .finally(() => isMounted() && setLoading(false)); - }, - [fn, isMounted] - ); - - return { - error, - loading, - result, - start, - }; -}; diff --git a/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.ts b/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.ts deleted file mode 100644 index a8013a65441c..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { renderHook } from '@testing-library/react'; - -import { useIsMounted } from '.'; - -describe('useIsMounted', () => { - it('evaluates to true when mounted', () => { - const { result } = renderHook(() => useIsMounted()); - - expect(result.current()).toEqual(true); - }); - - it('evaluates to false when unmounted', () => { - const { result, unmount } = renderHook(() => useIsMounted()); - - unmount(); - expect(result.current()).toEqual(false); - }); -}); diff --git a/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts b/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts deleted file mode 100644 index b563840d2f73..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback, useEffect, useRef } from 'react'; - -type GetIsMounted = () => boolean; - -/** - * - * @returns A {@link GetIsMounted} getter function returning whether the component is currently mounted - */ -export const useIsMounted = (): GetIsMounted => { - const isMounted = useRef(false); - const getIsMounted: GetIsMounted = useCallback(() => isMounted.current, []); - const handleCleanup = useCallback(() => { - isMounted.current = false; - }, []); - - useEffect(() => { - isMounted.current = true; - return handleCleanup; - }, [handleCleanup]); - - return getIsMounted; -}; diff --git a/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts b/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts deleted file mode 100644 index 8d90bffeb3ee..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts +++ /dev/null @@ -1,161 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { renderHook, act } from '@testing-library/react'; -import { Subject, throwError } from 'rxjs'; - -import { useObservable } from '.'; - -interface TestArgs { - n: number; - s: string; -} - -type TestReturn = Subject; - -describe('useObservable', () => { - let fn: jest.Mock; - let subject: TestReturn; - let args: TestArgs; - - beforeEach(() => { - args = { n: 1, s: 's' }; - subject = new Subject(); - fn = jest.fn().mockReturnValue(subject); - }); - - it('does not invoke fn if start was not called', () => { - renderHook(() => useObservable(fn)); - expect(fn).not.toHaveBeenCalled(); - }); - - it('invokes the function when start is called', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - - expect(fn).toHaveBeenCalled(); - }); - - it('invokes the function with start args', () => { - const { result } = renderHook(() => useObservable(fn)); - const expectedArgs = { ...args }; - - act(() => { - result.current.start(args); - }); - - expect(fn).toHaveBeenCalledWith(expectedArgs); - }); - - it('populates result with the next value of the fn', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - act(() => subject.next('value')); - - expect(result.current.result).toEqual('value'); - expect(result.current.error).toBeUndefined(); - }); - - it('populates error if observable throws an error', () => { - const error = new Error('whoops'); - const errorFn = () => throwError(error); - - const { result } = renderHook(() => useObservable(errorFn)); - - act(() => { - result.current.start(); - }); - - expect(result.current.result).toBeUndefined(); - expect(result.current.error).toEqual(error); - }); - - it('populates the loading state while no value has resolved', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => subject.next('a value')); - - expect(result.current.loading).toBe(false); - }); - - it('updates result with each resolved value', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - - act(() => subject.next('a value')); - expect(result.current.result).toEqual('a value'); - - act(() => subject.next('a subsequent value')); - expect(result.current.result).toEqual('a subsequent value'); - }); - - it('does not update result with values if start has not been called', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => subject.next('a value')); - expect(result.current.result).toBeUndefined(); - - act(() => subject.next('a subsequent value')); - expect(result.current.result).toBeUndefined(); - }); - - it('unsubscribes on unmount', () => { - const { result, unmount } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - expect(subject.observers).toHaveLength(1); - - unmount(); - expect(subject.observers).toHaveLength(0); - }); - - it('multiple start calls reset state', () => { - const { result } = renderHook(() => useObservable(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => subject.next('one value')); - - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('one value'); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - expect(result.current.result).toBe(undefined); - - act(() => subject.next('another value')); - - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('another value'); - }); -}); diff --git a/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts b/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts deleted file mode 100644 index 0b7f9ab93e02..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts +++ /dev/null @@ -1,93 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback, useEffect, useRef, useReducer, Reducer } from 'react'; -import { Observable, Subscription } from 'rxjs'; - -import { useIsMounted } from '../use_is_mounted'; -import { Task } from '../types'; - -interface State { - loading: boolean; - error?: unknown; - result?: T; -} - -export type Action = - | { type: 'setResult'; result: T } - | { type: 'setError'; error: unknown } - | { type: 'load' }; - -function reducer(state: State, action: Action) { - switch (action.type) { - case 'setResult': - return { ...state, result: action.result, loading: false }; - case 'setError': - return { ...state, error: action.error, loading: false }; - case 'load': - return { loading: true, result: undefined, error: undefined }; - } -} - -/** - * - * @param fn function returning an observable - * - * @returns An {@link Async} containing the underlying task's state along with a start callback - */ -export const useObservable = ( - fn: (...args: Args) => Observable -): Task => { - const isMounted = useIsMounted(); - const subRef = useRef(); - const [state, dispatch] = useReducer, Action>>(reducer, { - loading: false, - error: undefined, - result: undefined, - }); - - const start = useCallback( - (...args: Args) => { - if (subRef.current) { - subRef.current.unsubscribe(); - } - dispatch({ type: 'load' }); - - subRef.current = fn(...args).subscribe( - (r) => { - if (isMounted()) { - dispatch({ type: 'setResult', result: r }); - } - }, - (e) => { - if (isMounted()) { - dispatch({ type: 'setError', error: e }); - } - } - ); - }, - [fn, isMounted] - ); - - useEffect( - () => () => { - if (subRef.current) { - subRef.current.unsubscribe(); - } - }, - [] - ); - - return { - result: state.result, - error: state.error, - loading: state.loading, - start, - }; -}; diff --git a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.ts b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.ts deleted file mode 100644 index fa77482d24be..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { withOptionalSignal } from '.'; - -type TestFn = ({ number, signal }: { number: number; signal: AbortSignal }) => boolean; - -describe('withOptionalSignal', () => { - it('does not require a signal on the returned function', () => { - const fn = jest.fn().mockReturnValue('hello') as TestFn; - - const wrappedFn = withOptionalSignal(fn); - - expect(wrappedFn({ number: 1 })).toEqual('hello'); - }); - - it('will pass a given signal to the wrapped function', () => { - const fn = jest.fn().mockReturnValue('hello') as TestFn; - const { signal } = new AbortController(); - - const wrappedFn = withOptionalSignal(fn); - - wrappedFn({ number: 1, signal }); - expect(fn).toHaveBeenCalledWith({ number: 1, signal }); - }); -}); diff --git a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts deleted file mode 100644 index eb7cffeb7e00..000000000000 --- a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -interface SignalArgs { - signal: AbortSignal; -} - -export type OptionalSignalArgs = Omit & Partial; - -/** - * - * @param fn an async function receiving an AbortSignal argument - * - * @returns An async function where the AbortSignal argument is optional - */ -export const withOptionalSignal = - (fn: (args: Args) => Result) => - (args: OptionalSignalArgs): Result => { - const signal = args.signal != null ? args.signal : new AbortController().signal; - return fn({ ...args, signal } as Args); - }; diff --git a/packages/kbn-securitysolution-hook-utils/tsconfig.json b/packages/kbn-securitysolution-hook-utils/tsconfig.json deleted file mode 100644 index 9b5c5373afe0..000000000000 --- a/packages/kbn-securitysolution-hook-utils/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/index.ts deleted file mode 100644 index 6baaf0a70403..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/actions'; -export * from './src/default_actions_array'; -export * from './src/default_export_file_name'; -export * from './src/default_from_string'; -export * from './src/default_interval_string'; -export * from './src/default_language_string'; -export * from './src/default_max_signals_number'; -export * from './src/default_page'; -export * from './src/default_per_page'; -export * from './src/default_risk_score_mapping_array'; -export * from './src/default_severity_mapping_array'; -export * from './src/default_threat_array'; -export * from './src/default_to_string'; -export * from './src/default_uuid'; -export * from './src/frequency'; -export * from './src/language'; -export * from './src/machine_learning_job_id'; -export * from './src/max_signals'; -export * from './src/normalized_ml_job_id'; -export * from './src/references_default_array'; -export * from './src/risk_score'; -export * from './src/risk_score_mapping'; -export * from './src/rule_schedule'; -export * from './src/saved_object_attributes'; -export * from './src/severity'; -export * from './src/severity_mapping'; -export * from './src/threat'; -export * from './src/threat_mapping'; -export * from './src/threat_subtechnique'; -export * from './src/threat_tactic'; -export * from './src/threat_technique'; -export * from './src/throttle'; -export * from './src/type'; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js b/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js deleted file mode 100644 index b4c7014f9154..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-io-ts-alerting-types'], -}; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/package.json b/packages/kbn-securitysolution-io-ts-alerting-types/package.json deleted file mode 100644 index ab19f69d20b3..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-io-ts-alerting-types", - "version": "1.0.0", - "description": "io ts utilities and types to be shared with plugins from the security solution project", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts deleted file mode 100644 index ad1dde3da745..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts +++ /dev/null @@ -1,129 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -import * as t from 'io-ts'; -import { saved_object_attributes } from '../saved_object_attributes'; -import { RuleActionFrequency } from '../frequency'; - -export type RuleActionGroup = t.TypeOf; -export const RuleActionGroup = t.string; - -export type RuleActionId = t.TypeOf; -export const RuleActionId = t.string; - -export type RuleActionTypeId = t.TypeOf; -export const RuleActionTypeId = t.string; - -export type RuleActionUuid = t.TypeOf; -export const RuleActionUuid = NonEmptyString; - -/** - * Params is an "object", since it is a type of RuleActionParams which is action templates. - * @see x-pack/plugins/alerting/common/rule.ts - */ -export type RuleActionParams = t.TypeOf; -export const RuleActionParams = saved_object_attributes; - -export const RuleActionAlertsFilter = t.partial({ - query: t.union([ - t.undefined, - t.intersection([ - t.strict({ - kql: t.string, - filters: t.array( - t.intersection([ - t.type({ - meta: t.partial({ - alias: t.union([t.string, t.null]), - disabled: t.boolean, - negate: t.boolean, - controlledBy: t.string, - group: t.string, - index: t.string, - isMultiIndex: t.boolean, - type: t.string, - key: t.string, - params: t.any, - value: t.string, - }), - }), - t.partial({ - $state: t.type({ store: t.any }), - query: t.record(t.string, t.any), - }), - ]) - ), - }), - t.partial({ dsl: t.string }), - ]), - ]), - timeframe: t.union([ - t.undefined, - t.strict({ - timezone: t.string, - days: t.array( - t.union([ - t.literal(1), - t.literal(2), - t.literal(3), - t.literal(4), - t.literal(5), - t.literal(6), - t.literal(7), - ]) - ), - hours: t.strict({ - start: t.string, - end: t.string, - }), - }), - ]), -}); - -export type RuleAction = t.TypeOf; -export const RuleAction = t.exact( - t.intersection([ - t.type({ - group: RuleActionGroup, - id: RuleActionId, - action_type_id: RuleActionTypeId, - params: RuleActionParams, - }), - t.partial({ - uuid: RuleActionUuid, - alerts_filter: RuleActionAlertsFilter, - frequency: RuleActionFrequency, - }), - ]) -); - -export type RuleActionArray = t.TypeOf; -export const RuleActionArray = t.array(RuleAction); - -export type RuleActionCamel = t.TypeOf; -export const RuleActionCamel = t.exact( - t.intersection([ - t.type({ - group: RuleActionGroup, - id: RuleActionId, - actionTypeId: RuleActionTypeId, - params: RuleActionParams, - }), - t.partial({ - uuid: RuleActionUuid, - alertsFilter: RuleActionAlertsFilter, - frequency: RuleActionFrequency, - }), - ]) -); - -export type RuleActionArrayCamel = t.TypeOf; -export const RuleActionArrayCamel = t.array(RuleActionCamel); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.ts deleted file mode 100644 index bb398e0df846..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const ENTRY_VALUE = 'some host name'; -export const FIELD = 'host.name'; -export const MATCH = 'match'; -export const MATCH_ANY = 'match_any'; -export const OPERATOR = 'included'; -export const NESTED = 'nested'; -export const NESTED_FIELD = 'parent.field'; -export const LIST_ID = 'some-list-id'; -export const LIST = 'list'; -export const TYPE = 'ip'; -export const EXISTS = 'exists'; -export const WILDCARD = 'wildcard'; -export const USER = 'some user'; -export const DATE_NOW = '2020-04-20T15:25:31.830Z'; - -// Exception List specific -export const ID = 'uuid_here'; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts deleted file mode 100644 index 0c930e5f4a80..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/** - * TODO: Create a kbn-alerting-constants and add this to it. - * @deprecated Use a DEFAULT_MAX_SIGNALS from a kbn-alerting-constants package. - */ -export const DEFAULT_MAX_SIGNALS = 100; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/index.ts deleted file mode 100644 index 17c3f9301c6d..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { RuleActionArray } from '../actions'; - -export const DefaultActionsArray = new t.Type< - RuleActionArray, - RuleActionArray | undefined, - unknown ->( - 'DefaultActionsArray', - RuleActionArray.is, - (input, context): Either => - input == null ? t.success([]) : RuleActionArray.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts deleted file mode 100644 index b07ade238db2..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultExportFileName } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts deleted file mode 100644 index dedbadfa6f52..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts deleted file mode 100644 index 2515b3f8b015..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultFromString } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.ts deleted file mode 100644 index ccf70aab8a7b..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { From } from '../from'; - -/** - * Types the DefaultFromString as: - * - If null or undefined, then a default of the string "now-6m" will be used - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts deleted file mode 100644 index 8944d57ba899..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultIntervalString } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts deleted file mode 100644 index 3fc5d4f42ccb..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts deleted file mode 100644 index 4a8d50c88eaa..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts +++ /dev/null @@ -1,45 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { Language } from '../language'; -import { DefaultLanguageString } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.ts deleted file mode 100644 index 02328d94b011..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { language } from '../language'; - -/** - * Types the DefaultLanguageString as: - * - If null or undefined, then a default of the string "kuery" will be used - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts deleted file mode 100644 index 66eb77400ac1..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts +++ /dev/null @@ -1,67 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultMaxSignalsNumber } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.ts deleted file mode 100644 index 8acbc2f223a1..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { max_signals } from '../max_signals'; -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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts deleted file mode 100644 index 5af986fefe8d..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts +++ /dev/null @@ -1,86 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultPage } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.ts deleted file mode 100644 index 8486c516aebf..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; - -/** - * 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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts deleted file mode 100644 index 78fa2a9be8c8..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts +++ /dev/null @@ -1,86 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultPerPage } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.ts deleted file mode 100644 index 4f272fc0517e..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; - -/** - * 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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.ts deleted file mode 100644 index 9eb6938bcfcb..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { RiskScoreMapping } from '../risk_score_mapping'; - -/** - * Types the DefaultStringArray as: - * - If null or undefined, then a default RiskScoreMapping array will be set - */ -export const DefaultRiskScoreMappingArray = new t.Type< - RiskScoreMapping, - RiskScoreMapping | undefined, - unknown ->( - 'DefaultRiskScoreMappingArray', - RiskScoreMapping.is, - (input, context): Either => - input == null ? t.success([]) : RiskScoreMapping.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.ts deleted file mode 100644 index ac72e3330f2a..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { SeverityMapping } from '../severity_mapping'; - -/** - * Types the DefaultStringArray as: - * - If null or undefined, then a default SeverityMapping array will be set - */ -export const DefaultSeverityMappingArray = new t.Type< - SeverityMapping, - SeverityMapping | undefined, - unknown ->( - 'DefaultSeverityMappingArray', - SeverityMapping.is, - (input, context): Either => - input == null ? t.success([]) : SeverityMapping.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts deleted file mode 100644 index ebd1ca9384b1..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts +++ /dev/null @@ -1,67 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { Threats } from '../threat'; -import { DefaultThreatArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.ts deleted file mode 100644 index bb38b6382230..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { threats, Threats } from '../threat'; - -/** - * Types the DefaultThreatArray as: - * - If null or undefined, then an empty array will be set - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts deleted file mode 100644 index e8bcdcc664cf..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultToString } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts deleted file mode 100644 index 4074cc3bbbe9..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.ts deleted file mode 100644 index 4144b4e6824c..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { v4 as uuidv4 } from 'uuid'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -/** - * Types the DefaultUuid as: - * - If null or undefined, then a default string uuidv4() will be - * created otherwise it will be checked just against an empty string - */ -export const DefaultUuid = new t.Type( - 'DefaultUuid', - t.string.is, - (input, context): Either => - input == null ? t.success(uuidv4()) : NonEmptyString.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.ts deleted file mode 100644 index 0247bfb155f3..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RuleActionThrottle } from '../throttle'; - -/** - * Action summary indicates whether we will send a summary notification about all the generate alerts or notification per individual alert - */ -export type RuleActionSummary = t.TypeOf; -export const RuleActionSummary = t.boolean; - -/** - * The condition for throttling the notification: `onActionGroupChange`, `onActiveAlert`, or `onThrottleInterval` - */ -export type RuleActionNotifyWhen = t.TypeOf; -export const RuleActionNotifyWhen = t.union([ - t.literal('onActionGroupChange'), - t.literal('onActiveAlert'), - t.literal('onThrottleInterval'), -]); - -/** - * The action frequency defines when the action runs (for example, only on rule execution or at specific time intervals). - */ -export type RuleActionFrequency = t.TypeOf; -export const RuleActionFrequency = t.type({ - summary: RuleActionSummary, - notifyWhen: RuleActionNotifyWhen, - throttle: t.union([RuleActionThrottle, t.null]), -}); 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 deleted file mode 100644 index 390649416273..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Either } from 'fp-ts/lib/Either'; -import * as t from 'io-ts'; -import { parseScheduleDates } from '@kbn/securitysolution-io-ts-utils'; - -const stringValidator = (input: unknown): input is string => typeof input === 'string'; - -export type From = t.TypeOf; -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 -); 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 deleted file mode 100644 index 95017209b2c6..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const language = t.keyof({ eql: null, kuery: null, lucene: null, esql: 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 deleted file mode 100644 index 00dc70eb5575..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", 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 deleted file mode 100644 index aa8bdf6f539a..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; - -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/normalized_ml_job_id/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/normalized_ml_job_id/index.ts deleted file mode 100644 index 2d89147c4fa1..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/normalized_ml_job_id/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -import { NonEmptyArray } from '@kbn/securitysolution-io-ts-types'; - -export const machine_learning_job_id_normalized = NonEmptyArray(t.string); -export type MachineLearningJobIdNormalized = t.TypeOf; - -export const machineLearningJobIdNormalizedOrUndefined = t.union([ - machine_learning_job_id_normalized, - t.undefined, -]); -export type MachineLearningJobIdNormalizedOrUndefined = t.TypeOf< - typeof machineLearningJobIdNormalizedOrUndefined ->; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.test.ts deleted file mode 100644 index 7b6146a320d6..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { ReferencesDefaultArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('default_string_array', () => { - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = ReferencesDefaultArray.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 = ReferencesDefaultArray.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 = ReferencesDefaultArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "referencesWithDefaultArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = ReferencesDefaultArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts deleted file mode 100644 index fcf22ad918c9..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -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 - */ -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/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts deleted file mode 100644 index 85d83d0ec77d..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts +++ /dev/null @@ -1,62 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { RiskScore } from '.'; - -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/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 deleted file mode 100644 index ecc48e9a699d..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -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. - */ -export type RiskScore = t.TypeOf; -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 -); 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 deleted file mode 100644 index 59f7c7ab69fb..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { operator } from '@kbn/securitysolution-io-ts-types'; -import { RiskScore } from '../risk_score'; - -export type RiskScoreMappingItem = t.TypeOf; -export const RiskScoreMappingItem = t.exact( - t.type({ - field: t.string, - value: t.string, - operator, - risk_score: t.union([RiskScore, t.undefined]), - }) -); - -export type RiskScoreMapping = t.TypeOf; -export const RiskScoreMapping = t.array(RiskScoreMappingItem); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts deleted file mode 100644 index 4d0113f330ae..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { From } from '../from'; - -export type RuleInterval = t.TypeOf; -export const RuleInterval = t.string; // we need a more specific schema - -export type RuleIntervalFrom = t.TypeOf; -export const RuleIntervalFrom = From; - -/** - * TODO: Create a regular expression type or custom date math part type here - */ -export type RuleIntervalTo = t.TypeOf; -export const RuleIntervalTo = t.string; // we need a more specific schema diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.ts deleted file mode 100644 index 2a7af4e66518..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -/** - * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove - * this copied type. - * - * Don't use this type, it's simply a helper type for {@link SavedObjectAttribute} - * - * @public - */ -export type SavedObjectAttributeSingle = - | string - | number - | boolean - | null - | undefined - | SavedObjectAttributes; - -/** - * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove - * this copied type. - * - * Type definition for a Saved Object attribute value - * - * @public - */ -export type SavedObjectAttribute = SavedObjectAttributeSingle | SavedObjectAttributeSingle[]; - -/** - * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove - * this copied type. - * - * The data for a Saved Object is stored as an object in the `attributes` - * property. - * - * @public - */ -export interface SavedObjectAttributes { - [key: string]: SavedObjectAttribute; -} - -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]) -); -export const saved_object_attribute: t.Type = t.recursion( - 'saved_object_attribute', - () => t.union([saved_object_attribute_single, t.array(saved_object_attribute_single)]) -); -export const saved_object_attributes: t.Type = t.recursion( - 'saved_object_attributes', - () => t.record(t.string, saved_object_attribute) -); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts deleted file mode 100644 index fef1082129df..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts +++ /dev/null @@ -1,13 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export type Severity = t.TypeOf; -export const Severity = t.keyof({ low: null, medium: null, high: null, critical: null }); diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.ts deleted file mode 100644 index afd7889658a3..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { operator } from '@kbn/securitysolution-io-ts-types'; -import { Severity } from '../severity'; - -export type SeverityMappingItem = t.TypeOf; -export const SeverityMappingItem = t.exact( - t.type({ - field: t.string, - operator, - value: t.string, - severity: Severity, - }) -); - -export type SeverityMapping = t.TypeOf; -export const SeverityMapping = t.array(SeverityMappingItem); 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 deleted file mode 100644 index e60f9ccafcc1..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { threat_tactic } from '../threat_tactic'; -import { threat_techniques } from '../threat_technique'; - -export const threat_framework = t.string; - -export const threat = t.intersection([ - t.exact( - t.type({ - framework: threat_framework, - tactic: threat_tactic, - }) - ), - t.exact( - t.partial({ - technique: threat_techniques, - }) - ), -]); - -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_mapping/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts deleted file mode 100644 index 3d3e1ab9a22b..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts +++ /dev/null @@ -1,237 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { - concurrent_searches, - items_per_search, - ThreatMapping, - threatMappingEntries, - ThreatMappingEntries, - threat_mapping, -} from '.'; -import { foldLeftRight, getPaths, exactCheck } from '@kbn/securitysolution-io-ts-utils'; - -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: Array = [ - { - 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: Array = [ - { - 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: Array }> = [ - { - 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/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts deleted file mode 100644 index 0cc8c950f754..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts +++ /dev/null @@ -1,79 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { - NonEmptyArray, - NonEmptyString, - PositiveIntegerGreaterThanZero, -} from '@kbn/securitysolution-io-ts-types'; -import { language } from '../language'; - -export const threat_query = t.string; -export type ThreatQuery = t.TypeOf; -export const threatQueryOrUndefined = t.union([threat_query, t.undefined]); -export type ThreatQueryOrUndefined = t.TypeOf; - -export const threat_indicator_path = t.string; -export type ThreatIndicatorPath = t.TypeOf; -export const threatIndicatorPathOrUndefined = t.union([threat_indicator_path, t.undefined]); -export type ThreatIndicatorPathOrUndefined = t.TypeOf; - -export const threat_filters = t.array(t.unknown); // Filters are not easily type-able yet -export type ThreatFilters = t.TypeOf; -export const threatFiltersOrUndefined = t.union([threat_filters, t.undefined]); -export type ThreatFiltersOrUndefined = t.TypeOf; - -export const threatMapEntry = t.exact( - t.type({ - field: NonEmptyString, - type: t.keyof({ mapping: null }), - value: NonEmptyString, - }) -); - -export type ThreatMapEntry = t.TypeOf; - -export const threatMappingEntries = t.array(threatMapEntry); -export type ThreatMappingEntries = t.TypeOf; - -export const threatMap = t.exact( - t.type({ - entries: threatMappingEntries, - }) -); -export type ThreatMap = t.TypeOf; - -export const threat_mapping = NonEmptyArray(threatMap, 'NonEmptyArray'); -export type ThreatMapping = t.TypeOf; - -export const threatMappingOrUndefined = t.union([threat_mapping, t.undefined]); -export type ThreatMappingOrUndefined = t.TypeOf; - -export const threat_index = t.array(t.string); -export type ThreatIndex = t.TypeOf; -export const threatIndexOrUndefined = t.union([threat_index, t.undefined]); -export type ThreatIndexOrUndefined = t.TypeOf; - -export const threat_language = t.union([language, t.undefined]); -export type ThreatLanguage = t.TypeOf; -export const threatLanguageOrUndefined = t.union([threat_language, t.undefined]); -export type ThreatLanguageOrUndefined = t.TypeOf; - -export const concurrent_searches = PositiveIntegerGreaterThanZero; -export type ConcurrentSearches = t.TypeOf; -export const concurrentSearchesOrUndefined = t.union([concurrent_searches, t.undefined]); -export type ConcurrentSearchesOrUndefined = t.TypeOf; - -export const items_per_search = PositiveIntegerGreaterThanZero; -export type ItemsPerSearch = t.TypeOf; -export const itemsPerSearchOrUndefined = t.union([items_per_search, t.undefined]); -export type ItemsPerSearchOrUndefined = 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 deleted file mode 100644 index 963bf76bf5f8..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const threat_subtechnique_id = t.string; -export const threat_subtechnique_name = t.string; -export const threat_subtechnique_reference = t.string; - -export const threat_subtechnique = t.type({ - id: threat_subtechnique_id, - name: threat_subtechnique_name, - reference: threat_subtechnique_reference, -}); - -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_tactic/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_tactic/index.ts deleted file mode 100644 index a142788876e7..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_tactic/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const threat_tactic_id = t.string; -export const threat_tactic_name = t.string; -export const threat_tactic_reference = t.string; - -export const threat_tactic = t.type({ - id: threat_tactic_id, - name: threat_tactic_name, - reference: threat_tactic_reference, -}); 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 deleted file mode 100644 index 2953ea86b3b3..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { threat_subtechniques } from '../threat_subtechnique'; - -export const threat_technique_id = t.string; -export const threat_technique_name = t.string; -export const threat_technique_reference = t.string; - -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, - }) - ), -]); -export const threat_techniques = t.array(threat_technique); - -export type ThreatTechnique = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts deleted file mode 100644 index f1d6bdca8fed..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { TimeDuration } from '@kbn/securitysolution-io-ts-types'; - -export type RuleActionThrottle = t.TypeOf; -export const RuleActionThrottle = t.union([ - t.literal('no_actions'), - t.literal('rule'), - TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }), -]); 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 deleted file mode 100644 index 68c7a2f30a2b..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", 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, - new_terms: null, - esql: 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-alerting-types/tsconfig.json b/packages/kbn-securitysolution-io-ts-alerting-types/tsconfig.json deleted file mode 100644 index f9fb0b0fcebb..000000000000 --- a/packages/kbn-securitysolution-io-ts-alerting-types/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/securitysolution-io-ts-types", - "@kbn/securitysolution-io-ts-utils" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-io-ts-list-types/index.ts b/packages/kbn-securitysolution-io-ts-list-types/index.ts deleted file mode 100644 index 6d6b4e241b6d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/index.ts +++ /dev/null @@ -1,13 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/common'; -export * from './src/request'; -export * from './src/response'; -export * from './src/typescript_types'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/jest.config.js b/packages/kbn-securitysolution-io-ts-list-types/jest.config.js deleted file mode 100644 index adcf48629dd7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-io-ts-list-types'], -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/package.json b/packages/kbn-securitysolution-io-ts-list-types/package.json deleted file mode 100644 index 50c88fb22054..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-io-ts-list-types", - "version": "1.0.0", - "description": "io ts utilities and types to be shared with plugins from the security solution project", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.ts deleted file mode 100644 index d824f23fe74b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Comment, CommentsArray } from '.'; -import { DATE_NOW, ID, USER } from '../../constants/index.mock'; - -export const getCommentsMock = (): Comment => ({ - comment: 'some old comment', - created_at: DATE_NOW, - created_by: USER, - id: ID, -}); - -export const getCommentsArrayMock = (): CommentsArray => [getCommentsMock(), getCommentsMock()]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts deleted file mode 100644 index deca11f809cb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts +++ /dev/null @@ -1,238 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getCommentsArrayMock, getCommentsMock } from './index.mock'; -import { - Comment, - comment, - CommentsArray, - commentsArray, - CommentsArrayOrUndefined, - commentsArrayOrUndefined, -} from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { DATE_NOW } from '../../constants/index.mock'; - -describe('Comment', () => { - describe('comment', () => { - test('it fails validation when "id" is undefined', () => { - const payload = { ...getCommentsMock(), id: undefined }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it passes validation with a typical comment', () => { - const payload = getCommentsMock(); - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation with "updated_at" and "updated_by" fields included', () => { - const payload = getCommentsMock(); - payload.updated_at = DATE_NOW; - payload.updated_by = 'someone'; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "comment" is an empty string', () => { - const payload: Omit & { comment: string } = { - ...getCommentsMock(), - comment: '', - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "comment" is not a string', () => { - const payload: Omit & { comment: string[] } = { - ...getCommentsMock(), - comment: ['some value'], - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "comment"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "created_at" is not a string', () => { - const payload: Omit & { created_at: number } = { - ...getCommentsMock(), - created_at: 1, - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "created_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "created_by" is not a string', () => { - const payload: Omit & { created_by: number } = { - ...getCommentsMock(), - created_by: 1, - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "created_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "updated_at" is not a string', () => { - const payload: Omit & { updated_at: number } = { - ...getCommentsMock(), - updated_at: 1, - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "updated_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "updated_by" is not a string', () => { - const payload: Omit & { updated_by: number } = { - ...getCommentsMock(), - updated_by: 1, - }; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "updated_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: Comment & { - extraKey?: string; - } = getCommentsMock(); - payload.extraKey = 'some value'; - const decoded = comment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getCommentsMock()); - }); - }); - - describe('commentsArray', () => { - test('it passes validation an array of Comment', () => { - const payload = getCommentsArrayMock(); - const decoded = commentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation when a Comment includes "updated_at" and "updated_by"', () => { - const commentsPayload = getCommentsMock(); - commentsPayload.updated_at = DATE_NOW; - commentsPayload.updated_by = 'someone'; - const payload = [{ ...commentsPayload }, ...getCommentsArrayMock()]; - const decoded = commentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = commentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when array includes non Comment types', () => { - const payload = [1] as unknown as CommentsArray; - const decoded = commentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('commentsArrayOrUndefined', () => { - test('it passes validation an array of Comment', () => { - const payload = getCommentsArrayMock(); - const decoded = commentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation when undefined', () => { - const payload = undefined; - const decoded = commentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when array includes non Comment types', () => { - const payload = [1] as unknown as CommentsArrayOrUndefined; - const decoded = commentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.ts deleted file mode 100644 index 3aac99e6c48e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { created_at } from '../created_at'; -import { created_by } from '../created_by'; -import { id } from '../id'; -import { updated_at } from '../updated_at'; -import { updated_by } from '../updated_by'; - -export const comment = t.intersection([ - t.exact( - t.type({ - comment: NonEmptyString, - created_at, - created_by, - id, - }) - ), - t.exact( - t.partial({ - updated_at, - updated_by, - }) - ), -]); - -export const commentsArray = t.array(comment); -export type CommentsArray = t.TypeOf; -export type Comment = t.TypeOf; -export const commentsArrayOrUndefined = t.union([commentsArray, t.undefined]); -export type CommentsArrayOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts deleted file mode 100644 index bad427de9747..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { CreateComment, CreateCommentsArray } from '.'; - -export const getCreateCommentsMock = (): CreateComment => ({ - comment: 'some comments', -}); - -export const getCreateCommentsArrayMock = (): CreateCommentsArray => [getCreateCommentsMock()]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts deleted file mode 100644 index c537e9e28091..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getCreateCommentsArrayMock, getCreateCommentsMock } from './index.mock'; -import { - CreateComment, - createComment, - CreateCommentsArray, - createCommentsArray, - CreateCommentsArrayOrUndefined, - createCommentsArrayOrUndefined, -} from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('CreateComment', () => { - describe('createComment', () => { - test('it passes validation with a default comment', () => { - const payload = getCreateCommentsMock(); - const decoded = createComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = createComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "{| comment: NonEmptyString |}"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when "comment" is not a string', () => { - const payload: Omit & { comment: string[] } = { - ...getCreateCommentsMock(), - comment: ['some value'], - }; - const decoded = createComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "comment"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: CreateComment & { - extraKey?: string; - } = getCreateCommentsMock(); - payload.extraKey = 'some value'; - const decoded = createComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getCreateCommentsMock()); - }); - }); - - describe('createCommentsArray', () => { - test('it passes validation an array of comments', () => { - const payload = getCreateCommentsArrayMock(); - const decoded = createCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = createCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<{| comment: NonEmptyString |}>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when array includes non comments types', () => { - const payload = [1] as unknown as CreateCommentsArray; - const decoded = createCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('createCommentsArrayOrUndefined', () => { - test('it passes validation an array of comments', () => { - const payload = getCreateCommentsArrayMock(); - const decoded = createCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation when undefined', () => { - const payload = undefined; - const decoded = createCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when array includes non comments types', () => { - const payload = [1] as unknown as CreateCommentsArrayOrUndefined; - const decoded = createCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.ts deleted file mode 100644 index f4082df289ac..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -export const createComment = t.exact( - t.type({ - comment: NonEmptyString, - }) -); - -export type CreateComment = t.TypeOf; -export const createCommentsArray = t.array(createComment); -export type CreateCommentsArray = t.TypeOf; -export type CreateComments = t.TypeOf; -export const createCommentsArrayOrUndefined = t.union([createCommentsArray, t.undefined]); -export type CreateCommentsArrayOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts deleted file mode 100644 index 697a5034cbf0..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const created_at = t.string; // TODO: Make this into an ISO Date string check diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts deleted file mode 100644 index e6f3e2f90edb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const created_by = t.string; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts deleted file mode 100644 index 4844ffe7e364..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const cursor = t.string; -export type Cursor = t.TypeOf; -export const cursorOrUndefined = t.union([cursor, t.undefined]); -export type CursorOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts deleted file mode 100644 index d0c7e3cc0447..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { CommentsArray } from '../comment'; -import { DefaultCommentsArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getCommentsArrayMock } from '../comment/index.mock'; - -describe('default_comments_array', () => { - test('it should pass validation when supplied an empty array', () => { - const payload: CommentsArray = []; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of comments', () => { - const payload: CommentsArray = getCommentsArrayMock(); - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an array of numbers', () => { - const payload = [1]; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an array of strings', () => { - const payload = ['some string']; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.ts deleted file mode 100644 index 6a89b0063351..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { comment, CommentsArray } from '../comment'; - -/** - * Types the DefaultCommentsArray as: - * - If null or undefined, then a default array of type entry will be set - */ -export const DefaultCommentsArray = new t.Type( - 'DefaultCommentsArray', - t.array(comment).is, - (input): Either => - input == null ? t.success([]) : t.array(comment).decode(input), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts deleted file mode 100644 index ce909c0314b3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { CommentsArray } from '../comment'; -import { DefaultCommentsArray } from '../default_comments_array'; -import { getCommentsArrayMock } from '../comment/index.mock'; - -describe('default_comments_array', () => { - test('it should pass validation when supplied an empty array', () => { - const payload: CommentsArray = []; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of comments', () => { - const payload: CommentsArray = getCommentsArrayMock(); - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an array of numbers', () => { - const payload = [1]; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an array of strings', () => { - const payload = ['some string']; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.ts deleted file mode 100644 index 0ed345891719..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { createComment, CreateCommentsArray } from '../create_comment'; - -/** - * Types the DefaultCreateComments as: - * - If null or undefined, then a default array of type entry will be set - */ -export const DefaultCreateCommentsArray = new t.Type< - CreateCommentsArray, - CreateCommentsArray, - unknown ->( - 'DefaultCreateComments', - t.array(createComment).is, - (input): Either => - input == null ? t.success([]) : t.array(createComment).decode(input), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.ts deleted file mode 100644 index 9b6f8df6850c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.ts +++ /dev/null @@ -1,88 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { ImportCommentsArray } from '../import_comment'; -import { DefaultImportCommentsArray } from '.'; -import { getCommentsArrayMock } from '../comment/index.mock'; -import { getCreateCommentsArrayMock } from '../create_comment/index.mock'; - -describe('default_import_comments_array', () => { - test('it should pass validation when supplied an empty array', () => { - const payload: ImportCommentsArray = []; - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of comments', () => { - const payload: ImportCommentsArray = getCommentsArrayMock(); - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of new comments', () => { - const payload: ImportCommentsArray = getCreateCommentsArrayMock(); - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of new and existing comments', () => { - const payload: ImportCommentsArray = [ - ...getCommentsArrayMock(), - ...getCreateCommentsArrayMock(), - ]; - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an array of numbers', () => { - const payload = [1]; - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "DefaultImportComments"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an array of strings', () => { - const payload = ['some string']; - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "DefaultImportComments"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultImportCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.ts deleted file mode 100644 index dc8d18e7e11e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { importComment, ImportCommentsArray } from '../import_comment'; - -/** - * Types the DefaultImportCommentsArray as: - * - If null or undefined, then a default array of type ImportCommentsArray will be set - */ -export const DefaultImportCommentsArray = new t.Type< - ImportCommentsArray, - ImportCommentsArray, - unknown ->( - 'DefaultImportComments', - t.array(importComment).is, - (input, context): Either => - input == null ? t.success([]) : t.array(importComment).validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts deleted file mode 100644 index 69cdd841c0a5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts +++ /dev/null @@ -1,62 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultNamespace } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('default_namespace', () => { - test('it should validate "single"', () => { - const payload = 'single'; - const decoded = DefaultNamespace.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate "agnostic"', () => { - const payload = 'agnostic'; - const decoded = DefaultNamespace.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it defaults to "single" if "undefined"', () => { - const payload = undefined; - const decoded = DefaultNamespace.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('single'); - }); - - test('it defaults to "single" if "null"', () => { - const payload = null; - const decoded = DefaultNamespace.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('single'); - }); - - test('it should FAIL validation if not "single" or "agnostic"', () => { - const payload = 'something else'; - const decoded = DefaultNamespace.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - `Invalid value "something else" supplied to "DefaultNamespace"`, - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.ts deleted file mode 100644 index 33f53c55b198..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -export const namespaceType = t.keyof({ agnostic: null, single: null }); -export type NamespaceType = t.TypeOf; - -/** - * Types the DefaultNamespace as: - * - If null or undefined, then a default string/enumeration of "single" will be used. - */ -export const DefaultNamespace = new t.Type( - 'DefaultNamespace', - namespaceType.is, - (input, context): Either => - input == null ? t.success('single') : namespaceType.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.test.ts deleted file mode 100644 index 359674e57041..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultNamespaceArray, DefaultNamespaceArrayType } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('default_namespace_array', () => { - test('it should validate "null" single item as an array with a "single" value', () => { - const payload: DefaultNamespaceArrayType = null; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(['single']); - }); - - test('it should FAIL validation of numeric value', () => { - const payload = 5; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultNamespaceArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate "undefined" item as an array with a "single" value', () => { - const payload: DefaultNamespaceArrayType = undefined; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(['single']); - }); - - test('it should validate "single" as an array of a "single" value', () => { - const payload: DefaultNamespaceArrayType = 'single'; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([payload]); - }); - - test('it should validate "agnostic" as an array of a "agnostic" value', () => { - const payload: DefaultNamespaceArrayType = 'agnostic'; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([payload]); - }); - - test('it should validate "single,agnostic" as an array of 2 values of ["single", "agnostic"] values', () => { - const payload: DefaultNamespaceArrayType = 'agnostic,single'; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(['agnostic', 'single']); - }); - - test('it should validate 3 elements of "single,agnostic,single" as an array of 3 values of ["single", "agnostic", "single"] values', () => { - const payload: DefaultNamespaceArrayType = 'single,agnostic,single'; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(['single', 'agnostic', 'single']); - }); - - test('it should validate 3 elements of "single,agnostic, single" as an array of 3 values of ["single", "agnostic", "single"] values when there are spaces', () => { - const payload: DefaultNamespaceArrayType = ' single, agnostic, single '; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(['single', 'agnostic', 'single']); - }); - - test('it should FAIL validation when given 3 elements of "single,agnostic,junk" since the 3rd value is junk', () => { - const payload: DefaultNamespaceArrayType = 'single,agnostic,junk'; - const decoded = DefaultNamespaceArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "junk" supplied to "DefaultNamespaceArray"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts deleted file mode 100644 index 9692b8a2783d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts +++ /dev/null @@ -1,45 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { namespaceType } from '../default_namespace'; - -export const namespaceTypeArray = t.array(namespaceType); -export type NamespaceTypeArray = t.TypeOf; - -/** - * Types the DefaultNamespaceArray as: - * - If null or undefined, then a default string array of "single" will be used. - * - If it contains a string, then it is split along the commas and puts them into an array and validates it - */ -export const DefaultNamespaceArray = new t.Type< - NamespaceTypeArray, - string | undefined | null, - unknown ->( - 'DefaultNamespaceArray', - namespaceTypeArray.is, - (input, context): Either => { - if (input == null) { - return t.success(['single']); - } else if (typeof input === 'string') { - const commaSeparatedValues = input - .trim() - .split(',') - .map((value) => value.trim()); - return namespaceTypeArray.validate(commaSeparatedValues, context); - } - return t.failure(input, context); - }, - String -); - -export type DefaultNamespaceArrayType = t.OutputOf; -export type DefaultNamespaceArrayTypeDecoded = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts deleted file mode 100644 index aaffae53ceca..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { UpdateCommentsArray } from '../update_comment'; -import { DefaultUpdateCommentsArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getUpdateCommentsArrayMock } from '../update_comment/index.mock'; - -describe('default_update_comments_array', () => { - test('it should pass validation when supplied an empty array', () => { - const payload: UpdateCommentsArray = []; - const decoded = DefaultUpdateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied an array of comments', () => { - const payload: UpdateCommentsArray = getUpdateCommentsArrayMock(); - const decoded = DefaultUpdateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an array of numbers', () => { - const payload = [1]; - const decoded = DefaultUpdateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "DefaultUpdateComments"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an array of strings', () => { - const payload = ['some string']; - const decoded = DefaultUpdateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "DefaultUpdateComments"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultUpdateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.ts deleted file mode 100644 index 47c0e562133d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { updateCommentsArray, UpdateCommentsArray } from '../update_comment'; - -/** - * Types the DefaultUpdateComments as: - * - If null or undefined, then a default array of type UpdateCommentsArray will be set - */ -export const DefaultUpdateCommentsArray = new t.Type< - UpdateCommentsArray, - UpdateCommentsArray, - unknown ->( - 'DefaultUpdateComments', - updateCommentsArray.is, - (input, context): Either => - input == null ? t.success([]) : updateCommentsArray.validate(input, context), - t.identity -); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts deleted file mode 100644 index 75fd7ac92ffc..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const description = t.string; -export type Description = t.TypeOf; -export const descriptionOrUndefined = t.union([description, t.undefined]); -export type DescriptionOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts deleted file mode 100644 index c5489a946897..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const deserializer = t.string; -export type Deserializer = t.TypeOf; -export const deserializerOrUndefined = t.union([deserializer, t.undefined]); -export type DeserializerOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.ts deleted file mode 100644 index bc091b1e33c3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EndpointEntriesArray } from '.'; -import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; -import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEndpointEntryNestedMock } from '../entry_nested/index.mock'; -import { getEndpointEntryMatchWildcardMock } from '../entry_match_wildcard/index.mock'; - -export const getEndpointEntriesArrayMock = (): EndpointEntriesArray => [ - getEndpointEntryMatchMock(), - getEndpointEntryMatchAnyMock(), - getEndpointEntryNestedMock(), - getEndpointEntryMatchWildcardMock(), -]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts deleted file mode 100644 index 574bf4276461..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts +++ /dev/null @@ -1,122 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; -import { - endpointEntriesArray, - nonEmptyEndpointEntriesArray, - NonEmptyEndpointEntriesArray, -} from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEndpointEntryNestedMock } from '../entry_nested/index.mock'; -import { getEndpointEntriesArrayMock } from './index.mock'; -import { getEntryListMock } from '../../entries_list/index.mock'; -import { getEntryExistsMock } from '../../entries_exist/index.mock'; -import { getEndpointEntryMatchWildcardMock } from '../entry_match_wildcard/index.mock'; - -describe('Endpoint', () => { - describe('entriesArray', () => { - test('it should validate an array with match entry', () => { - const payload = [getEndpointEntryMatchMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with match_any entry', () => { - const payload = [getEndpointEntryMatchAnyMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate an empty array', () => { - const payload: NonEmptyEndpointEntriesArray = []; - const decoded = nonEmptyEndpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "[]" supplied to "NonEmptyEndpointEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('type guard for nonEmptyEndpointNestedEntries should allow array of endpoint entries', () => { - const payload: NonEmptyEndpointEntriesArray = [getEndpointEntryMatchAnyMock()]; - const guarded = nonEmptyEndpointEntriesArray.is(payload); - expect(guarded).toBeTruthy(); - }); - - test('type guard for nonEmptyEndpointNestedEntries should disallow empty arrays', () => { - const payload: NonEmptyEndpointEntriesArray = []; - const guarded = nonEmptyEndpointEntriesArray.is(payload); - expect(guarded).toBeFalsy(); - }); - - test('it should NOT validate an array with exists entry', () => { - const payload = [getEntryExistsMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "exists" supplied to "type"', - 'Invalid value "undefined" supplied to "value"', - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate an array with list entry', () => { - const payload = [getEntryListMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "list" supplied to "type"', - 'Invalid value "undefined" supplied to "value"', - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate an array with nested entry', () => { - const payload = [getEndpointEntryNestedMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with wildcard entry', () => { - const payload = [getEndpointEntryMatchWildcardMock()]; - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with all types of entries', () => { - const payload = getEndpointEntriesArrayMock(); - const decoded = endpointEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.ts deleted file mode 100644 index 992237161d06..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { endpointEntryMatch } from '../entry_match'; -import { endpointEntryMatchAny } from '../entry_match_any'; -import { endpointEntryNested } from '../entry_nested'; -import { endpointEntryMatchWildcard } from '../entry_match_wildcard'; - -export const endpointEntriesArray = t.array( - t.union([ - endpointEntryMatch, - endpointEntryMatchAny, - endpointEntryMatchWildcard, - endpointEntryNested, - ]) -); -export type EndpointEntriesArray = t.TypeOf; - -/** - * Types the nonEmptyEndpointEntriesArray as: - * - An array of entries of length 1 or greater - * - */ -export const nonEmptyEndpointEntriesArray = new t.Type< - EndpointEntriesArray, - EndpointEntriesArray, - unknown ->( - 'NonEmptyEndpointEntriesArray', - (u: unknown): u is EndpointEntriesArray => endpointEntriesArray.is(u) && u.length > 0, - (input, context): Either => { - if (Array.isArray(input) && input.length === 0) { - return t.failure(input, context); - } else { - return endpointEntriesArray.validate(input, context); - } - }, - t.identity -); - -export type NonEmptyEndpointEntriesArray = t.OutputOf; -export type NonEmptyEndpointEntriesArrayDecoded = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts deleted file mode 100644 index 76305cf70c58..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EndpointEntryMatch } from '.'; -import { ENTRY_VALUE, FIELD, MATCH, OPERATOR } from '../../../constants/index.mock'; - -export const getEndpointEntryMatchMock = (): EndpointEntryMatch => ({ - field: FIELD, - operator: OPERATOR, - type: MATCH, - value: ENTRY_VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts deleted file mode 100644 index 5c20b697b3bf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts +++ /dev/null @@ -1,103 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEndpointEntryMatchMock } from './index.mock'; -import { EndpointEntryMatch, endpointEntryMatch } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchMock } from '../../entry_match/index.mock'; - -describe('endpointEntryMatch', () => { - test('it should validate an entry', () => { - const payload = getEndpointEntryMatchMock(); - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate when "operator" is "excluded"', () => { - // Use the generic entry mock so we can test operator: excluded - const payload = getEntryMatchMock(); - payload.operator = 'excluded'; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "excluded" supplied to "operator"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { field: string } = { - ...getEndpointEntryMatchMock(), - field: '', - }; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is not string', () => { - const payload: Omit & { value: string[] } = { - ...getEndpointEntryMatchMock(), - value: ['some value'], - }; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is empty string', () => { - const payload: Omit & { value: string } = { - ...getEndpointEntryMatchMock(), - value: '', - }; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "match"', () => { - const payload: Omit & { type: string } = { - ...getEndpointEntryMatchMock(), - type: 'match_any', - }; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "match_any" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EndpointEntryMatch & { - extraKey?: string; - } = getEndpointEntryMatchMock(); - payload.extraKey = 'some value'; - const decoded = endpointEntryMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.ts deleted file mode 100644 index 5ae0258ebfb7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString, operatorIncluded } from '@kbn/securitysolution-io-ts-types'; - -export const endpointEntryMatch = t.exact( - t.type({ - field: NonEmptyString, - operator: operatorIncluded, - type: t.keyof({ match: null }), - value: NonEmptyString, - }) -); -export type EndpointEntryMatch = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts deleted file mode 100644 index b3bfffd4daf9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ENTRY_VALUE, FIELD, MATCH_ANY, OPERATOR } from '../../../constants/index.mock'; -import { EndpointEntryMatchAny } from '.'; - -export const getEndpointEntryMatchAnyMock = (): EndpointEntryMatchAny => ({ - field: FIELD, - operator: OPERATOR, - type: MATCH_ANY, - value: [ENTRY_VALUE], -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts deleted file mode 100644 index e121eed769ea..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts +++ /dev/null @@ -1,101 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEndpointEntryMatchAnyMock } from './index.mock'; -import { EndpointEntryMatchAny, endpointEntryMatchAny } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchAnyMock } from '../../entry_match_any/index.mock'; - -describe('endpointEntryMatchAny', () => { - test('it should validate an entry', () => { - const payload = getEndpointEntryMatchAnyMock(); - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate when operator is "excluded"', () => { - // Use the generic entry mock so we can test operator: excluded - const payload = getEntryMatchAnyMock(); - payload.operator = 'excluded'; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "excluded" supplied to "operator"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when field is empty string', () => { - const payload: Omit & { field: string } = { - ...getEndpointEntryMatchAnyMock(), - field: '', - }; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when value is empty array', () => { - const payload: Omit & { value: string[] } = { - ...getEndpointEntryMatchAnyMock(), - value: [], - }; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "[]" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when value is not string array', () => { - const payload: Omit & { value: string } = { - ...getEndpointEntryMatchAnyMock(), - value: 'some string', - }; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "match_any"', () => { - const payload: Omit & { type: string } = { - ...getEndpointEntryMatchAnyMock(), - type: 'match', - }; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EndpointEntryMatchAny & { - extraKey?: string; - } = getEndpointEntryMatchAnyMock(); - payload.extraKey = 'some extra key'; - const decoded = endpointEntryMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchAnyMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.ts deleted file mode 100644 index d639f4481d4d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { - NonEmptyString, - nonEmptyOrNullableStringArray, - operatorIncluded, -} from '@kbn/securitysolution-io-ts-types'; - -export const endpointEntryMatchAny = t.exact( - t.type({ - field: NonEmptyString, - operator: operatorIncluded, - type: t.keyof({ match_any: null }), - value: nonEmptyOrNullableStringArray, - }) -); -export type EndpointEntryMatchAny = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts deleted file mode 100644 index f1b5c7e7421a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ENTRY_VALUE, FIELD, OPERATOR, WILDCARD } from '../../../constants/index.mock'; -import { EndpointEntryMatchWildcard } from '.'; - -export const getEndpointEntryMatchWildcardMock = (): EndpointEntryMatchWildcard => ({ - field: FIELD, - operator: OPERATOR, - type: WILDCARD, - value: ENTRY_VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts deleted file mode 100644 index 025994afcd9e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEndpointEntryMatchWildcardMock } from './index.mock'; -import { EndpointEntryMatchWildcard, endpointEntryMatchWildcard } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchWildcardMock } from '../../entry_match_wildcard/index.mock'; - -describe('endpointEntryMatchWildcard', () => { - test('it should validate an entry', () => { - const payload = getEndpointEntryMatchWildcardMock(); - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "excluded"', () => { - const payload = getEntryMatchWildcardMock(); - payload.operator = 'excluded'; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { field: string } = { - ...getEndpointEntryMatchWildcardMock(), - field: '', - }; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is not string', () => { - const payload: Omit & { value: string[] } = { - ...getEndpointEntryMatchWildcardMock(), - value: ['some value'], - }; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is empty string', () => { - const payload: Omit & { value: string } = { - ...getEndpointEntryMatchWildcardMock(), - value: '', - }; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "wildcard"', () => { - const payload: Omit & { type: string } = { - ...getEndpointEntryMatchWildcardMock(), - type: 'match', - }; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EndpointEntryMatchWildcard & { - extraKey?: string; - } = getEndpointEntryMatchWildcardMock(); - payload.extraKey = 'some value'; - const decoded = endpointEntryMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchWildcardMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.ts deleted file mode 100644 index b42f6245ea28..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { - NonEmptyString, - operatorExcluded, - operatorIncluded, -} from '@kbn/securitysolution-io-ts-types'; - -export const endpointEntryMatchWildcard = t.exact( - t.type({ - field: NonEmptyString, - operator: t.union([operatorIncluded, operatorExcluded]), - type: t.keyof({ wildcard: null }), - value: NonEmptyString, - }) -); -export type EndpointEntryMatchWildcard = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts deleted file mode 100644 index 44c5f8db5f6e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EndpointEntryNested } from '.'; -import { FIELD, NESTED } from '../../../constants/index.mock'; -import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; -import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; - -export const getEndpointEntryNestedMock = (): EndpointEntryNested => ({ - entries: [getEndpointEntryMatchMock(), getEndpointEntryMatchAnyMock()], - field: FIELD, - type: NESTED, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts deleted file mode 100644 index c062deb88af8..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts +++ /dev/null @@ -1,138 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { EndpointEntryNested, endpointEntryNested } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEndpointEntryNestedMock } from './index.mock'; -import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { - nonEmptyEndpointNestedEntriesArray, - NonEmptyEndpointNestedEntriesArray, -} from '../non_empty_nested_entries_array'; -import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; -import { getEntryExistsMock } from '../../entries_exist/index.mock'; - -describe('endpointEntryNested', () => { - test('it should validate a nested entry', () => { - const payload = getEndpointEntryNestedMock(); - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "type" is not "nested"', () => { - const payload: Omit & { type: 'match' } = { - ...getEndpointEntryNestedMock(), - type: 'match', - }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { - field: string; - } = { ...getEndpointEntryNestedMock(), field: '' }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "field" is not a string', () => { - const payload: Omit & { - field: number; - } = { ...getEndpointEntryNestedMock(), field: 1 }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "entries" is not an array', () => { - const payload: Omit & { - entries: string; - } = { ...getEndpointEntryNestedMock(), entries: 'im a string' }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "im a string" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate when "entries" contains an entry item that is type "match"', () => { - const payload = { ...getEndpointEntryNestedMock(), entries: [getEndpointEntryMatchAnyMock()] }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual({ - entries: [ - { - field: 'host.name', - operator: 'included', - type: 'match_any', - value: ['some host name'], - }, - ], - field: 'host.name', - type: 'nested', - }); - }); - - test('it should NOT validate when "entries" contains an entry item that is type "exists"', () => { - const payload = { ...getEndpointEntryNestedMock(), entries: [getEntryExistsMock()] }; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "exists" supplied to "entries,type"', - 'Invalid value "undefined" supplied to "entries,value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EndpointEntryNested & { - extraKey?: string; - } = getEndpointEntryNestedMock(); - payload.extraKey = 'some extra key'; - const decoded = endpointEntryNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEndpointEntryNestedMock()); - }); - - test('type guard for nonEmptyEndpointNestedEntries should allow array of endpoint entries', () => { - const payload: NonEmptyEndpointNestedEntriesArray = [ - getEndpointEntryMatchMock(), - getEndpointEntryMatchAnyMock(), - ]; - const guarded = nonEmptyEndpointNestedEntriesArray.is(payload); - expect(guarded).toBeTruthy(); - }); - - test('type guard for nonEmptyEndpointNestedEntries should disallow empty arrays', () => { - const payload: NonEmptyEndpointNestedEntriesArray = []; - const guarded = nonEmptyEndpointNestedEntriesArray.is(payload); - expect(guarded).toBeFalsy(); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.ts deleted file mode 100644 index 6625c1dfeaf5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { nonEmptyEndpointNestedEntriesArray } from '../non_empty_nested_entries_array'; - -export const endpointEntryNested = t.exact( - t.type({ - entries: nonEmptyEndpointNestedEntriesArray, - field: NonEmptyString, - type: t.keyof({ nested: null }), - }) -); -export type EndpointEntryNested = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts deleted file mode 100644 index fb42cc8ee468..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts +++ /dev/null @@ -1,11 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './entries'; -export * from './non_empty_nested_entries_array'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts deleted file mode 100644 index 9bcfccae97b3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts +++ /dev/null @@ -1,47 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { endpointEntryMatch } from '../entry_match'; -import { endpointEntryMatchAny } from '../entry_match_any'; - -export const endpointNestedEntriesArray = t.array( - t.union([endpointEntryMatch, endpointEntryMatchAny]) -); -export type EndpointNestedEntriesArray = t.TypeOf; - -/** - * Types the nonEmptyNestedEntriesArray as: - * - An array of entries of length 1 or greater - * - */ -export const nonEmptyEndpointNestedEntriesArray = new t.Type< - EndpointNestedEntriesArray, - EndpointNestedEntriesArray, - unknown ->( - 'NonEmptyEndpointNestedEntriesArray', - (u: unknown): u is EndpointNestedEntriesArray => endpointNestedEntriesArray.is(u) && u.length > 0, - (input, context): Either => { - if (Array.isArray(input) && input.length === 0) { - return t.failure(input, context); - } else { - return endpointNestedEntriesArray.validate(input, context); - } - }, - t.identity -); - -export type NonEmptyEndpointNestedEntriesArray = t.OutputOf< - typeof nonEmptyEndpointNestedEntriesArray ->; -export type NonEmptyEndpointNestedEntriesArrayDecoded = t.TypeOf< - typeof nonEmptyEndpointNestedEntriesArray ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.ts deleted file mode 100644 index 5b8c802c94a3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntriesArray } from '.'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; -import { getEntryListMock } from '../entries_list/index.mock'; -import { getEntryMatchMock } from '../entry_match/index.mock'; -import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEntryNestedMock } from '../entry_nested/index.mock'; - -export const getListAndNonListEntriesArrayMock = (): EntriesArray => [ - getEntryMatchMock(), - getEntryMatchAnyMock(), - getEntryListMock(), - getEntryExistsMock(), - getEntryNestedMock(), -]; - -export const getListEntriesArrayMock = (): EntriesArray => [getEntryListMock(), getEntryListMock()]; - -export const getEntriesArrayMock = (): EntriesArray => [ - getEntryMatchMock(), - getEntryMatchAnyMock(), - getEntryExistsMock(), - getEntryNestedMock(), -]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts deleted file mode 100644 index 73553be78b9a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts +++ /dev/null @@ -1,149 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryMatchMock } from '../entry_match/index.mock'; -import { entriesArray, entriesArrayOrUndefined, entry } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; -import { getEntryListMock } from '../entries_list/index.mock'; -import { getEntryNestedMock } from '../entry_nested/index.mock'; -import { getEntriesArrayMock } from './index.mock'; - -describe('Entries', () => { - describe('entry', () => { - test('it should validate a match entry', () => { - const payload = getEntryMatchMock(); - const decoded = entry.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a match_any entry', () => { - const payload = getEntryMatchAnyMock(); - const decoded = entry.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a exists entry', () => { - const payload = getEntryExistsMock(); - const decoded = entry.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a list entry', () => { - const payload = getEntryListMock(); - const decoded = entry.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation of nested entry', () => { - const payload = getEntryNestedMock(); - const decoded = entry.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "operator"', - 'Invalid value "nested" supplied to "type"', - 'Invalid value "undefined" supplied to "value"', - 'Invalid value "undefined" supplied to "list"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('entriesArray', () => { - test('it should validate an array with match entry', () => { - const payload = [getEntryMatchMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with match_any entry', () => { - const payload = [getEntryMatchAnyMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with exists entry', () => { - const payload = [getEntryExistsMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with list entry', () => { - const payload = [getEntryListMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with nested entry', () => { - const payload = [getEntryNestedMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with all types of entries', () => { - const payload = [...getEntriesArrayMock()]; - const decoded = entriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - }); - - describe('entriesArrayOrUndefined', () => { - test('it should validate undefined', () => { - const payload = undefined; - const decoded = entriesArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array with nested entry', () => { - const payload = [getEntryNestedMock()]; - const decoded = entriesArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.ts deleted file mode 100644 index f2dbbd91dfce..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { entriesExists } from '../entries_exist'; -import { entriesList } from '../entries_list'; -import { entriesMatch } from '../entry_match'; -import { entriesMatchAny } from '../entry_match_any'; -import { entriesMatchWildcard } from '../entry_match_wildcard'; -import { entriesNested } from '../entry_nested'; - -// NOTE: Type nested is not included here to denote it's non-recursive nature. -// So a nested entry is really just a collection of `Entry` types. -export const entry = t.union([ - entriesMatch, - entriesMatchAny, - entriesList, - entriesExists, - entriesMatchWildcard, -]); -export type Entry = t.TypeOf; - -export const entriesArray = t.array( - t.union([ - entriesMatch, - entriesMatchAny, - entriesList, - entriesExists, - entriesNested, - entriesMatchWildcard, - ]) -); -export type EntriesArray = t.TypeOf; - -export const entriesArrayOrUndefined = t.union([entriesArray, t.undefined]); -export type EntriesArrayOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.ts deleted file mode 100644 index 3a588ec9cc7b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryExists } from '.'; -import { EXISTS, FIELD, OPERATOR } from '../../constants/index.mock'; - -export const getEntryExistsMock = (): EntryExists => ({ - field: FIELD, - operator: OPERATOR, - type: EXISTS, -}); - -export const getEntryExistsExcludedMock = (): EntryExists => ({ - ...getEntryExistsMock(), - operator: 'excluded', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts deleted file mode 100644 index 8ebf60ebc19f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryExistsMock } from './index.mock'; -import { entriesExists, EntryExists } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('entriesExists', () => { - test('it should validate an entry', () => { - const payload = getEntryExistsMock(); - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "included"', () => { - const payload = getEntryExistsMock(); - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "excluded"', () => { - const payload = getEntryExistsMock(); - payload.operator = 'excluded'; - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { field: string } = { - ...getEntryExistsMock(), - field: '', - }; - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EntryExists & { - extraKey?: string; - } = getEntryExistsMock(); - payload.extraKey = 'some extra key'; - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryExistsMock()); - }); - - test('it should FAIL validation when "type" is not "exists"', () => { - const payload: Omit & { type: string } = { - ...getEntryExistsMock(), - type: 'match', - }; - const decoded = entriesExists.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts deleted file mode 100644 index 460030dcc951..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { listOperator as operator } from '../list_operator'; - -export const entriesExists = t.exact( - t.type({ - field: NonEmptyString, - operator, - type: t.keyof({ exists: null }), - }) -); -export type EntryExists = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts deleted file mode 100644 index 06e006ed661b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryList } from '.'; -import { FIELD, LIST, LIST_ID, OPERATOR, TYPE } from '../../constants/index.mock'; - -export const getEntryListMock = (): EntryList => ({ - field: FIELD, - list: { id: LIST_ID, type: TYPE }, - operator: OPERATOR, - type: LIST, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts deleted file mode 100644 index eb047a07f08d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts +++ /dev/null @@ -1,97 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryListMock } from './index.mock'; -import { entriesList, EntryList } from '.'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('entriesList', () => { - test('it should validate an entry', () => { - const payload = getEntryListMock(); - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when operator is "included"', () => { - const payload = getEntryListMock(); - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "excluded"', () => { - const payload = getEntryListMock(); - payload.operator = 'excluded'; - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "list" is not expected value', () => { - const payload: Omit & { list: string } = { - ...getEntryListMock(), - list: 'someListId', - }; - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "someListId" supplied to "list"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "list.id" is empty string', () => { - const payload: Omit & { list: { id: string; type: 'ip' } } = { - ...getEntryListMock(), - list: { id: '', type: 'ip' }, - }; - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "list,id"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "lists"', () => { - const payload: Omit & { type: 'match_any' } = { - ...getEntryListMock(), - type: 'match_any', - }; - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "match_any" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EntryList & { - extraKey?: string; - } = getEntryListMock(); - payload.extraKey = 'some extra key'; - const decoded = entriesList.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryListMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.ts deleted file mode 100644 index f55a3f056218..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -import { type } from '../type'; -import { listOperator as operator } from '../list_operator'; - -export const entriesList = t.exact( - t.type({ - field: NonEmptyString, - list: t.exact(t.type({ id: NonEmptyString, type })), - operator, - type: t.keyof({ list: null }), - }) -); -export type EntryList = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.ts deleted file mode 100644 index 9e09661c2945..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryMatch } from '.'; -import { ENTRY_VALUE, FIELD, MATCH, OPERATOR } from '../../constants/index.mock'; - -export const getEntryMatchMock = (): EntryMatch => ({ - field: FIELD, - operator: OPERATOR, - type: MATCH, - value: ENTRY_VALUE, -}); - -export const getEntryMatchExcludeMock = (): EntryMatch => ({ - ...getEntryMatchMock(), - operator: 'excluded', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts deleted file mode 100644 index f2f8dbb8998f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryMatchMock } from './index.mock'; -import { entriesMatch, EntryMatch } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('entriesMatch', () => { - test('it should validate an entry', () => { - const payload = getEntryMatchMock(); - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when operator is "included"', () => { - const payload = getEntryMatchMock(); - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "excluded"', () => { - const payload = getEntryMatchMock(); - payload.operator = 'excluded'; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { field: string } = { - ...getEntryMatchMock(), - field: '', - }; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is not string', () => { - const payload: Omit & { value: string[] } = { - ...getEntryMatchMock(), - value: ['some value'], - }; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is empty string', () => { - const payload: Omit & { value: string } = { - ...getEntryMatchMock(), - value: '', - }; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "match"', () => { - const payload: Omit & { type: string } = { - ...getEntryMatchMock(), - type: 'match_any', - }; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "match_any" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EntryMatch & { - extraKey?: string; - } = getEntryMatchMock(); - payload.extraKey = 'some value'; - const decoded = entriesMatch.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts deleted file mode 100644 index 17bf0ab5b89e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { listOperator as operator } from '../list_operator'; - -export const entriesMatch = t.exact( - t.type({ - field: NonEmptyString, - operator, - type: t.keyof({ match: null }), - value: NonEmptyString, - }) -); -export type EntryMatch = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.ts deleted file mode 100644 index 7a5c4c57fa32..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryMatchAny } from '.'; -import { ENTRY_VALUE, FIELD, MATCH_ANY, OPERATOR } from '../../constants/index.mock'; - -export const getEntryMatchAnyMock = (): EntryMatchAny => ({ - field: FIELD, - operator: OPERATOR, - type: MATCH_ANY, - value: [ENTRY_VALUE], -}); - -export const getEntryMatchAnyExcludeMock = (): EntryMatchAny => ({ - ...getEntryMatchAnyMock(), - operator: 'excluded', - value: [ENTRY_VALUE, 'some other host name'], -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts deleted file mode 100644 index 3e4752f39508..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts +++ /dev/null @@ -1,106 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryMatchAnyMock } from './index.mock'; -import { entriesMatchAny, EntryMatchAny } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('entriesMatchAny', () => { - test('it should validate an entry', () => { - const payload = getEntryMatchAnyMock(); - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when operator is "included"', () => { - const payload = getEntryMatchAnyMock(); - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when operator is "excluded"', () => { - const payload = getEntryMatchAnyMock(); - payload.operator = 'excluded'; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when field is empty string', () => { - const payload: Omit & { field: string } = { - ...getEntryMatchAnyMock(), - field: '', - }; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when value is empty array', () => { - const payload: Omit & { value: string[] } = { - ...getEntryMatchAnyMock(), - value: [], - }; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "[]" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when value is not string array', () => { - const payload: Omit & { value: string } = { - ...getEntryMatchAnyMock(), - value: 'some string', - }; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "match_any"', () => { - const payload: Omit & { type: string } = { - ...getEntryMatchAnyMock(), - type: 'match', - }; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EntryMatchAny & { - extraKey?: string; - } = getEntryMatchAnyMock(); - payload.extraKey = 'some extra key'; - const decoded = entriesMatchAny.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchAnyMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts deleted file mode 100644 index be08fb370abd..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NonEmptyString, nonEmptyOrNullableStringArray } from '@kbn/securitysolution-io-ts-types'; -import { listOperator as operator } from '../list_operator'; - -export const entriesMatchAny = t.exact( - t.type({ - field: NonEmptyString, - operator, - type: t.keyof({ match_any: null }), - value: nonEmptyOrNullableStringArray, - }) -); -export type EntryMatchAny = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.ts deleted file mode 100644 index 6dc33289d22d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryMatchWildcard } from '.'; -import { ENTRY_VALUE, FIELD, OPERATOR, WILDCARD } from '../../constants/index.mock'; - -export const getEntryMatchWildcardMock = (): EntryMatchWildcard => ({ - field: FIELD, - operator: OPERATOR, - type: WILDCARD, - value: ENTRY_VALUE, -}); - -export const getEntryMatchWildcardExcludeMock = (): EntryMatchWildcard => ({ - ...getEntryMatchWildcardMock(), - operator: 'excluded', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts deleted file mode 100644 index a84996a6c105..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts +++ /dev/null @@ -1,106 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryMatchWildcardMock } from './index.mock'; -import { entriesMatchWildcard, EntryMatchWildcard } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('entriesMatchWildcard', () => { - test('it should validate an entry', () => { - const payload = getEntryMatchWildcardMock(); - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when operator is "included"', () => { - const payload = getEntryMatchWildcardMock(); - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when "operator" is "excluded"', () => { - const payload = getEntryMatchWildcardMock(); - payload.operator = 'excluded'; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { field: string } = { - ...getEntryMatchWildcardMock(), - field: '', - }; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is not string', () => { - const payload: Omit & { value: string[] } = { - ...getEntryMatchWildcardMock(), - value: ['some value'], - }; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["some value"]" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "value" is empty string', () => { - const payload: Omit & { value: string } = { - ...getEntryMatchWildcardMock(), - value: '', - }; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "type" is not "wildcard"', () => { - const payload: Omit & { type: string } = { - ...getEntryMatchWildcardMock(), - type: 'match', - }; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: EntryMatchWildcard & { - extraKey?: string; - } = getEntryMatchWildcardMock(); - payload.extraKey = 'some value'; - const decoded = entriesMatchWildcard.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryMatchWildcardMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts deleted file mode 100644 index 17afe342961c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { listOperator as operator } from '../list_operator'; - -export const entriesMatchWildcard = t.exact( - t.type({ - field: NonEmptyString, - operator, - type: t.keyof({ wildcard: null }), - value: NonEmptyString, - }) -); -export type EntryMatchWildcard = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.ts deleted file mode 100644 index 34d687502e24..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EntryNested } from '.'; -import { NESTED, NESTED_FIELD } from '../../constants/index.mock'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; -import { getEntryMatchExcludeMock, getEntryMatchMock } from '../entry_match/index.mock'; -import { getEntryMatchAnyExcludeMock, getEntryMatchAnyMock } from '../entry_match_any/index.mock'; - -export const getEntryNestedMock = (): EntryNested => ({ - entries: [getEntryMatchMock(), getEntryMatchAnyMock()], - field: NESTED_FIELD, - type: NESTED, -}); - -export const getEntryNestedExcludeMock = (): EntryNested => ({ - ...getEntryNestedMock(), - entries: [getEntryMatchExcludeMock(), getEntryMatchAnyExcludeMock()], -}); - -export const getEntryNestedMixedEntries = (): EntryNested => ({ - ...getEntryNestedMock(), - entries: [getEntryMatchMock(), getEntryMatchAnyExcludeMock(), getEntryExistsMock()], -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts deleted file mode 100644 index cfd43c4c0993..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEntryNestedMock } from './index.mock'; -import { entriesNested, EntryNested } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; - -describe('entriesNested', () => { - test('it should validate a nested entry', () => { - const payload = getEntryNestedMock(); - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when "type" is not "nested"', () => { - const payload: Omit & { type: 'match' } = { - ...getEntryNestedMock(), - type: 'match', - }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "field" is empty string', () => { - const payload: Omit & { - field: string; - } = { ...getEntryNestedMock(), field: '' }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "field" is not a string', () => { - const payload: Omit & { - field: number; - } = { ...getEntryNestedMock(), field: 1 }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when "entries" is not a an array', () => { - const payload: Omit & { - entries: string; - } = { ...getEntryNestedMock(), entries: 'im a string' }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "im a string" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate when "entries" contains an entry item that is type "match"', () => { - const payload = { ...getEntryNestedMock(), entries: [getEntryMatchAnyMock()] }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual({ - entries: [ - { - field: 'host.name', - operator: 'included', - type: 'match_any', - value: ['some host name'], - }, - ], - field: 'parent.field', - type: 'nested', - }); - }); - - test('it should validate when "entries" contains an entry item that is type "exists"', () => { - const payload = { ...getEntryNestedMock(), entries: [getEntryExistsMock()] }; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual({ - entries: [ - { - field: 'host.name', - operator: 'included', - type: 'exists', - }, - ], - field: 'parent.field', - type: 'nested', - }); - }); - - test('it should strip out extra keys', () => { - const payload: EntryNested & { - extraKey?: string; - } = getEntryNestedMock(); - payload.extraKey = 'some extra key'; - const decoded = entriesNested.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getEntryNestedMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.ts deleted file mode 100644 index 8b19fee9fb5c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { nonEmptyNestedEntriesArray } from '../non_empty_nested_entries_array'; - -export const entriesNested = t.exact( - t.type({ - entries: nonEmptyNestedEntriesArray, - field: NonEmptyString, - type: t.keyof({ nested: null }), - }) -); -export type EntryNested = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts deleted file mode 100644 index 15cdd79dc2e9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExportExceptionDetails } from '.'; - -export interface ExportExceptionDetailsMock { - listCount?: number; - missingListsCount?: number; - missingLists?: Array>; - itemCount?: number; - missingItemCount?: number; - missingItems?: Array>; -} - -export const getExceptionExportDetailsMock = ( - details?: ExportExceptionDetailsMock -): ExportExceptionDetails => ({ - exported_exception_list_count: details?.listCount ?? 0, - exported_exception_list_item_count: details?.itemCount ?? 0, - missing_exception_list_item_count: details?.missingItemCount ?? 0, - missing_exception_list_items: details?.missingItems ?? [], - missing_exception_lists: details?.missingLists ?? [], - missing_exception_lists_count: details?.missingListsCount ?? 0, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts deleted file mode 100644 index c9b1a4767e57..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getExceptionExportDetailsMock } from './index.mock'; -import { exportExceptionDetailsSchema, ExportExceptionDetails } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('exportExceptionDetails', () => { - test('it should validate export meta', () => { - const payload = getExceptionExportDetailsMock(); - const decoded = exportExceptionDetailsSchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should strip out extra keys', () => { - const payload: ExportExceptionDetails & { - extraKey?: string; - } = getExceptionExportDetailsMock(); - payload.extraKey = 'some extra key'; - const decoded = exportExceptionDetailsSchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getExceptionExportDetailsMock()); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts deleted file mode 100644 index 9e4ff134d6e9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -export const exportExceptionDetails = { - exported_exception_list_count: t.number, - exported_exception_list_item_count: t.number, - missing_exception_list_item_count: t.number, - missing_exception_list_items: t.array( - t.exact( - t.type({ - item_id: NonEmptyString, - }) - ) - ), - missing_exception_lists: t.array( - t.exact( - t.type({ - list_id: NonEmptyString, - }) - ) - ), - missing_exception_lists_count: t.number, -}; - -export const exportExceptionDetailsSchema = t.exact(t.type(exportExceptionDetails)); - -export type ExportExceptionDetails = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.test.ts deleted file mode 100644 index 2c6aae8a5693..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exceptionListType, ExceptionListTypeEnum } from '.'; - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('exceptionListType', () => { - test('it should validate for "detection"', () => { - const payload = 'detection'; - const decoded = exceptionListType.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate for "rule_default"', () => { - const payload = 'rule_default'; - const decoded = exceptionListType.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate for "endpoint"', () => { - const payload = 'endpoint'; - const decoded = exceptionListType.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should contain same amount of keys as enum', () => { - // Might seem like a weird test, but its meant to - // ensure that if exceptionListType is updated, you - // also update the ExceptionListTypeEnum, a workaround - // for io-ts not yet supporting enums - // https://github.com/gcanti/io-ts/issues/67 - const keys = Object.keys(exceptionListType.keys).sort().join(',').toLowerCase(); - const enumKeys = Object.keys(ExceptionListTypeEnum).sort().join(',').toLowerCase(); - - expect(keys).toEqual(enumKeys); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.ts deleted file mode 100644 index db7633705ac5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const exceptionListType = t.keyof({ - detection: null, - rule_default: null, - endpoint: null, - endpoint_trusted_apps: null, - endpoint_events: null, - endpoint_host_isolation_exceptions: null, - endpoint_blocklists: null, -}); -export const exceptionListTypeOrUndefined = t.union([exceptionListType, t.undefined]); -export type ExceptionListType = t.TypeOf; -export type ExceptionListTypeOrUndefined = t.TypeOf; -export enum ExceptionListTypeEnum { - DETECTION = 'detection', // shared exception list type - RULE_DEFAULT = 'rule_default', // rule default, cannot be shared - ENDPOINT = 'endpoint', - ENDPOINT_TRUSTED_APPS = 'endpoint', - ENDPOINT_EVENTS = 'endpoint_events', - ENDPOINT_HOST_ISOLATION_EXCEPTIONS = 'endpoint_host_isolation_exceptions', - ENDPOINT_BLOCKLISTS = 'endpoint_blocklists', -} diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts deleted file mode 100644 index 5e124b9f923d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const exceptionListItemType = t.keyof({ simple: null }); -export const exceptionListItemTypeOrUndefined = t.union([exceptionListItemType, t.undefined]); -export type ExceptionListItemType = t.TypeOf; -export type ExceptionListItemTypeOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts deleted file mode 100644 index 4e8184d4e6ce..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { IsoDateString } from '@kbn/securitysolution-io-ts-types'; - -export const expireTime = IsoDateString; -export const expireTimeOrUndefined = t.union([expireTime, t.undefined]); -export type ExpireTimeOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts deleted file mode 100644 index f569d42c41f1..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts +++ /dev/null @@ -1,12 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const file = t.object; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts deleted file mode 100644 index 70d526eaefbe..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const filter = t.string; -export type Filter = t.TypeOf; -export const filterOrUndefined = t.union([filter, t.undefined]); -export type FilterOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts deleted file mode 100644 index c9f35b36ee57..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -export const id = NonEmptyString; -export type Id = t.TypeOf; -export const idOrUndefined = t.union([id, t.undefined]); -export type IdOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts deleted file mode 100644 index 9bdb50647abd..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const immutable = t.boolean; -export type Immutable = t.TypeOf; -export const immutableOrUndefined = t.union([immutable, t.undefined]); -export type ImmutableOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts deleted file mode 100644 index 50121086c141..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts +++ /dev/null @@ -1,136 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getCommentsArrayMock, getCommentsMock } from '../comment/index.mock'; -import { getCreateCommentsArrayMock } from '../create_comment/index.mock'; -import { - importComment, - ImportCommentsArray, - importCommentsArray, - ImportCommentsArrayOrUndefined, - importCommentsArrayOrUndefined, -} from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('ImportComment', () => { - describe('importComment', () => { - test('it passes validation with a typical comment', () => { - const payload = getCommentsMock(); - const decoded = importComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation with a new comment', () => { - const payload = { comment: 'new comment' }; - const decoded = importComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = importComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('importCommentsArray', () => { - test('it passes validation an array of Comment', () => { - const payload = getCommentsArrayMock(); - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation an array of CreateComment', () => { - const payload = getCreateCommentsArrayMock(); - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation an array of Comment and CreateComment', () => { - const payload = [...getCommentsArrayMock(), ...getCreateCommentsArrayMock()]; - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when undefined', () => { - const payload = undefined; - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it fails validation when array includes non ImportComment types', () => { - const payload = [1] as unknown as ImportCommentsArray; - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('importCommentsArrayOrUndefined', () => { - test('it passes validation an array of ImportComment', () => { - const payload = [...getCommentsArrayMock(), ...getCreateCommentsArrayMock()]; - const decoded = importCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it passes validation when undefined', () => { - const payload = undefined; - const decoded = importCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it fails validation when array includes non ImportComment types', () => { - const payload = [1] as unknown as ImportCommentsArrayOrUndefined; - const decoded = importCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.ts deleted file mode 100644 index 4511b28078bc..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { createComment } from '../create_comment'; -import { comment } from '../comment'; - -export const importComment = t.union([comment, createComment]); - -export type ImportComment = t.TypeOf; -export const importCommentsArray = t.array(importComment); -export type ImportCommentsArray = t.TypeOf; -export const importCommentsArrayOrUndefined = t.union([importCommentsArray, t.undefined]); -export type ImportCommentsArrayOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/index.ts deleted file mode 100644 index 7c40e74d8189..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const include_expired_exceptions = t.keyof({ true: null, false: null }); -export const includeExpiredExceptionsOrUndefined = t.union([ - include_expired_exceptions, - t.undefined, -]); -export type IncludeExpiredExceptionsOrUndefined = t.TypeOf< - typeof includeExpiredExceptionsOrUndefined ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts deleted file mode 100644 index b30ac02dab96..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts +++ /dev/null @@ -1,67 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './comment'; -export * from './create_comment'; -export * from './created_at'; -export * from './created_by'; -export * from './cursor'; -export * from './default_namespace'; -export * from './default_namespace_array'; -export * from './default_create_comments_array'; -export * from './default_import_comments_array'; -export * from './description'; -export * from './deserializer'; -export * from './endpoint'; -export * from './entries'; -export * from './entries_exist'; -export * from './entries_list'; -export * from './entry_match'; -export * from './entry_match_any'; -export * from './entry_match_wildcard'; -export * from './entry_nested'; -export * from './exception_export_details'; -export * from './exception_list'; -export * from './exception_list_item_type'; -export * from './expire_time'; -export * from './filter'; -export * from './id'; -export * from './immutable'; -export * from './import_comment'; -export * from './item_id'; -export * from './list_id'; -export * from './list_operator'; -export * from './list_type'; -export * from './lists'; -export * from './lists_default_array'; -export * from './max_size'; -export * from './meta'; -export * from './name'; -export * from './namespace_type'; -export * from './non_empty_entries_array'; -export * from './non_empty_nested_entries_array'; -export * from './os_type'; -export * from './page'; -export * from './per_page'; -export * from './pit'; -export * from './search'; -export * from './search_after'; -export * from './serializer'; -export * from './sort_field'; -export * from './sort_order'; -export * from './tags'; -export * from './tie_breaker_id'; -export * from './timestamp'; -export * from './total'; -export * from './type'; -export * from './underscore_version'; -export * from './update_comment'; -export * from './updated_at'; -export * from './updated_by'; -export * from './refresh'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts deleted file mode 100644 index d69ec5358400..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts +++ /dev/null @@ -1,12 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const item = t.string; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts deleted file mode 100644 index 0e4551ad5c8f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -export const item_id = NonEmptyString; -export type ItemId = t.TypeOf; -export const itemIdOrUndefined = t.union([item_id, t.undefined]); -export type ItemIdOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts deleted file mode 100644 index 88e88aa8bc3c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; - -export const list_id = NonEmptyString; -export type ListId = t.TypeOf; -export const list_idOrUndefined = t.union([list_id, t.undefined]); -export type ListIdOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts deleted file mode 100644 index 054af26b4a62..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { ListOperatorEnum as OperatorEnum, listOperator as operator } from '.'; - -describe('operator', () => { - test('it should validate for "included"', () => { - const payload = 'included'; - const decoded = operator.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate for "excluded"', () => { - const payload = 'excluded'; - const decoded = operator.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should contain same amount of keys as enum', () => { - // Might seem like a weird test, but its meant to - // ensure that if operator is updated, you - // also update the operatorEnum, a workaround - // for io-ts not yet supporting enums - // https://github.com/gcanti/io-ts/issues/67 - const keys = Object.keys(operator.keys).sort().join(',').toLowerCase(); - const enumKeys = Object.keys(OperatorEnum).sort().join(',').toLowerCase(); - - expect(keys).toEqual(enumKeys); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.ts deleted file mode 100644 index 574a64e0f032..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const listOperator = t.keyof({ excluded: null, included: null }); -export type ListOperator = t.TypeOf; -export enum ListOperatorEnum { - INCLUDED = 'included', - EXCLUDED = 'excluded', -} - -export const listOperatorType = t.keyof({ - nested: null, - match: null, - match_any: null, - wildcard: null, - exists: null, - list: null, -}); -export type ListOperatorType = t.TypeOf; -export enum ListOperatorTypeEnum { - NESTED = 'nested', - MATCH = 'match', - MATCH_ANY = 'match_any', - WILDCARD = 'wildcard', - EXISTS = 'exists', - LIST = 'list', -} diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts deleted file mode 100644 index 716d9a6b24d7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const list_type = t.keyof({ item: null, list: null }); -export type ListType = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.ts deleted file mode 100644 index c8319867b577..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { List, ListArray } from '.'; -import { ENDPOINT_LIST_ID } from '@kbn/securitysolution-list-constants'; - -export const getListMock = (): List => ({ - id: 'some_uuid', - list_id: 'list_id_single', - namespace_type: 'single', - type: 'detection', -}); - -export const getEndpointListMock = (): List => ({ - id: ENDPOINT_LIST_ID, - list_id: ENDPOINT_LIST_ID, - namespace_type: 'agnostic', - type: 'endpoint', -}); - -export const getListArrayMock = (): ListArray => [getListMock(), getEndpointListMock()]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts deleted file mode 100644 index 57c221f10384..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts +++ /dev/null @@ -1,127 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getEndpointListMock, getListArrayMock, getListMock } from './index.mock'; -import { List, list, ListArray, listArray, ListArrayOrUndefined, listArrayOrUndefined } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -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" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", 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" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", namespace_type: "agnostic" | "single" |}> | undefined)"', - 'Invalid value "[1]" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", namespace_type: "agnostic" | "single" |}> | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.ts deleted file mode 100644 index 564ce7833b0f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { exceptionListType } from '../exception_list'; -import { namespaceType } from '../default_namespace'; - -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/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.test.ts deleted file mode 100644 index fa4f22c4718e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultListArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getListArrayMock } from '../lists/index.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/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.ts deleted file mode 100644 index a014d769410e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { list, ListArray } from '../lists'; - -/** - * Types the DefaultListArray as: - * - If null or undefined, then a default array of type list will be set - */ -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/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.test.ts deleted file mode 100644 index 9ddf86818eaf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck } from '@kbn/securitysolution-io-ts-utils'; -import { maxSizeOrUndefined } from '.'; - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('maxSizeOrUndefined', () => { - test('it will validate a correct max value', () => { - const payload = 123; - const decoded = maxSizeOrUndefined.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 fail to validate a 0', () => { - const payload = 0; - const decoded = maxSizeOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it will fail to validate a -1', () => { - const payload = -1; - const decoded = maxSizeOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it will fail to validate a string', () => { - const payload = '123'; - const decoded = maxSizeOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "123" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts deleted file mode 100644 index 0c99edf69252..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; -import * as t from 'io-ts'; - -export const max_size = PositiveIntegerGreaterThanZero; -export type MaxSize = t.TypeOf; - -export const maxSizeOrUndefined = t.union([max_size, t.undefined]); -export type MaxSizeOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts deleted file mode 100644 index 07f329819fc1..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const meta = t.object; -export type Meta = t.TypeOf; -export const metaOrUndefined = t.union([meta, t.undefined]); -export type MetaOrUndefined = t.TypeOf; - -export const nullableMetaOrUndefined = t.union([metaOrUndefined, t.null]); -export type NullableMetaOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts deleted file mode 100644 index 5d4a13c06cee..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const name = t.string; -export type Name = t.TypeOf; -export const nameOrUndefined = t.union([name, t.undefined]); -export type NameOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts deleted file mode 100644 index b8d052910b86..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import { DefaultNamespace } from '../default_namespace'; - -export const namespace_type = DefaultNamespace; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts deleted file mode 100644 index 1128dd53871e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts +++ /dev/null @@ -1,132 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { EntriesArray } from '../entries'; -import { nonEmptyEntriesArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchMock } from '../entry_match/index.mock'; -import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; -import { - getEntriesArrayMock, - getListAndNonListEntriesArrayMock, - getListEntriesArrayMock, -} from '../entries/index.mock'; -import { getEntryNestedMock } from '../entry_nested/index.mock'; - -describe('non_empty_entries_array', () => { - test('it should FAIL validation when given an empty array', () => { - const payload: EntriesArray = []; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "[]" supplied to "NonEmptyEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when given "undefined"', () => { - const payload = undefined; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "NonEmptyEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when given "null"', () => { - const payload = null; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "null" supplied to "NonEmptyEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate an array of "match" entries', () => { - const payload: EntriesArray = [getEntryMatchMock(), getEntryMatchMock()]; - const decoded = nonEmptyEntriesArray.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 "match_any" entries', () => { - const payload: EntriesArray = [getEntryMatchAnyMock(), getEntryMatchAnyMock()]; - const decoded = nonEmptyEntriesArray.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 "exists" entries', () => { - const payload: EntriesArray = [getEntryExistsMock(), getEntryExistsMock()]; - const decoded = nonEmptyEntriesArray.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 "list" entries', () => { - const payload: EntriesArray = [...getListEntriesArrayMock()]; - const decoded = nonEmptyEntriesArray.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 "nested" entries', () => { - const payload: EntriesArray = [getEntryNestedMock(), getEntryNestedMock()]; - const decoded = nonEmptyEntriesArray.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 entries', () => { - const payload: EntriesArray = [...getEntriesArrayMock()]; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when given an array of entries of value list and non-value list entries', () => { - const payload: EntriesArray = [...getListAndNonListEntriesArrayMock()]; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Cannot have entry of type list and other']); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when given an array of non entries', () => { - const payload = [1]; - const decoded = nonEmptyEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "NonEmptyEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.ts deleted file mode 100644 index a5e06d5bb2c4..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { entriesArray, EntriesArray } from '../entries'; -import { entriesList } from '../entries_list'; - -/** - * Types the nonEmptyEntriesArray as: - * - An array of entries of length 1 or greater - * - */ -export const nonEmptyEntriesArray = new t.Type( - 'NonEmptyEntriesArray', - entriesArray.is, - (input, context): Either => { - if (Array.isArray(input) && input.length === 0) { - return t.failure(input, context); - } else { - if ( - Array.isArray(input) && - input.some((entry) => entriesList.is(entry)) && - input.some((entry) => !entriesList.is(entry)) - ) { - // fail when an exception item contains both a value list entry and a non-value list entry - return t.failure(input, context, 'Cannot have entry of type list and other'); - } - return entriesArray.validate(input, context); - } - }, - t.identity -); - -export type NonEmptyEntriesArray = t.OutputOf; -export type NonEmptyEntriesArrayDecoded = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts deleted file mode 100644 index afb62d1f8768..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts +++ /dev/null @@ -1,117 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { EntriesArray } from '../entries'; -import { nonEmptyNestedEntriesArray } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getEntryMatchMock } from '../entry_match/index.mock'; -import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; -import { getEntryExistsMock } from '../entries_exist/index.mock'; -import { getEntryNestedMock } from '../entry_nested/index.mock'; - -describe('non_empty_nested_entries_array', () => { - test('it should FAIL validation when given an empty array', () => { - const payload: EntriesArray = []; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "[]" supplied to "NonEmptyNestedEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when given "undefined"', () => { - const payload = undefined; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "NonEmptyNestedEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should FAIL validation when given "null"', () => { - const payload = null; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "null" supplied to "NonEmptyNestedEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate an array of "match" entries', () => { - const payload: EntriesArray = [getEntryMatchMock(), getEntryMatchMock()]; - const decoded = nonEmptyNestedEntriesArray.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 "match_any" entries', () => { - const payload: EntriesArray = [getEntryMatchAnyMock(), getEntryMatchAnyMock()]; - const decoded = nonEmptyNestedEntriesArray.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 "exists" entries', () => { - const payload: EntriesArray = [getEntryExistsMock(), getEntryExistsMock()]; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when given an array of "nested" entries', () => { - const payload: EntriesArray = [getEntryNestedMock(), getEntryNestedMock()]; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "operator"', - 'Invalid value "nested" supplied to "type"', - 'Invalid value "undefined" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate an array of entries', () => { - const payload: EntriesArray = [ - getEntryExistsMock(), - getEntryMatchAnyMock(), - getEntryMatchMock(), - ]; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should FAIL validation when given an array of non entries', () => { - const payload = [1]; - const decoded = nonEmptyNestedEntriesArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "NonEmptyNestedEntriesArray"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.ts deleted file mode 100644 index 73a00e75010f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { entriesMatch } from '../entry_match'; -import { entriesMatchAny } from '../entry_match_any'; -import { entriesExists } from '../entries_exist'; - -export const nestedEntryItem = t.union([entriesMatch, entriesMatchAny, entriesExists]); -export const nestedEntriesArray = t.array(nestedEntryItem); -export type NestedEntriesArray = t.TypeOf; - -/** - * Types the nonEmptyNestedEntriesArray as: - * - An array of entries of length 1 or greater - * - */ -export const nonEmptyNestedEntriesArray = new t.Type< - NestedEntriesArray, - NestedEntriesArray, - unknown ->( - 'NonEmptyNestedEntriesArray', - nestedEntriesArray.is, - (input, context): Either => { - if (Array.isArray(input) && input.length === 0) { - return t.failure(input, context); - } else { - return nestedEntriesArray.validate(input, context); - } - }, - t.identity -); - -export type NonEmptyNestedEntriesArray = t.OutputOf; -export type NonEmptyNestedEntriesArrayDecoded = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts deleted file mode 100644 index 566a2aa0973a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts +++ /dev/null @@ -1,47 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck } from '@kbn/securitysolution-io-ts-utils'; -import { osType, osTypeArrayOrUndefined } from '.'; - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('osType', () => { - test('it will validate a correct osType', () => { - const payload = 'windows'; - const decoded = osType.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 fail to validate an incorrect osType', () => { - const payload = 'foo'; - const decoded = osType.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "foo" supplied to ""linux" | "macos" | "windows""', - ]); - expect(message.schema).toEqual({}); - }); - - test('it will default to an empty array when osTypeArrayOrUndefined is used', () => { - const payload = undefined; - const decoded = osTypeArrayOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.ts deleted file mode 100644 index 1dfbb9687e21..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { DefaultArray } from '@kbn/securitysolution-io-ts-types'; - -export const osType = t.keyof({ - linux: null, - macos: null, - windows: null, -}); -export type OsType = t.TypeOf; - -export const osTypeArray = DefaultArray(osType); -export type OsTypeArray = t.TypeOf; - -export const osTypeArrayOrUndefined = t.union([osTypeArray, t.undefined]); -export type OsTypeArrayOrUndefined = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts deleted file mode 100644 index 58c5581cc6e2..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const page = t.number; // TODO: Change this out for PositiveNumber from siem -export type Page = t.TypeOf; - -export const pageOrUndefined = t.union([page, t.undefined]); -export type PageOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts deleted file mode 100644 index 9ab3d1dde38c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const per_page = t.number; // TODO: Change this out for PositiveNumber from siem -export type PerPage = t.TypeOf; - -export const perPageOrUndefined = t.union([per_page, t.undefined]); -export type PerPageOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts deleted file mode 100644 index 36bc95ce1786..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck } from '@kbn/securitysolution-io-ts-utils'; -import { pitOrUndefined } from '.'; - -import * as t from 'io-ts'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('pitOrUndefined', () => { - test('it will validate a correct pit', () => { - const payload = { id: '123', keepAlive: '1m' }; - const decoded = pitOrUndefined.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 validate with the value of "undefined"', () => { - const obj = t.exact( - t.type({ - pit_id: pitOrUndefined, - }) - ); - const payload: t.TypeOf = { - pit_id: undefined, - }; - const decoded = obj.decode({ - pit_id: undefined, - }); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it will validate a correct pit without having a "keepAlive"', () => { - const payload = { id: '123' }; - const decoded = pitOrUndefined.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 fail to validate an incorrect pit', () => { - const payload = 'foo'; - const decoded = pitOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "foo" supplied to "({| id: string, keepAlive: (string | undefined) |} | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts deleted file mode 100644 index 3347f986113e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const pitId = t.string; -export const pit = t.exact( - t.type({ - id: pitId, - keepAlive: t.union([t.string, t.undefined]), - }) -); -export const pitOrUndefined = t.union([pit, t.undefined]); - -export type Pit = t.TypeOf; -export type PitId = t.TypeOf; -export type PitOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts deleted file mode 100644 index faa301fd450a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const refresh = t.union([t.literal('true'), t.literal('false')]); -export const refreshWithWaitFor = t.union([ - t.literal('true'), - t.literal('false'), - t.literal('wait_for'), -]); -export type Refresh = t.TypeOf; -export type RefreshWithWaitFor = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.ts deleted file mode 100644 index 5e6b30cf720c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/** - * This makes any optional property the same as Required would but also has the - * added benefit of keeping your undefined. - * - * For example: - * type A = RequiredKeepUndefined<{ a?: undefined; b: number }>; - * - * will yield a type of: - * type A = { a: undefined; b: number; } - * @deprecated This has no replacement. We should stop using/relying on this and just remove it. - */ -export type RequiredKeepUndefined = { [K in keyof T]-?: [T[K]] } extends infer U - ? U extends Record - ? { [K in keyof U]: U[K][0] } - : never - : never; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.test.ts deleted file mode 100644 index 1224b277c852..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck } from '@kbn/securitysolution-io-ts-utils'; -import { searchOrUndefined } from '.'; - -import * as t from 'io-ts'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('search', () => { - test('it will validate a correct search', () => { - const payload = 'name:foo'; - const decoded = searchOrUndefined.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 validate with the value of "undefined"', () => { - const obj = t.exact( - t.type({ - search: searchOrUndefined, - }) - ); - const payload: t.TypeOf = { - search: undefined, - }; - const decoded = obj.decode({ - pit_id: undefined, - }); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it will fail to validate an incorrect search', () => { - const payload = ['foo']; - const decoded = searchOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "["foo"]" supplied to "(string | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts deleted file mode 100644 index 85e360b84267..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const search = t.string; -export type Search = t.TypeOf; - -export const searchOrUndefined = t.union([search, t.undefined]); -export type SearchOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.test.ts deleted file mode 100644 index d06198272792..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck } from '@kbn/securitysolution-io-ts-utils'; -import { searchAfterOrUndefined } from '.'; - -import * as t from 'io-ts'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('searchAfter', () => { - test('it will validate a correct search_after', () => { - const payload = ['test-1', 'test-2']; - const decoded = searchAfterOrUndefined.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 validate with the value of "undefined"', () => { - const obj = t.exact( - t.type({ - search_after: searchAfterOrUndefined, - }) - ); - const payload: t.TypeOf = { - search_after: undefined, - }; - const decoded = obj.decode({ - pit_id: undefined, - }); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it will fail to validate an incorrect search_after', () => { - const payload = 'foo'; - const decoded = searchAfterOrUndefined.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "foo" supplied to "(Array | undefined)"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts deleted file mode 100644 index 5cef26cbb0c4..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const search_after = t.array(t.string); -export type SearchAfter = t.TypeOf; - -export const searchAfterOrUndefined = t.union([search_after, t.undefined]); -export type SearchAfterOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts deleted file mode 100644 index 7eb585c068e2..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const serializer = t.string; -export type Serializer = t.TypeOf; -export const serializerOrUndefined = t.union([serializer, t.undefined]); -export type SerializerOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts deleted file mode 100644 index e2c61659a94e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const sort_field = t.string; -export const sortFieldOrUndefined = t.union([sort_field, t.undefined]); -export type SortFieldOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts deleted file mode 100644 index fb075ff63fee..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const sort_order = t.keyof({ asc: null, desc: null }); -export const sortOrderOrUndefined = t.union([sort_order, t.undefined]); -export type SortOrderOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts deleted file mode 100644 index ad99a1d0800f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { DefaultStringArray } from '@kbn/securitysolution-io-ts-types'; - -export const tags = DefaultStringArray; -export type Tags = t.TypeOf; -export const tagsOrUndefined = t.union([tags, t.undefined]); -export type TagsOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts deleted file mode 100644 index 0e393c7f154b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const tie_breaker_id = t.string; // TODO: Use UUID for this instead of a string for validation diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts deleted file mode 100644 index ba47dd545fbb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { IsoDateString } from '@kbn/securitysolution-io-ts-types'; - -export const timestamp = IsoDateString; -export const timestampOrUndefined = t.union([IsoDateString, t.undefined]); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts deleted file mode 100644 index f3c84417cd41..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const total = t.number; // TODO: Change this out for PositiveNumber from siem -export const totalUndefined = t.union([total, t.undefined]); -export type TotalOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts deleted file mode 100644 index 60156cda9fe6..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { Type, type } from '.'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('type', () => { - test('it will work with a given expected type', () => { - const payload: Type = 'keyword'; - const decoded = type.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 give an error if given a type that does not exist', () => { - const payload: Type | 'madeup' = 'madeup'; - const decoded = type.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "madeup" supplied to ""binary" | "boolean" | "byte" | "date" | "date_nanos" | "date_range" | "double" | "double_range" | "float" | "float_range" | "geo_point" | "geo_shape" | "half_float" | "integer" | "integer_range" | "ip" | "ip_range" | "keyword" | "long" | "long_range" | "shape" | "short" | "text""', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts deleted file mode 100644 index d617fd2cccdf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -/** - * Types of all the regular single value list items but not exception list - * or exception list types. Those types are in the list_types folder. - */ -export const type = t.keyof({ - binary: null, - boolean: null, - byte: null, - date: null, - date_nanos: null, - date_range: null, - double: null, - double_range: null, - float: null, - float_range: null, - geo_point: null, - geo_shape: null, - half_float: null, - integer: null, - integer_range: null, - ip: null, - ip_range: null, - keyword: null, - long: null, - long_range: null, - shape: null, - short: null, - text: null, -}); - -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/common/underscore_version/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/underscore_version/index.ts deleted file mode 100644 index 2e4901990fb5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/underscore_version/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const _version = t.string; -export const _versionOrUndefined = t.union([_version, t.undefined]); -export type _VersionOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.ts deleted file mode 100644 index c84db08f8c93..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { UpdateComment, UpdateCommentsArray } from '.'; -import { ID } from '../../constants/index.mock'; - -export const getUpdateCommentMock = (): UpdateComment => ({ - comment: 'some comment', - id: ID, -}); - -export const getUpdateCommentsArrayMock = (): UpdateCommentsArray => [ - getUpdateCommentMock(), - getUpdateCommentMock(), -]; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts deleted file mode 100644 index 88cdfbdd573e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts +++ /dev/null @@ -1,150 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { getUpdateCommentMock, getUpdateCommentsArrayMock } from './index.mock'; -import { - UpdateComment, - updateComment, - UpdateCommentsArray, - updateCommentsArray, - UpdateCommentsArrayOrUndefined, - updateCommentsArrayOrUndefined, -} from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -describe('UpdateComment', () => { - describe('updateComment', () => { - test('it should pass validation when supplied typical comment update', () => { - const payload = getUpdateCommentMock(); - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an undefined for "comment"', () => { - const payload = getUpdateCommentMock(); - // @ts-expect-error - delete payload.comment; - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "comment"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an empty string for "comment"', () => { - const payload = { ...getUpdateCommentMock(), comment: '' }; - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); - expect(message.schema).toEqual({}); - }); - - test('it should pass validation when supplied an undefined for "id"', () => { - const payload = getUpdateCommentMock(); - delete payload.id; - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an empty string for "id"', () => { - const payload = { ...getUpdateCommentMock(), id: '' }; - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra key passed in', () => { - const payload: UpdateComment & { - extraKey?: string; - } = { ...getUpdateCommentMock(), extraKey: 'some new value' }; - const decoded = updateComment.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getUpdateCommentMock()); - }); - }); - - describe('updateCommentsArray', () => { - test('it should pass validation when supplied an array of comments', () => { - const payload = getUpdateCommentsArrayMock(); - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when undefined', () => { - const payload = undefined; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when array includes non comments types', () => { - const payload = [1] as unknown as UpdateCommentsArray; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('updateCommentsArrayOrUndefined', () => { - test('it should pass validation when supplied an array of comments', () => { - const payload = getUpdateCommentsArrayMock(); - const decoded = updateCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should pass validation when supplied when undefined', () => { - const payload = undefined; - const decoded = updateCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when array includes non comments types', () => { - const payload = [1] as unknown as UpdateCommentsArrayOrUndefined; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts deleted file mode 100644 index 79a721c8dad5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; -import { id } from '../id'; - -export const updateComment = t.intersection([ - t.exact( - t.type({ - comment: NonEmptyString, - }) - ), - t.exact( - t.partial({ - id, - }) - ), -]); - -export type UpdateComment = t.TypeOf; -export const updateCommentsArray = t.array(updateComment); -export type UpdateCommentsArray = t.TypeOf; -export const updateCommentsArrayOrUndefined = t.union([updateCommentsArray, t.undefined]); -export type UpdateCommentsArrayOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts deleted file mode 100644 index a6c0a803e6db..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const updated_at = t.string; // TODO: Make this into an ISO Date string check diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts deleted file mode 100644 index b99396254c91..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -export const updated_by = t.string; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts deleted file mode 100644 index cad092aee4b7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts +++ /dev/null @@ -1,13 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const value = t.string; -export const valueOrUndefined = t.union([value, t.undefined]); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts deleted file mode 100644 index 4d09fc1efbeb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts +++ /dev/null @@ -1,115 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { EndpointEntriesArray } from '../common/endpoint/entries'; -import { EntriesArray, Entry } from '../common/entries'; -import { EntryMatch } from '../common/entry_match'; -import { EntryNested } from '../common/entry_nested'; -import { OsTypeArray } from '../common/os_type'; - -export const DATE_NOW = '2020-04-20T15:25:31.830Z'; -export const OLD_DATE_RELATIVE_TO_DATE_NOW = '2020-04-19T15:25:31.830Z'; -export const USER = 'some user'; -export const ELASTIC_USER = 'elastic'; -export const LIST_INDEX = '.lists'; -export const LIST_ITEM_INDEX = '.items'; -export const NAME = 'some name'; -export const DESCRIPTION = 'some description'; -export const LIST_ID = 'some-list-id'; -export const LIST_ITEM_ID = 'some-list-item-id'; -export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; -export const TIE_BREAKERS = [ - '21530991-4051-46ec-bc35-2afa09a1b0b5', - '3c662054-ae37-4aa9-9936-3e8e2ea26775', - '60e49a20-3a23-48b6-8bf9-ed5e3b70f7a0', - '38814080-a40f-4358-992a-3b875f9b7dec', - '29fa61be-aaaf-411c-a78a-7059e3f723f1', - '9c19c959-cb9d-4cd2-99e4-1ea2baf0ef0e', - 'd409308c-f94b-4b3a-8234-bbd7a80c9140', - '87824c99-cd83-45c4-8aa6-4ad95dfea62c', - '7b940c17-9355-479f-b882-f3e575718f79', - '5983ad0c-4ef4-4fa0-8308-80ab9ecc4f74', -]; -export const META = {}; -export const TYPE = 'ip'; -export const VALUE = '127.0.0.1'; -export const VALUE_2 = '255.255.255'; -export const NAMESPACE_TYPE = 'single'; -export const NESTED_FIELD = 'parent.field'; - -// Exception List specific -export const ID = 'uuid_here'; -export const ITEM_ID = 'some-list-item-id'; -export const DETECTION_TYPE = 'detection'; -export const ENDPOINT_TYPE = 'endpoint'; -export const FIELD = 'host.name'; -export const OPERATOR = 'included'; -export const OPERATOR_EXCLUDED = 'excluded'; -export const ENTRY_VALUE = 'some host name'; -export const MATCH = 'match'; -export const MATCH_ANY = 'match_any'; -export const WILDCARD = 'wildcard'; -export const MAX_IMPORT_PAYLOAD_BYTES = 9000000; -export const IMPORT_BUFFER_SIZE = 1000; -export const LIST = 'list'; -export const EXISTS = 'exists'; -export const NESTED = 'nested'; -export const ENTRIES: EntriesArray = [ - { - entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], - field: 'some.parentField', - type: 'nested', - }, - { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, -]; -export const ENDPOINT_ENTRIES: EndpointEntriesArray = [ - { - entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], - field: 'some.parentField', - type: 'nested', - }, - { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, -]; -// ENTRIES_WITH_IDS should only be used to mock out functionality of a collection of transforms -// that are UI specific and useful for UI concerns that are inserted between the -// API and the actual user interface. In some ways these might be viewed as -// technical debt or to compensate for the differences and preferences -// of how ReactJS might prefer data vs. how we want to model data. -export const ENTRIES_WITH_IDS: EntriesArray = [ - { - entries: [ - { - field: 'nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as EntryMatch & { id: string }, - ], - field: 'some.parentField', - id: '123', - type: 'nested', - } as EntryNested & { id: string }, - { - field: 'some.not.nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as Entry & { id: string }, -]; -export const ITEM_TYPE = 'simple'; -export const OS_TYPES: OsTypeArray = ['windows']; -export const TAGS = []; -export const COMMENTS = []; -export const FILTER = 'name:Nicolas Bourbaki'; -export const CURSOR = 'c29tZXN0cmluZ2ZvcnlvdQ=='; -export const _VERSION = 'WzI5NywxXQ=='; -export const VERSION = 1; -export const IMMUTABLE = false; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.ts deleted file mode 100644 index db83807b0271..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { CreateEndpointListItemSchema } from '.'; -import { - COMMENTS, - DESCRIPTION, - ENDPOINT_ENTRIES, - ITEM_TYPE, - META, - NAME, - OS_TYPES, - TAGS, -} from '../../constants/index.mock'; - -export const getCreateEndpointListItemSchemaMock = (): CreateEndpointListItemSchema => ({ - comments: COMMENTS, - description: DESCRIPTION, - entries: ENDPOINT_ENTRIES, - item_id: undefined, - meta: META, - name: NAME, - os_types: OS_TYPES, - tags: TAGS, - type: ITEM_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts deleted file mode 100644 index 9dc599a75ad5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts +++ /dev/null @@ -1,207 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { getCreateEndpointListItemSchemaMock } from './index.mock'; -import { CreateEndpointListItemSchema, createEndpointListItemSchema } from '.'; -import { getCreateCommentsArrayMock } from '../../common/create_comment/index.mock'; -import { getCommentsMock } from '../../common/comment/index.mock'; -import { CommentsArray } from '../../common/comment'; - -describe('create_endpoint_list_item_schema', () => { - test('it should pass validation when supplied a typical list item request not counting the auto generated uuid', () => { - const payload = getCreateEndpointListItemSchemaMock(); - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an undefined for "description"', () => { - const payload = getCreateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "name"', () => { - const payload = getCreateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "type"', () => { - const payload = getCreateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied a "list_id" since it does not required one', () => { - const inputPayload: CreateEndpointListItemSchema & { list_id: string } = { - ...getCreateEndpointListItemSchemaMock(), - list_id: 'list-123', - }; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied a "namespace_type" since it does not required one', () => { - const inputPayload: CreateEndpointListItemSchema & { namespace_type: string } = { - ...getCreateEndpointListItemSchemaMock(), - namespace_type: 'single', - }; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "namespace_type"']); - expect(message.schema).toEqual({}); - }); - - test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { - const payload = getCreateEndpointListItemSchemaMock(); - const outputPayload = getCreateEndpointListItemSchemaMock(); - delete payload.meta; - delete outputPayload.meta; - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { - const inputPayload = getCreateEndpointListItemSchemaMock(); - const outputPayload = getCreateEndpointListItemSchemaMock(); - delete inputPayload.comments; - outputPayload.comments = []; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied "comments" array', () => { - const inputPayload = { - ...getCreateEndpointListItemSchemaMock(), - comments: getCreateCommentsArrayMock(), - }; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(inputPayload); - }); - - test('it should fail validation when supplied "comments" with "created_at", "created_by", or "id" values', () => { - const inputPayload: Omit & { - comments?: CommentsArray; - } = { - ...getCreateEndpointListItemSchemaMock(), - comments: [getCommentsMock()], - }; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "entries"', () => { - const inputPayload = getCreateEndpointListItemSchemaMock(); - const outputPayload = getCreateEndpointListItemSchemaMock(); - // @ts-expect-error - delete inputPayload.entries; - outputPayload.entries = []; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { - const inputPayload = getCreateEndpointListItemSchemaMock(); - const outputPayload = getCreateEndpointListItemSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { - const inputPayload = getCreateEndpointListItemSchemaMock(); - delete inputPayload.item_id; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect((message.schema as CreateEndpointListItemSchema).item_id).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 - ); - }); - - test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { - const inputPayload = getCreateEndpointListItemSchemaMock(); - delete inputPayload.item_id; - const decoded = createEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateEndpointListItemSchema).item_id; - expect(message.schema).toEqual(inputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: CreateEndpointListItemSchema & { - extraKey: string; - } = { ...getCreateEndpointListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = createEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts deleted file mode 100644 index f8e3965df733..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts +++ /dev/null @@ -1,59 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; -import { nonEmptyEndpointEntriesArray } from '../../common/endpoint/entries'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { DefaultCreateCommentsArray } from '../../common/default_create_comments_array'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { CreateCommentsArray } from '../../common/create_comment'; -import { Tags } from '../../common/tags'; -import { ItemId } from '../../common/item_id'; -import { EntriesArray } from '../../common/entries'; -import { description } from '../../common/description'; -import { name } from '../../common/name'; -import { meta } from '../../common/meta'; -import { tags } from '../../common/tags'; - -export const createEndpointListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEndpointEntriesArray, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode - item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode - meta, // defaults to undefined if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - }) - ), -]); - -export type CreateEndpointListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type CreateEndpointListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'item_id' | 'entries' | 'comments' | 'os_types' -> & { - comments: CreateCommentsArray; - tags: Tags; - item_id: ItemId; - entries: EntriesArray; - os_types: OsTypeArray; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts deleted file mode 100644 index 23b3eb19171d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,63 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { CreateExceptionListItemSchema } from '.'; -import { - COMMENTS, - DESCRIPTION, - ENTRIES, - ITEM_ID, - ITEM_TYPE, - LIST_ID, - META, - NAME, - NAMESPACE_TYPE, - OS_TYPES, - TAGS, -} from '../../constants/index.mock'; - -export const getCreateExceptionListItemSchemaMock = (): CreateExceptionListItemSchema => ({ - comments: COMMENTS, - description: DESCRIPTION, - entries: ENTRIES, - item_id: undefined, - list_id: LIST_ID, - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: OS_TYPES, - tags: TAGS, - type: ITEM_TYPE, -}); - -/** - * Useful for end to end testing - */ -export const getCreateExceptionListItemMinimalSchemaMock = (): CreateExceptionListItemSchema => ({ - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - list_id: LIST_ID, - name: NAME, - os_types: OS_TYPES, - type: ITEM_TYPE, -}); - -/** - * Useful for end to end testing - */ -export const getCreateExceptionListItemMinimalSchemaMockWithoutId = - (): CreateExceptionListItemSchema => ({ - description: DESCRIPTION, - entries: ENTRIES, - list_id: LIST_ID, - name: NAME, - os_types: OS_TYPES, - type: ITEM_TYPE, - }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts deleted file mode 100644 index dc5dcb63cf1b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,211 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getCreateExceptionListItemSchemaMock } from './index.mock'; -import { CreateExceptionListItemSchema, createExceptionListItemSchema } from '.'; -import { getCreateCommentsArrayMock } from '../../common/create_comment/index.mock'; -import { getCommentsMock } from '../../common/comment/index.mock'; -import { CommentsArray } from '../../common/comment'; - -describe('create_exception_list_item_schema', () => { - test('it should pass validation when supplied a typical exception list item request not counting the auto generated uuid', () => { - const payload = getCreateExceptionListItemSchemaMock(); - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation when supplied an undefined for "description"', () => { - const payload = getCreateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "name"', () => { - const payload = getCreateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "type"', () => { - const payload = getCreateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "list_id"', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - // @ts-expect-error - delete inputPayload.list_id; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { - const payload = getCreateExceptionListItemSchemaMock(); - const outputPayload = getCreateExceptionListItemSchemaMock(); - delete payload.meta; - delete outputPayload.meta; - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - const outputPayload = getCreateExceptionListItemSchemaMock(); - delete inputPayload.comments; - outputPayload.comments = []; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied "comments" array', () => { - const inputPayload = { - ...getCreateExceptionListItemSchemaMock(), - comments: getCreateCommentsArrayMock(), - }; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(inputPayload); - }); - - test('it should fail validation when supplied "comments" with "created_at" or "created_by" values', () => { - const inputPayload: Omit & { - comments?: CommentsArray; - } = { - ...getCreateExceptionListItemSchemaMock(), - comments: [getCommentsMock()], - }; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when supplied an undefined for "entries"', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - const outputPayload = getCreateExceptionListItemSchemaMock(); - // @ts-expect-error - delete inputPayload.entries; - outputPayload.entries = []; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should pass validation when supplied an undefined for "namespace_type" but return enum "single" and generate a correct body not counting the auto generated uuid', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - const outputPayload = getCreateExceptionListItemSchemaMock(); - delete inputPayload.namespace_type; - outputPayload.namespace_type = 'single'; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - const outputPayload = getCreateExceptionListItemSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - delete inputPayload.item_id; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect((message.schema as CreateExceptionListItemSchema).item_id).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 - ); - }); - - test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { - const inputPayload = getCreateExceptionListItemSchemaMock(); - delete inputPayload.item_id; - const decoded = createExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListItemSchema).item_id; - expect(message.schema).toEqual(inputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: CreateExceptionListItemSchema & { - extraKey?: string; - } = getCreateExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = createExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts deleted file mode 100644 index 8445b2d03d67..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts +++ /dev/null @@ -1,68 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; - -import { DefaultCreateCommentsArray } from '../../common/default_create_comments_array'; -import { CreateCommentsArray } from '../../common/create_comment'; -import { Tags } from '../../common/tags'; -import { ItemId } from '../../common/item_id'; -import { EntriesArray } from '../../common/entries'; -import { NamespaceType } from '../../common/default_namespace'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { description } from '../../common/description'; -import { list_id } from '../../common/list_id'; -import { name } from '../../common/name'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { meta } from '../../common/meta'; -import { namespace_type } from '../../common/namespace_type'; -import { tags } from '../../common/tags'; -import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; -import { ExpireTimeOrUndefined, expireTimeOrUndefined } from '../../common'; - -export const createExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEntriesArray, - list_id, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode - expire_time: expireTimeOrUndefined, - item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - }) - ), -]); - -export type CreateExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type CreateExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' -> & { - comments: CreateCommentsArray; - expire_time: ExpireTimeOrUndefined; - tags: Tags; - item_id: ItemId; - entries: EntriesArray; - namespace_type: NamespaceType; - os_types: OsTypeArray; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.ts deleted file mode 100644 index 798d36783d7c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - DESCRIPTION, - ENDPOINT_TYPE, - LIST_ID, - META, - NAME, - NAMESPACE_TYPE, - VERSION, -} from '../../constants/index.mock'; - -import { CreateExceptionListSchema } from '.'; - -export const getCreateExceptionListSchemaMock = (): CreateExceptionListSchema => ({ - description: DESCRIPTION, - list_id: undefined, - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: [], - tags: [], - type: ENDPOINT_TYPE, - version: VERSION, -}); - -/** - * Useful for end to end testing - */ -export const getCreateExceptionListMinimalSchemaMock = (): CreateExceptionListSchema => ({ - description: DESCRIPTION, - list_id: LIST_ID, - name: NAME, - type: ENDPOINT_TYPE, -}); - -/** - * Useful for end to end testing - */ -export const getCreateExceptionListMinimalSchemaMockWithoutId = (): CreateExceptionListSchema => ({ - description: DESCRIPTION, - name: NAME, - type: ENDPOINT_TYPE, -}); - -/** - * Useful for end to end testing with detections - */ -export const getCreateExceptionListDetectionSchemaMock = (): CreateExceptionListSchema => ({ - description: DESCRIPTION, - list_id: LIST_ID, - name: NAME, - type: 'detection', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts deleted file mode 100644 index f6d164f8786b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts +++ /dev/null @@ -1,85 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { CreateExceptionListSchema, createExceptionListSchema } from '.'; -import { getCreateExceptionListSchemaMock } from './index.mock'; - -describe('create_exception_list_schema', () => { - test('it should validate a typical exception lists request and generate a correct body not counting the uuid', () => { - const payload = getCreateExceptionListSchemaMock(); - const decoded = createExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListSchema).list_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "meta" and generate a correct body not counting the uuid', () => { - const payload = getCreateExceptionListSchemaMock(); - delete payload.meta; - const decoded = createExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListSchema).list_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "tags" but return an array and generate a correct body not counting the uuid', () => { - const inputPayload = getCreateExceptionListSchemaMock(); - const outputPayload = getCreateExceptionListSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = createExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListSchema).list_id; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "list_id" and auto generate a uuid', () => { - const inputPayload = getCreateExceptionListSchemaMock(); - delete inputPayload.list_id; - const decoded = createExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect((message.schema as CreateExceptionListSchema).list_id).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 - ); - }); - - test('it should accept an undefined for "list_id" and generate a correct body not counting the uuid', () => { - const inputPayload = getCreateExceptionListSchemaMock(); - delete inputPayload.list_id; - const decoded = createExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as CreateExceptionListSchema).list_id; - expect(message.schema).toEqual(inputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: CreateExceptionListSchema & { - extraKey?: string; - } = getCreateExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = createExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.ts deleted file mode 100644 index 786e39a61864..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { - DefaultUuid, - DefaultVersionNumber, - DefaultVersionNumberDecoded, -} from '@kbn/securitysolution-io-ts-types'; - -import { exceptionListType } from '../../common/exception_list'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { Tags } from '../../common/tags'; -import { ListId } from '../../common/list_id'; -import { NamespaceType } from '../../common/default_namespace'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; -import { namespace_type } from '../../common/namespace_type'; -import { tags } from '../../common/tags'; -import { meta } from '../../common/meta'; - -export const createExceptionListSchema = t.intersection([ - t.exact( - t.type({ - description, - name, - type: exceptionListType, - }) - ), - t.exact( - t.partial({ - list_id: DefaultUuid, // defaults to a GUID (UUID v4) string if not set during decode - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - version: DefaultVersionNumber, // defaults to numerical 1 if not set during decode - }) - ), -]); - -export type CreateExceptionListSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type CreateExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'list_id' | 'namespace_type' | 'os_types' -> & { - tags: Tags; - list_id: ListId; - namespace_type: NamespaceType; - os_types: OsTypeArray; - version: DefaultVersionNumberDecoded; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts deleted file mode 100644 index ed9a77fb859a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID, LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; - -import { CreateListItemSchema } from '.'; - -export const getCreateListItemSchemaMock = (): CreateListItemSchema => ({ - id: LIST_ITEM_ID, - list_id: LIST_ID, - meta: META, - value: VALUE, -}); - -/** - * Useful for end to end testing - */ -export const getCreateMinimalListItemSchemaMock = (): CreateListItemSchema => ({ - id: LIST_ITEM_ID, - list_id: LIST_ID, - value: VALUE, -}); - -/** - * Useful for end to end testing - */ -export const getCreateMinimalListItemSchemaMockWithoutId = (): CreateListItemSchema => ({ - list_id: LIST_ID, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts deleted file mode 100644 index 3e991933b664..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts +++ /dev/null @@ -1,59 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getCreateListItemSchemaMock } from './index.mock'; -import { CreateListItemSchema, createListItemSchema } from '.'; - -describe('create_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getCreateListItemSchemaMock(); - const decoded = createListItemSchema.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 accept an undefined for an id', () => { - const payload = getCreateListItemSchemaMock(); - delete payload.id; - const decoded = createListItemSchema.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 accept an undefined for meta', () => { - const payload = getCreateListItemSchemaMock(); - delete payload.meta; - const decoded = createListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: CreateListItemSchema & { extraKey?: string } = getCreateListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = createListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.ts deleted file mode 100644 index f1b3c6586535..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { list_id } from '../../common/list_id'; -import { value } from '../../common/value'; -import { id } from '../../common/id'; -import { meta } from '../../common/meta'; -import { refreshWithWaitFor } from '../../common/refresh'; - -export const createListItemSchema = t.intersection([ - t.exact( - t.type({ - list_id, - value, - }) - ), - t.exact(t.partial({ id, meta, refresh: refreshWithWaitFor })), -]); - -export type CreateListItemSchema = t.OutputOf; -export type CreateListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.ts deleted file mode 100644 index bbdd927a58e7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DESCRIPTION, LIST_ID, META, NAME, TYPE, VERSION } from '../../constants/index.mock'; - -import { CreateListSchema } from '.'; - -export const getCreateListSchemaMock = (): CreateListSchema => ({ - description: DESCRIPTION, - deserializer: undefined, - id: LIST_ID, - meta: META, - name: NAME, - serializer: undefined, - type: TYPE, - version: VERSION, -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - */ -export const getCreateMinimalListSchemaMock = (): CreateListSchema => ({ - description: DESCRIPTION, - id: LIST_ID, - name: NAME, - type: TYPE, -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - */ -export const getCreateMinimalListSchemaMockWithoutId = (): CreateListSchema => ({ - description: DESCRIPTION, - name: NAME, - type: TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.test.ts deleted file mode 100644 index 0eb9ecd02505..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { CreateListSchema, createListSchema } from '.'; -import { getCreateListSchemaMock } from './index.mock'; - -describe('create_list_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getCreateListSchemaMock(); - const decoded = createListSchema.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 accept an undefined for an id', () => { - const payload = getCreateListSchemaMock(); - delete payload.id; - const decoded = createListSchema.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 accept an undefined for meta', () => { - const payload = getCreateListSchemaMock(); - delete payload.meta; - const decoded = createListSchema.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 accept an undefined for serializer', () => { - const payload = getCreateListSchemaMock(); - delete payload.serializer; - const decoded = createListSchema.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 accept an undefined for deserializer', () => { - const payload = getCreateListSchemaMock(); - delete payload.deserializer; - const decoded = createListSchema.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 not allow an extra key to be sent in', () => { - const payload: CreateListSchema & { extraKey?: string } = getCreateListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = createListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts deleted file mode 100644 index c6e210a999ea..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts +++ /dev/null @@ -1,47 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { - DefaultVersionNumber, - DefaultVersionNumberDecoded, -} from '@kbn/securitysolution-io-ts-types'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; -import { type } from '../../common/type'; -import { deserializer } from '../../common/deserializer'; -import { id } from '../../common/id'; -import { meta } from '../../common/meta'; -import { serializer } from '../../common/serializer'; - -export const createListSchema = t.intersection([ - t.exact( - t.type({ - description, - name, - type, - }) - ), - t.exact( - t.partial({ - deserializer, // defaults to undefined if not set during decode - id, // defaults to undefined if not set during decode - meta, // defaults to undefined if not set during decode - serializer, // defaults to undefined if not set during decode - version: DefaultVersionNumber, // defaults to a numerical 1 if not set during decode - }) - ), -]); - -export type CreateListSchema = t.OutputOf; -export type CreateListSchemaDecoded = RequiredKeepUndefined< - Omit, 'version'> -> & { version: DefaultVersionNumberDecoded }; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts deleted file mode 100644 index 1eda590adb5d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts +++ /dev/null @@ -1,127 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { CreateRuleExceptionListItemSchema, createRuleExceptionListItemSchema } from '.'; -import { CreateExceptionListItemSchema } from '../create_exception_list_item_schema'; - -const getCreateExceptionListItemSchemaMock = (): CreateExceptionListItemSchema => ({ - comments: [], - description: 'some description', - entries: [ - { - field: 'host.name', - operator: 'included', - type: 'match_any', - value: ['foo', 'bar'], - }, - ], - item_id: undefined, - list_id: 'some-list-id', - name: 'some name', - namespace_type: 'single', - os_types: [], - tags: [], - type: 'simple', -}); - -describe('createRuleExceptionListItemSchema', () => { - test('empty objects do not validate', () => { - const payload = {} as CreateRuleExceptionListItemSchema; - - const decoded = createRuleExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - 'Invalid value "undefined" supplied to "entries"', - 'Invalid value "undefined" supplied to "name"', - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('items without list_id validate', () => { - const payload: CreateRuleExceptionListItemSchema = { - description: 'Exception item for rule default exception list', - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - name: 'Sample exception item', - type: 'simple', - }; - - const decoded = createRuleExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual( - expect.objectContaining({ - comments: [], - description: 'Exception item for rule default exception list', - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - name: 'Sample exception item', - os_types: [], - tags: [], - type: 'simple', - }) - ); - }); - - test('items with list_id do not validate', () => { - const payload = - getCreateExceptionListItemSchemaMock() as unknown as CreateRuleExceptionListItemSchema; - - const decoded = createRuleExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some-list-id" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('made up parameters do not validate', () => { - const payload: Partial & { madeUp: string } = { - description: 'Exception item for rule default exception list', - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - name: 'Sample exception item', - type: 'simple', - madeUp: 'invalid value', - }; - - const decoded = createRuleExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts deleted file mode 100644 index 1e4a254f92b8..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts +++ /dev/null @@ -1,73 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; - -import { - CreateCommentsArray, - DefaultCreateCommentsArray, - description, - EntriesArray, - exceptionListItemType, - ItemId, - meta, - NamespaceType, - namespaceType, - nonEmptyEntriesArray, - OsTypeArray, - osTypeArrayOrUndefined, - Tags, - tags, - name, - ExpireTimeOrUndefined, - expireTimeOrUndefined, -} from '../../common'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; - -export const createRuleExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEntriesArray, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode - item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode - list_id: t.undefined, - meta, // defaults to undefined if not set during decode - namespace_type: namespaceType, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - expire_time: expireTimeOrUndefined, - }) - ), -]); - -export type CreateRuleExceptionListItemSchema = t.OutputOf< - typeof createRuleExceptionListItemSchema ->; - -// This type is used after a decode since some things are defaults after a decode. -export type CreateRuleExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' -> & { - comments: CreateCommentsArray; - tags: Tags; - item_id: ItemId; - entries: EntriesArray; - namespace_type: NamespaceType; - os_types: OsTypeArray; - expire_time: ExpireTimeOrUndefined; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts deleted file mode 100644 index 2f7963171197..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID } from '../../constants/index.mock'; - -import { DeleteEndpointListItemSchema } from '.'; - -export const getDeleteEndpointListItemSchemaMock = (): DeleteEndpointListItemSchema => ({ - id: ID, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.test.ts deleted file mode 100644 index d702632713a5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DeleteEndpointListItemSchema, deleteEndpointListItemSchema } from '.'; -import { getDeleteEndpointListItemSchemaMock } from './index.mock'; - -describe('delete_endpoint_list_item_schema', () => { - test('it should validate a typical endpoint list item request', () => { - const payload = getDeleteEndpointListItemSchemaMock(); - const decoded = deleteEndpointListItemSchema.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 NOT accept a value for "namespace_type" since it does not require one', () => { - const payload: DeleteEndpointListItemSchema & { - namespace_type: string; - } = { ...getDeleteEndpointListItemSchemaMock(), namespace_type: 'single' }; - // @ts-expect-error - delete payload.namespace_type; - const decoded = deleteEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getDeleteEndpointListItemSchemaMock()); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: DeleteEndpointListItemSchema & { - extraKey?: string; - } = { ...getDeleteEndpointListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = deleteEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.ts deleted file mode 100644 index f968b1410a25..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { id } from '../../common/id'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { item_id } from '../../common/item_id'; - -export const deleteEndpointListItemSchema = t.exact( - t.partial({ - id, - item_id, - }) -); - -export type DeleteEndpointListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type DeleteEndpointListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts deleted file mode 100644 index 723b5acb6620..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { DeleteExceptionListItemSchema } from '.'; - -export const getDeleteExceptionListItemSchemaMock = (): DeleteExceptionListItemSchema => ({ - id: ID, - namespace_type: NAMESPACE_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.test.ts deleted file mode 100644 index 375fc20ba4da..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DeleteExceptionListItemSchema, deleteExceptionListItemSchema } from '.'; -import { getDeleteExceptionListItemSchemaMock } from './index.mock'; - -describe('delete_exception_list_item_schema', () => { - test('it should validate a typical exception list item request', () => { - const payload = getDeleteExceptionListItemSchemaMock(); - const decoded = deleteExceptionListItemSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { - const payload = getDeleteExceptionListItemSchemaMock(); - delete payload.namespace_type; - const decoded = deleteExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getDeleteExceptionListItemSchemaMock()); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: DeleteExceptionListItemSchema & { - extraKey?: string; - } = getDeleteExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = deleteExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.ts deleted file mode 100644 index 4d961aa9e1a5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NamespaceType } from '../../common/default_namespace'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { item_id } from '../../common/item_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const deleteExceptionListItemSchema = t.exact( - t.partial({ - id, - item_id, - namespace_type, // defaults to 'single' if not set during decode - }) -); - -export type DeleteExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type DeleteExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceType; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts deleted file mode 100644 index f41f5b288004..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { DeleteExceptionListSchema } from '.'; - -export const getDeleteExceptionListSchemaMock = (): DeleteExceptionListSchema => ({ - id: ID, - namespace_type: NAMESPACE_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.test.ts deleted file mode 100644 index 5507f855d783..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DeleteExceptionListSchema, deleteExceptionListSchema } from '.'; -import { getDeleteExceptionListSchemaMock } from './index.mock'; - -describe('delete_exception_list_schema', () => { - test('it should validate a typical exception list request', () => { - const payload = getDeleteExceptionListSchemaMock(); - const decoded = deleteExceptionListSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { - const payload = getDeleteExceptionListSchemaMock(); - delete payload.namespace_type; - const decoded = deleteExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getDeleteExceptionListSchemaMock()); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: DeleteExceptionListSchema & { - extraKey?: string; - } = getDeleteExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = deleteExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.ts deleted file mode 100644 index 62855c9dc212..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NamespaceType } from '../../common/default_namespace'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const deleteExceptionListSchema = t.exact( - t.partial({ - id, - list_id, - namespace_type, // defaults to 'single' if not set during decode - }) -); - -export type DeleteExceptionListSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type DeleteExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceType; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts deleted file mode 100644 index aaa03621d676..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, LIST_ID, VALUE } from '../../constants/index.mock'; - -import { DeleteListItemSchema } from '.'; - -export const getDeleteListItemSchemaMock = (): DeleteListItemSchema => ({ - id: ID, - list_id: LIST_ID, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.ts deleted file mode 100644 index d838fbab4f16..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DeleteListItemSchema, deleteListItemSchema } from '.'; -import { getDeleteListItemSchemaMock } from './index.mock'; - -describe('delete_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getDeleteListItemSchemaMock(); - const decoded = deleteListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: DeleteListItemSchema & { - extraKey?: string; - } = { ...getDeleteListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = deleteListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.ts deleted file mode 100644 index bbf0a09a15c8..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { valueOrUndefined } from '../../common/value'; -import { refresh } from '../../common/refresh'; - -export const deleteListItemSchema = t.intersection([ - t.exact( - t.type({ - value: valueOrUndefined, - }) - ), - t.exact(t.partial({ id, list_id, refresh })), -]); - -export type DeleteListItemSchema = t.OutputOf; -export type DeleteListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts deleted file mode 100644 index 4514b70ad39f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID } from '../../constants/index.mock'; - -import { DeleteListSchema } from '.'; - -export const getDeleteListSchemaMock = (): DeleteListSchema => ({ - deleteReferences: false, - id: LIST_ID, - ignoreReferences: true, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts deleted file mode 100644 index 5de3ec2c2109..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DeleteListSchema, deleteListSchema } from '.'; -import { getDeleteListSchemaMock } from './index.mock'; - -describe('delete_list_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getDeleteListSchemaMock(); - const decoded = deleteListSchema.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 NOT accept an undefined for an id', () => { - const payload = getDeleteListSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = deleteListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: DeleteListSchema & { extraKey?: string } = getDeleteListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = deleteListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts deleted file mode 100644 index 239a4d72113d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { DefaultStringBooleanFalse } from '@kbn/securitysolution-io-ts-types'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; - -export const deleteListSchema = t.intersection([ - t.exact( - t.type({ - id, - }) - ), - t.exact( - t.partial({ - deleteReferences: DefaultStringBooleanFalse, - ignoreReferences: DefaultStringBooleanFalse, - }) - ), -]); - -export type DeleteListSchema = RequiredKeepUndefined>; -export type DeleteListSchemaEncoded = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts deleted file mode 100644 index 121ab5f0b914..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { DuplicateExceptionListQuerySchema } from '.'; - -export const getDuplicateExceptionListQuerySchemaMock = (): DuplicateExceptionListQuerySchema => ({ - list_id: LIST_ID, - namespace_type: NAMESPACE_TYPE, - include_expired_exceptions: 'true', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts deleted file mode 100644 index 244adc07a81d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts +++ /dev/null @@ -1,67 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { DuplicateExceptionListQuerySchema, duplicateExceptionListQuerySchema } from '.'; -import { getDuplicateExceptionListQuerySchemaMock } from './index.mock'; - -describe('duplicate_exceptionList_query_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getDuplicateExceptionListQuerySchemaMock(); - const decoded = duplicateExceptionListQuerySchema.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 default namespace_type to "single" if an undefined given for namespacetype', () => { - const payload = getDuplicateExceptionListQuerySchemaMock(); - delete payload.namespace_type; - const decoded = duplicateExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(message.schema).toEqual({ - include_expired_exceptions: 'true', - list_id: 'some-list-id', - namespace_type: 'single', - }); - }); - - test('it should NOT accept an undefined for an list_id', () => { - const payload = getDuplicateExceptionListQuerySchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = duplicateExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: DuplicateExceptionListQuerySchema & { - extraKey?: string; - } = getDuplicateExceptionListQuerySchemaMock(); - payload.extraKey = 'some new value'; - const decoded = duplicateExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.ts deleted file mode 100644 index b329e1244eb9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { NamespaceType } from '../../common'; - -import { includeExpiredExceptionsOrUndefined } from '../../common/include_expired_exceptions'; -import { list_id } from '../../common/list_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const duplicateExceptionListQuerySchema = t.exact( - t.type({ - list_id, - namespace_type, - include_expired_exceptions: includeExpiredExceptionsOrUndefined, - }) -); - -export type DuplicateExceptionListQuerySchema = t.OutputOf< - typeof duplicateExceptionListQuerySchema ->; - -// This type is used after a decode since some things are defaults after a decode. -export type DuplicateExceptionListQuerySchemaDecoded = Omit< - t.TypeOf, - 'namespace_type' -> & { - namespace_type: NamespaceType; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts deleted file mode 100644 index 4f34a59407ea..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { ExportExceptionListQuerySchema } from '.'; - -export const getExportExceptionListQuerySchemaMock = (): ExportExceptionListQuerySchema => ({ - id: ID, - list_id: LIST_ID, - namespace_type: NAMESPACE_TYPE, - include_expired_exceptions: 'true', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts deleted file mode 100644 index 00b41f6d70f9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { ExportExceptionListQuerySchema, exportExceptionListQuerySchema } from '.'; -import { getExportExceptionListQuerySchemaMock } from './index.mock'; - -describe('export_exception_list_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getExportExceptionListQuerySchemaMock(); - const decoded = exportExceptionListQuerySchema.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 NOT accept an undefined for an id', () => { - const payload = getExportExceptionListQuerySchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = exportExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should default namespace_type to "single" if an undefined given for namespacetype', () => { - const payload = getExportExceptionListQuerySchemaMock(); - delete payload.namespace_type; - const decoded = exportExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(message.schema).toEqual({ - id: 'uuid_here', - include_expired_exceptions: 'true', - list_id: 'some-list-id', - namespace_type: 'single', - }); - }); - - test('it should NOT accept an undefined for an list_id', () => { - const payload = getExportExceptionListQuerySchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = exportExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ExportExceptionListQuerySchema & { - extraKey?: string; - } = getExportExceptionListQuerySchemaMock(); - payload.extraKey = 'some new value'; - const decoded = exportExceptionListQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.ts deleted file mode 100644 index 3943af148b15..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { id } from '../../common/id'; -import { includeExpiredExceptionsOrUndefined } from '../../common/include_expired_exceptions'; -import { list_id } from '../../common/list_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const exportExceptionListQuerySchema = t.exact( - t.type({ - id, - list_id, - namespace_type, - include_expired_exceptions: includeExpiredExceptionsOrUndefined, - // TODO: Add file_name here with a default value - }) -); - -export type ExportExceptionListQuerySchema = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts deleted file mode 100644 index 3c66cae1fb0e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID } from '../../constants/index.mock'; - -import { ExportListItemQuerySchema } from '.'; - -export const getExportListItemQuerySchemaMock = (): ExportListItemQuerySchema => ({ - list_id: LIST_ID, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts deleted file mode 100644 index 55713e33f160..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { ExportListItemQuerySchema, exportListItemQuerySchema } from '.'; -import { getExportListItemQuerySchemaMock } from './index.mock'; - -describe('export_list_item_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getExportListItemQuerySchemaMock(); - const decoded = exportListItemQuerySchema.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 NOT accept an undefined for an id', () => { - const payload = getExportListItemQuerySchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = exportListItemQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ExportListItemQuerySchema & { - extraKey?: string; - } = getExportListItemQuerySchemaMock(); - payload.extraKey = 'some new value'; - const decoded = exportListItemQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.ts deleted file mode 100644 index 86c8318f1ad5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { list_id } from '../../common/list_id'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; - -export const exportListItemQuerySchema = t.exact( - t.type({ - list_id, - // TODO: Add file_name here with a default value - }) -); - -export type ExportListItemQuerySchema = RequiredKeepUndefined< - t.TypeOf ->; -export type ExportListItemQuerySchemaEncoded = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.ts deleted file mode 100644 index d24d31cca5d9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FILTER } from '../../constants/index.mock'; - -import { FindEndpointListItemSchema, FindEndpointListItemSchemaDecoded } from '.'; - -export const getFindEndpointListItemSchemaMock = (): FindEndpointListItemSchema => ({ - filter: FILTER, - page: '1', - per_page: '25', - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindEndpointListItemSchemaDecodedMock = (): FindEndpointListItemSchemaDecoded => ({ - filter: FILTER, - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts deleted file mode 100644 index 776cc2976868..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts +++ /dev/null @@ -1,109 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { - getFindEndpointListItemSchemaDecodedMock, - getFindEndpointListItemSchemaMock, -} from './index.mock'; -import { FindEndpointListItemSchema, findEndpointListItemSchema } from '.'; - -describe('find_endpoint_list_item_schema', () => { - test('it should validate a typical find item request', () => { - const payload = getFindEndpointListItemSchemaMock(); - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindEndpointListItemSchemaDecodedMock()); - }); - - test('it should validate and empty object since everything is optional and has defaults', () => { - const payload: FindEndpointListItemSchema = {}; - const decoded = findEndpointListItemSchema.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 validate with page missing', () => { - const payload = getFindEndpointListItemSchemaMock(); - delete payload.page; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindEndpointListItemSchemaDecodedMock(); - delete expected.page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with pre_page missing', () => { - const payload = getFindEndpointListItemSchemaMock(); - delete payload.per_page; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindEndpointListItemSchemaDecodedMock(); - delete expected.per_page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with filter missing', () => { - const payload = getFindEndpointListItemSchemaMock(); - delete payload.filter; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindEndpointListItemSchemaDecodedMock(); - delete expected.filter; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_field missing', () => { - const payload = getFindEndpointListItemSchemaMock(); - delete payload.sort_field; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindEndpointListItemSchemaDecodedMock(); - delete expected.sort_field; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_order missing', () => { - const payload = getFindEndpointListItemSchemaMock(); - delete payload.sort_order; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindEndpointListItemSchemaDecodedMock(); - delete expected.sort_order; - expect(message.schema).toEqual(expected); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FindEndpointListItemSchema & { - extraKey: string; - } = { ...getFindEndpointListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = findEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.ts deleted file mode 100644 index a76854d3b4bf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { filter } from '../../common/filter'; -import { sort_field } from '../../common/sort_field'; -import { sort_order } from '../../common/sort_order'; - -export const findEndpointListItemSchema = t.exact( - t.partial({ - filter, // defaults to undefined if not set during decode - page: StringToPositiveNumber, // defaults to undefined if not set during decode - per_page: StringToPositiveNumber, // defaults to undefined if not set during decode - sort_field, // defaults to undefined if not set during decode - sort_order, // defaults to undefined if not set during decode - }) -); - -export type FindEndpointListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type FindEndpointListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts deleted file mode 100644 index 02b89bdf4c73..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FILTER, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { FindExceptionListItemSchema, FindExceptionListItemSchemaDecoded } from '.'; - -export const getFindExceptionListItemSchemaMock = (): FindExceptionListItemSchema => ({ - filter: FILTER, - list_id: LIST_ID, - namespace_type: NAMESPACE_TYPE, - page: '1', - per_page: '25', - search: undefined, - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindExceptionListItemSchemaMultipleMock = (): FindExceptionListItemSchema => ({ - filter: 'name:Sofia Kovalevskaya,name:Hypatia,name:Sophie Germain', - list_id: 'list-1,list-2,list-3', - namespace_type: 'single,single,agnostic', - page: '1', - per_page: '25', - search: undefined, - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindExceptionListItemSchemaDecodedMock = - (): FindExceptionListItemSchemaDecoded => ({ - filter: [FILTER], - list_id: [LIST_ID], - namespace_type: [NAMESPACE_TYPE], - page: 1, - per_page: 25, - search: undefined, - sort_field: undefined, - sort_order: undefined, - }); - -export const getFindExceptionListItemSchemaDecodedMultipleMock = - (): FindExceptionListItemSchemaDecoded => ({ - filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'], - list_id: ['list-1', 'list-2', 'list-3'], - namespace_type: ['single', 'single', 'agnostic'], - page: 1, - per_page: 25, - search: undefined, - sort_field: undefined, - sort_order: undefined, - }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts deleted file mode 100644 index da9c98d48e62..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,150 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { LIST_ID } from '../../constants/index.mock'; - -import { - getFindExceptionListItemSchemaDecodedMock, - getFindExceptionListItemSchemaDecodedMultipleMock, - getFindExceptionListItemSchemaMock, - getFindExceptionListItemSchemaMultipleMock, -} from './index.mock'; -import { - FindExceptionListItemSchema, - FindExceptionListItemSchemaDecoded, - findExceptionListItemSchema, -} from '.'; - -describe('find_list_item_schema', () => { - test('it should validate a typical find item request', () => { - const payload = getFindExceptionListItemSchemaMock(); - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindExceptionListItemSchemaDecodedMock()); - }); - - test('it should validate a typical find item request with multiple input strings turned into array elements', () => { - const payload = getFindExceptionListItemSchemaMultipleMock(); - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindExceptionListItemSchemaDecodedMultipleMock()); - }); - - test('it should validate just a list_id where it decodes into an array for list_id and adds a namespace_type of "single" as an array', () => { - const payload: FindExceptionListItemSchema = { list_id: LIST_ID }; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected: FindExceptionListItemSchemaDecoded = { - filter: [], - list_id: [LIST_ID], - namespace_type: ['single'], - page: undefined, - per_page: undefined, - search: undefined, - sort_field: undefined, - sort_order: undefined, - }; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with page missing', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.page; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListItemSchemaDecodedMock(); - delete expected.page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with per_page missing', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.per_page; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListItemSchemaDecodedMock(); - delete expected.per_page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with filter missing and add filter as an empty array', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.filter; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected: FindExceptionListItemSchemaDecoded = { - ...getFindExceptionListItemSchemaDecodedMock(), - filter: [], - }; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_field missing', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.sort_field; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListItemSchemaDecodedMock(); - delete expected.sort_field; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_order missing', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.sort_order; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListItemSchemaDecodedMock(); - delete expected.sort_order; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with search missing', () => { - const payload = getFindExceptionListItemSchemaMock(); - delete payload.search; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListItemSchemaDecodedMock(); - delete expected.search; - expect(message.schema).toEqual(expected); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FindExceptionListItemSchema & { - extraKey: string; - } = { ...getFindExceptionListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = findExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.ts deleted file mode 100644 index 88258538e031..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { - EmptyStringArray, - EmptyStringArrayDecoded, - NonEmptyStringArray, - StringToPositiveNumber, -} from '@kbn/securitysolution-io-ts-types'; - -import { - DefaultNamespaceArray, - DefaultNamespaceArrayTypeDecoded, -} from '../../common/default_namespace_array'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { sort_field } from '../../common/sort_field'; -import { sort_order } from '../../common/sort_order'; -import { search } from '../../common/search'; - -export const findExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - list_id: NonEmptyStringArray, - }) - ), - t.exact( - t.partial({ - filter: EmptyStringArray, // defaults to an empty array [] if not set during decode - namespace_type: DefaultNamespaceArray, // defaults to ['single'] if not set during decode - page: StringToPositiveNumber, // defaults to undefined if not set during decode - per_page: StringToPositiveNumber, // defaults to undefined if not set during decode - search, - sort_field, // defaults to undefined if not set during decode - sort_order, // defaults to undefined if not set during decode - }) - ), -]); - -export type FindExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type FindExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' | 'filter' -> & { - filter: EmptyStringArrayDecoded; - namespace_type: DefaultNamespaceArrayTypeDecoded; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.ts deleted file mode 100644 index 0b8c9e3db9bb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FILTER, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { FindExceptionListSchema, FindExceptionListSchemaDecoded } from '.'; - -export const getFindExceptionListSchemaMock = (): FindExceptionListSchema => ({ - filter: FILTER, - namespace_type: NAMESPACE_TYPE, - page: '1', - per_page: '25', - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindExceptionListSchemaDecodedMock = (): FindExceptionListSchemaDecoded => ({ - filter: FILTER, - namespace_type: [NAMESPACE_TYPE], - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts deleted file mode 100644 index fd105d3d2f61..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts +++ /dev/null @@ -1,121 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { - getFindExceptionListSchemaDecodedMock, - getFindExceptionListSchemaMock, -} from './index.mock'; -import { - FindExceptionListSchema, - FindExceptionListSchemaDecoded, - findExceptionListSchema, -} from '.'; - -describe('find_exception_list_schema', () => { - test('it should validate a typical find item request', () => { - const payload = getFindExceptionListSchemaMock(); - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindExceptionListSchemaDecodedMock()); - }); - - test('it should validate and empty object since everything is optional and will respond only with namespace_type filled out to be "single"', () => { - const payload: FindExceptionListSchema = {}; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected: FindExceptionListSchemaDecoded = { - filter: undefined, - namespace_type: ['single'], - page: undefined, - per_page: undefined, - sort_field: undefined, - sort_order: undefined, - }; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with page missing', () => { - const payload = getFindExceptionListSchemaMock(); - delete payload.page; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListSchemaDecodedMock(); - delete expected.page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with pre_page missing', () => { - const payload = getFindExceptionListSchemaMock(); - delete payload.per_page; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListSchemaDecodedMock(); - delete expected.per_page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with filter missing', () => { - const payload = getFindExceptionListSchemaMock(); - delete payload.filter; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListSchemaDecodedMock(); - delete expected.filter; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_field missing', () => { - const payload = getFindExceptionListSchemaMock(); - delete payload.sort_field; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListSchemaDecodedMock(); - delete expected.sort_field; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_order missing', () => { - const payload = getFindExceptionListSchemaMock(); - delete payload.sort_order; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindExceptionListSchemaDecodedMock(); - delete expected.sort_order; - expect(message.schema).toEqual(expected); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FindExceptionListSchema & { - extraKey: string; - } = { ...getFindExceptionListSchemaMock(), extraKey: 'some new value' }; - const decoded = findExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.ts deleted file mode 100644 index 1e22f752d014..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; - -import { DefaultNamespaceArray, NamespaceTypeArray } from '../../common/default_namespace_array'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { filter } from '../../common/filter'; -import { sort_field } from '../../common/sort_field'; -import { sort_order } from '../../common/sort_order'; - -export const findExceptionListSchema = t.exact( - t.partial({ - filter, // defaults to undefined if not set during decode - namespace_type: DefaultNamespaceArray, // defaults to 'single' if not set during decode - page: StringToPositiveNumber, // defaults to undefined if not set during decode - per_page: StringToPositiveNumber, // defaults to undefined if not set during decode - sort_field, // defaults to undefined if not set during decode - sort_order, // defaults to undefined if not set during decode - }) -); - -export type FindExceptionListSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type FindExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceTypeArray; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.ts deleted file mode 100644 index 601406ce3e37..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { CURSOR, FILTER, LIST_ID } from '../../constants/index.mock'; - -import { FindListItemSchema, FindListItemSchemaDecoded } from '.'; - -export const getFindListItemSchemaMock = (): FindListItemSchema => ({ - cursor: CURSOR, - filter: FILTER, - list_id: LIST_ID, - page: '1', - per_page: '25', - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindListItemSchemaDecodedMock = (): FindListItemSchemaDecoded => ({ - cursor: CURSOR, - filter: FILTER, - list_id: LIST_ID, - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts deleted file mode 100644 index b80629f8546b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts +++ /dev/null @@ -1,105 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { LIST_ID } from '../../constants/index.mock'; - -import { FindListItemSchema, FindListItemSchemaDecoded, findListItemSchema } from '.'; -import { getFindListItemSchemaDecodedMock, getFindListItemSchemaMock } from './index.mock'; - -describe('find_list_item_schema', () => { - test('it should validate a typical find item request', () => { - const payload = getFindListItemSchemaMock(); - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindListItemSchemaDecodedMock()); - }); - - test('it should validate just a list_id where it decodes into an array for list_id and adds a namespace_type of "single"', () => { - const payload: FindListItemSchema = { list_id: LIST_ID }; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected: FindListItemSchemaDecoded = { - cursor: undefined, - filter: undefined, - list_id: LIST_ID, - page: undefined, - per_page: undefined, - sort_field: undefined, - sort_order: undefined, - }; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with page missing', () => { - const payload = getFindListItemSchemaMock(); - delete payload.page; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListItemSchemaDecodedMock(); - delete expected.page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with pre_page missing', () => { - const payload = getFindListItemSchemaMock(); - delete payload.per_page; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListItemSchemaDecodedMock(); - delete expected.per_page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_field missing', () => { - const payload = getFindListItemSchemaMock(); - delete payload.sort_field; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListItemSchemaDecodedMock(); - delete expected.sort_field; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_order missing', () => { - const payload = getFindListItemSchemaMock(); - delete payload.sort_order; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListItemSchemaDecodedMock(); - delete expected.sort_order; - expect(message.schema).toEqual(expected); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FindListItemSchema & { - extraKey: string; - } = { ...getFindListItemSchemaMock(), extraKey: 'some new value' }; - const decoded = findListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts deleted file mode 100644 index 4509f6bc973b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; -import { filter } from '../../common/filter'; -import { cursor } from '../../common/cursor'; -import { sort_field } from '../../common/sort_field'; -import { sort_order } from '../../common/sort_order'; -import { list_id } from '../../common/list_id'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; - -export const findListItemSchema = t.intersection([ - t.exact(t.type({ list_id })), - t.exact( - t.partial({ - cursor, // defaults to undefined if not set during decode - filter, // defaults to undefined if not set during decode - page: StringToPositiveNumber, // defaults to undefined if not set during decode - per_page: StringToPositiveNumber, // defaults to undefined if not set during decode - sort_field, // defaults to undefined if not set during decode - sort_order, // defaults to undefined if not set during decode - }) - ), -]); - -export type FindListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type FindListItemSchemaDecoded = RequiredKeepUndefined>; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.ts deleted file mode 100644 index 48c9671e4ac1..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FILTER } from '../../constants/index.mock'; - -import { FindListSchema, FindListSchemaEncoded } from '.'; - -export const getFindListSchemaMock = (): FindListSchemaEncoded => ({ - filter: FILTER, - page: '1', - per_page: '25', - sort_field: undefined, - sort_order: undefined, -}); - -export const getFindListSchemaDecodedMock = (): FindListSchema => ({ - cursor: undefined, - filter: FILTER, - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts deleted file mode 100644 index ba03ddcb8526..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts +++ /dev/null @@ -1,106 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getFindListSchemaDecodedMock, getFindListSchemaMock } from './index.mock'; -import { FindListSchemaEncoded, findListSchema } from '.'; - -describe('find_list_schema', () => { - test('it should validate a typical find item request', () => { - const payload = getFindListSchemaMock(); - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getFindListSchemaDecodedMock()); - }); - - test('it should validate and empty object since everything is optional and will respond with an empty object', () => { - const payload: FindListSchemaEncoded = {}; - const decoded = findListSchema.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 validate with page missing', () => { - const payload = getFindListSchemaMock(); - delete payload.page; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListSchemaDecodedMock(); - delete expected.page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with pre_page missing', () => { - const payload = getFindListSchemaMock(); - delete payload.per_page; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListSchemaDecodedMock(); - delete expected.per_page; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with filter missing', () => { - const payload = getFindListSchemaMock(); - delete payload.filter; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListSchemaDecodedMock(); - delete expected.filter; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_field missing', () => { - const payload = getFindListSchemaMock(); - delete payload.sort_field; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListSchemaDecodedMock(); - delete expected.sort_field; - expect(message.schema).toEqual(expected); - }); - - test('it should validate with sort_order missing', () => { - const payload = getFindListSchemaMock(); - delete payload.sort_order; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - const expected = getFindListSchemaDecodedMock(); - delete expected.sort_order; - expect(message.schema).toEqual(expected); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FindListSchemaEncoded & { - extraKey: string; - } = { ...getFindListSchemaMock(), extraKey: 'some new value' }; - const decoded = findListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts deleted file mode 100644 index 8b33ffc6a947..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; -import { cursor } from '../../common/cursor'; -import { filter } from '../../common/filter'; -import { sort_field } from '../../common/sort_field'; -import { sort_order } from '../../common/sort_order'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; - -export const findListSchema = t.exact( - t.partial({ - cursor, // defaults to undefined if not set during decode - filter, // defaults to undefined if not set during decode - page: StringToPositiveNumber, // defaults to undefined if not set during decode - per_page: StringToPositiveNumber, // defaults to undefined if not set during decode - sort_field, // defaults to undefined if not set during decode - sort_order, // defaults to undefined if not set during decode - }) -); - -export type FindListSchema = RequiredKeepUndefined>; -export type FindListSchemaEncoded = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/index.ts deleted file mode 100644 index 58c93b697a85..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { namespaceType } from '../../common/default_namespace'; -import { exceptionListItemSchema } from '../../response'; -import { createExceptionListItemSchema } from '../create_exception_list_item_schema'; - -const exceptionListId = t.type({ - exception_list_id: t.string, - namespace_type: namespaceType, -}); - -export const exceptionListIds = t.type({ - exception_list_ids: t.array(exceptionListId), - type: t.literal('exception_list_ids'), -}); - -export const exceptions = t.type({ - exceptions: t.array(t.union([exceptionListItemSchema, createExceptionListItemSchema])), - type: t.literal('exception_items'), -}); - -const optionalExceptionParams = t.exact( - t.partial({ alias: t.string, chunk_size: t.number, exclude_exceptions: t.boolean }) -); - -export const getExceptionFilterSchema = t.intersection([ - t.union([exceptions, exceptionListIds]), - optionalExceptionParams, -]); - -export type GetExceptionFilterSchema = t.TypeOf; -export type ExceptionListId = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts deleted file mode 100644 index e66b805de496..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ENTRIES } from '../../constants/index.mock'; -import { ImportExceptionListItemSchema, ImportExceptionListItemSchemaDecoded } from '.'; - -export const getImportExceptionsListItemSchemaMock = ( - itemId = 'item_id_1', - listId = 'detection_list_id' -): ImportExceptionListItemSchema => ({ - description: 'some description', - entries: ENTRIES, - item_id: itemId, - list_id: listId, - name: 'Query with a rule id', - type: 'simple', -}); - -export const getImportExceptionsListItemSchemaDecodedMock = ( - itemId = 'item_id_1', - listId = 'detection_list_id' -): ImportExceptionListItemSchemaDecoded => ({ - ...getImportExceptionsListItemSchemaMock(itemId, listId), - comments: [], - meta: undefined, - namespace_type: 'single', - os_types: [], - tags: [], - expire_time: undefined, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts deleted file mode 100644 index 58b9bce4c410..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts +++ /dev/null @@ -1,174 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { importExceptionListItemSchema, ImportExceptionListItemSchema } from '.'; -import { - getImportExceptionsListItemSchemaDecodedMock, - getImportExceptionsListItemSchemaMock, -} from './index.mock'; -import { getCommentsArrayMock } from '../../common/comment/index.mock'; - -describe('import_list_item_schema', () => { - test('it should validate a typical item request', () => { - const payload = getImportExceptionsListItemSchemaMock(); - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getImportExceptionsListItemSchemaDecodedMock()); - }); - - test('it should validate a typical item request with comments', () => { - const payload = { - ...getImportExceptionsListItemSchemaMock(), - comments: getCommentsArrayMock(), - }; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual({ - ...getImportExceptionsListItemSchemaDecodedMock(), - comments: [ - { - comment: 'some old comment', - created_at: '2020-04-20T15:25:31.830Z', - created_by: 'some user', - id: 'uuid_here', - }, - { - comment: 'some old comment', - created_at: '2020-04-20T15:25:31.830Z', - created_by: 'some user', - id: 'uuid_here', - }, - ], - }); - }); - - test('it should NOT accept an undefined for "item_id"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.item_id; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "item_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "list_id"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.list_id; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "description"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.description; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "name"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.name; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.type; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "entries"', () => { - const payload: Partial> = - getImportExceptionsListItemSchemaMock(); - delete payload.entries; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept any partial fields', () => { - const payload: ImportExceptionListItemSchema = { - ...getImportExceptionsListItemSchemaMock(), - id: '123', - namespace_type: 'single', - comments: [], - os_types: [], - tags: ['123'], - created_at: '2018-08-24T17:49:30.145142000', - created_by: 'elastic', - updated_at: '2018-08-24T17:49:30.145142000', - updated_by: 'elastic', - tie_breaker_id: '123', - _version: '3', - meta: undefined, - }; - - const decoded = importExceptionListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: ImportExceptionListItemSchema & { - extraKey?: string; - } = getImportExceptionsListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = importExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.ts deleted file mode 100644 index 9b0762005f3a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.ts +++ /dev/null @@ -1,90 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { Tags } from '../../common/tags'; -import { NamespaceType } from '../../common/default_namespace'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; -import { namespace_type } from '../../common/namespace_type'; -import { tags } from '../../common/tags'; -import { meta } from '../../common/meta'; -import { list_id } from '../../common/list_id'; -import { item_id } from '../../common/item_id'; -import { id } from '../../common/id'; -import { created_at } from '../../common/created_at'; -import { created_by } from '../../common/created_by'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; -import { _version } from '../../common/underscore_version'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; -import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { ItemId } from '../../common/item_id'; -import { EntriesArray } from '../../common/entries'; -import { DefaultImportCommentsArray } from '../../common/default_import_comments_array'; -import { ExpireTimeOrUndefined, expireTimeOrUndefined, ImportCommentsArray } from '../../common'; - -/** - * Differences from this and the createExceptionsListItemSchema are - * - item_id is required - * - id is optional (but ignored in the import code - item_id is exclusively used for imports) - * - immutable is optional but if it is any value other than false it will be rejected - * - created_at is optional (but ignored in the import code) - * - updated_at is optional (but ignored in the import code) - * - created_by is optional (but ignored in the import code) - * - updated_by is optional (but ignored in the import code) - */ -export const importExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEntriesArray, - item_id, - list_id, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - id, // defaults to undefined if not set during decode - comments: DefaultImportCommentsArray, // defaults to empty array if not set during decode - created_at, // defaults undefined if not set during decode - updated_at, // defaults undefined if not set during decode - created_by, // defaults undefined if not set during decode - updated_by, // defaults undefined if not set during decode - _version, // defaults to undefined if not set during decode - tie_breaker_id, - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - expire_time: expireTimeOrUndefined, - }) - ), -]); - -export type ImportExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type ImportExceptionListItemSchemaDecoded = Omit< - ImportExceptionListItemSchema, - 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' -> & { - comments: ImportCommentsArray; - tags: Tags; - item_id: ItemId; - entries: EntriesArray; - namespace_type: NamespaceType; - os_types: OsTypeArray; - expire_time: ExpireTimeOrUndefined; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts deleted file mode 100644 index 5bf263beb372..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ImportExceptionListSchemaDecoded, ImportExceptionsListSchema } from '.'; - -export const getImportExceptionsListSchemaMock = ( - listId = 'detection_list_id' -): ImportExceptionsListSchema => ({ - description: 'some description', - list_id: listId, - name: 'Query with a rule id', - type: 'detection', -}); - -export const getImportExceptionsListSchemaDecodedMock = ( - listId = 'detection_list_id' -): ImportExceptionListSchemaDecoded => ({ - ...getImportExceptionsListSchemaMock(listId), - immutable: false, - meta: undefined, - namespace_type: 'single', - os_types: [], - tags: [], - version: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts deleted file mode 100644 index 677e089fe1ef..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts +++ /dev/null @@ -1,133 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { importExceptionsListSchema, ImportExceptionsListSchema } from '.'; -import { - getImportExceptionsListSchemaMock, - getImportExceptionsListSchemaDecodedMock, -} from './index.mock'; - -describe('import_list_item_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getImportExceptionsListSchemaMock(); - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getImportExceptionsListSchemaDecodedMock()); - }); - - test('it should NOT accept an undefined for "list_id"', () => { - const payload: Partial> = - getImportExceptionsListSchemaMock(); - delete payload.list_id; - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "description"', () => { - const payload: Partial> = - getImportExceptionsListSchemaMock(); - delete payload.description; - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "name"', () => { - const payload: Partial> = - getImportExceptionsListSchemaMock(); - delete payload.name; - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload: Partial> = - getImportExceptionsListSchemaMock(); - delete payload.type; - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept value of "true" for "immutable"', () => { - const payload: ImportExceptionsListSchema = { - ...getImportExceptionsListSchemaMock(), - immutable: true, - }; - - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "true" supplied to "immutable"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept any partial fields', () => { - const payload: ImportExceptionsListSchema = { - ...getImportExceptionsListSchemaMock(), - namespace_type: 'single', - immutable: false, - os_types: [], - tags: ['123'], - created_at: '2018-08-24T17:49:30.145142000', - created_by: 'elastic', - updated_at: '2018-08-24T17:49:30.145142000', - updated_by: 'elastic', - version: 3, - tie_breaker_id: '123', - _version: '3', - meta: undefined, - }; - - const decoded = importExceptionsListSchema.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 not allow an extra key to be sent in', () => { - const payload: ImportExceptionsListSchema & { - extraKey?: string; - } = getImportExceptionsListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = importExceptionsListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts deleted file mode 100644 index 9c0584aa267e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts +++ /dev/null @@ -1,88 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { - DefaultVersionNumber, - DefaultVersionNumberDecoded, - OnlyFalseAllowed, -} from '@kbn/securitysolution-io-ts-types'; - -import { exceptionListType } from '../../common/exception_list'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { Tags } from '../../common/tags'; -import { ListId } from '../../common/list_id'; -import { NamespaceType } from '../../common/default_namespace'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; -import { namespace_type } from '../../common/namespace_type'; -import { tags } from '../../common/tags'; -import { meta } from '../../common/meta'; -import { list_id } from '../../common/list_id'; -import { id } from '../../common/id'; -import { created_at } from '../../common/created_at'; -import { created_by } from '../../common/created_by'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; -import { _version } from '../../common/underscore_version'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; - -/** - * Differences from this and the createExceptionsSchema are - * - list_id is required - * - id is optional (but ignored in the import code - list_id is exclusively used for imports) - * - immutable is optional but if it is any value other than false it will be rejected - * - created_at is optional (but ignored in the import code) - * - updated_at is optional (but ignored in the import code) - * - created_by is optional (but ignored in the import code) - * - updated_by is optional (but ignored in the import code) - */ -export const importExceptionsListSchema = t.intersection([ - t.exact( - t.type({ - description, - name, - type: exceptionListType, - list_id, - }) - ), - t.exact( - t.partial({ - id, // defaults to undefined if not set during decode - immutable: OnlyFalseAllowed, - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - created_at, // defaults "undefined" if not set during decode - updated_at, // defaults "undefined" if not set during decode - created_by, // defaults "undefined" if not set during decode - updated_by, // defaults "undefined" if not set during decode - _version, // defaults to undefined if not set during decode - tie_breaker_id, - version: DefaultVersionNumber, // defaults to numerical 1 if not set during decode - }) - ), -]); - -export type ImportExceptionsListSchema = t.TypeOf; - -// This type is used after a decode since some things are defaults after a decode. -export type ImportExceptionListSchemaDecoded = Omit< - ImportExceptionsListSchema, - 'tags' | 'list_id' | 'namespace_type' | 'os_types' | 'immutable' -> & { - immutable: false; - tags: Tags; - list_id: ListId; - namespace_type: NamespaceType; - os_types: OsTypeArray; - version: DefaultVersionNumberDecoded; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.ts deleted file mode 100644 index 74a2122ff1dc..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID, TYPE } from '../../constants/index.mock'; - -import { ImportListItemQuerySchema } from '.'; - -export const getImportListItemQuerySchemaMock = (): ImportListItemQuerySchema => ({ - deserializer: undefined, - list_id: LIST_ID, - serializer: undefined, - type: TYPE, - refresh: 'false', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts deleted file mode 100644 index b0ec4f10af87..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts +++ /dev/null @@ -1,90 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { ImportListItemQuerySchema, importListItemQuerySchema } from '.'; -import { getImportListItemQuerySchemaMock } from './index.mock'; - -describe('import_list_item_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getImportListItemQuerySchemaMock(); - const decoded = importListItemQuerySchema.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 accept an undefined for "list_id"', () => { - const payload = getImportListItemQuerySchemaMock(); - delete payload.list_id; - const decoded = importListItemQuerySchema.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 accept an undefined for "type"', () => { - const payload = getImportListItemQuerySchemaMock(); - delete payload.type; - const decoded = importListItemQuerySchema.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 accept an undefined for "type" and "list_id', () => { - const payload = getImportListItemQuerySchemaMock(); - delete payload.type; - delete payload.list_id; - const decoded = importListItemQuerySchema.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 accept an undefined for "serializer"', () => { - const payload = getImportListItemQuerySchemaMock(); - delete payload.serializer; - const decoded = importListItemQuerySchema.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 accept an undefined for "deserializer"', () => { - const payload = getImportListItemQuerySchemaMock(); - delete payload.deserializer; - const decoded = importListItemQuerySchema.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 not allow an extra key to be sent in', () => { - const payload: ImportListItemQuerySchema & { - extraKey?: string; - } = getImportListItemQuerySchemaMock(); - payload.extraKey = 'some new value'; - const decoded = importListItemQuerySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.ts deleted file mode 100644 index e34d94c49866..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { deserializer } from '../../common/deserializer'; -import { list_id } from '../../common/list_id'; -import { type } from '../../common/type'; -import { serializer } from '../../common/serializer'; -import { refreshWithWaitFor } from '../../common/refresh'; - -export const importListItemQuerySchema = t.exact( - t.partial({ deserializer, list_id, serializer, type, refresh: refreshWithWaitFor }) -); - -export type ImportListItemQuerySchema = RequiredKeepUndefined< - t.TypeOf ->; -export type ImportListItemQuerySchemaEncoded = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.ts deleted file mode 100644 index 15dd19d4bdef..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ImportListItemSchema } from '.'; - -export const getImportListItemSchemaMock = (): ImportListItemSchema => ({ - file: {}, -}); - -/** - * This is useful for end to end tests, it will return a buffer given a string array - * of things to import. - * @param input Array of strings of things to import - */ -export const getImportListItemAsBuffer = (input: string[]): Buffer => { - return Buffer.from(input.join('\r\n')); -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts deleted file mode 100644 index c4841f394f8d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { ImportListItemSchema, importListItemSchema } from '.'; -import { getImportListItemSchemaMock } from './index.mock'; - -describe('import_list_item_schema', () => { - test('it should validate a typical lists request', () => { - const payload = getImportListItemSchemaMock(); - const decoded = importListItemSchema.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 NOT accept an undefined for a file', () => { - const payload = getImportListItemSchemaMock(); - // @ts-expect-error - delete payload.file; - const decoded = importListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "file"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ImportListItemSchema & { - extraKey?: string; - } = getImportListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = importListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts deleted file mode 100644 index 45dbf838e587..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { file } from '../../common/file'; - -export const importListItemSchema = t.exact( - t.type({ - file, - }) -); - -export type ImportListItemSchema = RequiredKeepUndefined>; -export type ImportListItemSchemaEncoded = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/index.ts deleted file mode 100644 index 3d21a5ffdcb2..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './create_endpoint_list_item_schema'; -export * from './create_exception_list_item_schema'; -export * from './create_exception_list_schema'; -export * from './create_rule_exception_item_schema'; -export * from './create_list_item_schema'; -export * from './create_list_schema'; -export * from './delete_endpoint_list_item_schema'; -export * from './delete_exception_list_schema'; -export * from './delete_exception_list_item_schema'; -export * from './delete_list_item_schema'; -export * from './delete_list_schema'; -export * from './duplicate_exception_list_query_schema'; -export * from './export_exception_list_query_schema'; -export * from './export_list_item_query_schema'; -export * from './find_endpoint_list_item_schema'; -export * from './find_exception_list_schema'; -export * from './find_exception_list_item_schema'; -export * from './find_list_item_schema'; -export * from './find_list_schema'; -export * from './get_exception_filter_schema'; -export * from './import_list_item_query_schema'; -export * from './import_exception_list_schema'; -export * from './import_exception_item_schema'; -export * from './import_list_item_schema'; -export * from './patch_list_item_schema'; -export * from './patch_list_schema'; -export * from './read_endpoint_list_item_schema'; -export * from './read_exception_list_item_schema'; -export * from './read_exception_list_schema'; -export * from './read_list_item_schema'; -export * from './read_list_schema'; -export * from './summary_exception_list_schema'; -export * from './update_endpoint_list_item_schema'; -export * from './update_exception_list_item_schema'; -export * from './update_exception_list_schema'; -export * from './update_list_item_schema'; -export * from './update_list_schema'; - -// Internal routes -export * from './internal/create_exception_list_schema'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts deleted file mode 100644 index 4a4a090723c3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts +++ /dev/null @@ -1,70 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; - -import { ExceptionListTypeEnum } from '../../../common/exception_list'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { internalCreateExceptionListSchema } from '.'; -import { getCreateExceptionListSchemaMock } from '../../create_exception_list_schema/index.mock'; - -describe('create_exception_list_schema', () => { - test('it should accept artifact list_id', () => { - const payload = { - ...getCreateExceptionListSchemaMock(), - list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, - }; - const decoded = internalCreateExceptionListSchema.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 when invalid list_id', () => { - const payload = { - ...getCreateExceptionListSchemaMock(), - list_id: ExceptionListTypeEnum.DETECTION, - }; - const decoded = internalCreateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "detection" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - test('it should accept artifact type', () => { - const payload = { - ...getCreateExceptionListSchemaMock(), - list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, - type: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, - }; - const decoded = internalCreateExceptionListSchema.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 when invalid type', () => { - const payload = { - ...getCreateExceptionListSchemaMock(), - list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, - type: ExceptionListTypeEnum.DETECTION, - }; - const decoded = internalCreateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "detection" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts deleted file mode 100644 index 3aa11ba50050..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ENDPOINT_ARTIFACT_LIST_IDS } from '@kbn/securitysolution-list-constants'; -import * as t from 'io-ts'; - -import { - createExceptionListSchema, - CreateExceptionListSchemaDecoded, -} from '../../create_exception_list_schema'; - -export const internalCreateExceptionListSchema = t.intersection([ - t.exact( - t.type({ - type: t.keyof({ - endpoint: null, - endpoint_events: null, - endpoint_host_isolation_exceptions: null, - endpoint_blocklists: null, - }), - }) - ), - t.exact( - t.partial({ - list_id: t.keyof( - ENDPOINT_ARTIFACT_LIST_IDS.reduce>((mapOfListIds, listId) => { - mapOfListIds[listId] = null; - - return mapOfListIds; - }, {}) - ), - }) - ), - createExceptionListSchema, -]); - -export type InternalCreateExceptionListSchema = t.OutputOf< - typeof internalCreateExceptionListSchema ->; - -// This type is used after a decode since some things are defaults after a decode. -export type InternalCreateExceptionListSchemaDecoded = CreateExceptionListSchemaDecoded; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts deleted file mode 100644 index ff156386baa9..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; - -import { PatchListItemSchema } from '.'; - -export const getPathListItemSchemaMock = (): PatchListItemSchema => ({ - id: LIST_ITEM_ID, - meta: META, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts deleted file mode 100644 index fddeeaf0055c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts +++ /dev/null @@ -1,83 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getPathListItemSchemaMock } from './index.mock'; -import { PatchListItemSchema, patchListItemSchema } from '.'; - -describe('patch_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getPathListItemSchemaMock(); - const decoded = patchListItemSchema.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 NOT accept an undefined for "id"', () => { - const payload = getPathListItemSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = patchListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getPathListItemSchemaMock(); - delete payload.meta; - const decoded = patchListItemSchema.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 accept an undefined for "value"', () => { - const payload = getPathListItemSchemaMock(); - delete payload.value; - const decoded = patchListItemSchema.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 accept an undefined for "meta" and "value"', () => { - const payload = getPathListItemSchemaMock(); - delete payload.meta; - delete payload.value; - const decoded = patchListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: PatchListItemSchema & { extraKey?: string } = getPathListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = patchListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts deleted file mode 100644 index 96b50702d99b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { _version } from '../../common/underscore_version'; -import { id } from '../../common/id'; -import { meta } from '../../common/meta'; -import { value } from '../../common/value'; -import { refresh } from '../../common/refresh'; - -export const patchListItemSchema = t.intersection([ - t.exact( - t.type({ - id, - }) - ), - t.exact(t.partial({ _version, meta, value, refresh })), -]); - -export type PatchListItemSchema = t.OutputOf; -export type PatchListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts deleted file mode 100644 index 818dd4e79e98..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DESCRIPTION, LIST_ITEM_ID, META, NAME } from '../../constants/index.mock'; - -import { PatchListSchema } from '.'; - -export const getPathListSchemaMock = (): PatchListSchema => ({ - description: DESCRIPTION, - id: LIST_ITEM_ID, - meta: META, - name: NAME, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts deleted file mode 100644 index b79bfc8fddd6..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts +++ /dev/null @@ -1,131 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getPathListSchemaMock } from './index.mock'; -import { PatchListSchema, patchListSchema } from '.'; - -describe('patch_list_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getPathListSchemaMock(); - const decoded = patchListSchema.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 NOT accept an undefined for "id"', () => { - const payload = getPathListSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = patchListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getPathListSchemaMock(); - delete payload.meta; - const decoded = patchListSchema.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 accept an undefined for "name"', () => { - const payload = getPathListSchemaMock(); - delete payload.name; - const decoded = patchListSchema.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 accept an undefined for "description"', () => { - const payload = getPathListSchemaMock(); - delete payload.description; - const decoded = patchListSchema.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 accept an undefined for "description", "meta", "name', () => { - const payload = getPathListSchemaMock(); - delete payload.description; - delete payload.name; - delete payload.meta; - const decoded = patchListSchema.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 accept an undefined for "description", "meta"', () => { - const payload = getPathListSchemaMock(); - delete payload.description; - delete payload.meta; - const decoded = patchListSchema.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 accept an undefined for "description", "name"', () => { - const payload = getPathListSchemaMock(); - delete payload.description; - delete payload.name; - const decoded = patchListSchema.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 accept an undefined for "meta", "name"', () => { - const payload = getPathListSchemaMock(); - delete payload.meta; - delete payload.name; - const decoded = patchListSchema.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 not allow an extra key to be sent in', () => { - const payload: PatchListSchema & { extraKey?: string } = getPathListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = patchListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.ts deleted file mode 100644 index e5c477c84424..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { version } from '@kbn/securitysolution-io-ts-types'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { _version } from '../../common/underscore_version'; -import { meta } from '../../common/meta'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; - -export const patchListSchema = t.intersection([ - t.exact( - t.type({ - id, - }) - ), - t.exact( - t.partial({ - _version, // is undefined if not set during decode - description, // is undefined if not set during decode - meta, // is undefined if not set during decode - name, // is undefined if not set during decode - version, // is undefined if not set during decode - }) - ), -]); - -export type PatchListSchema = t.OutputOf; -export type PatchListSchemaDecoded = RequiredKeepUndefined>; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts deleted file mode 100644 index d7850f0cca32..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, ITEM_ID } from '../../constants/index.mock'; - -import { ReadEndpointListItemSchema } from '.'; - -export const getReadEndpointListItemSchemaMock = (): ReadEndpointListItemSchema => ({ - id: ID, - item_id: ITEM_ID, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.ts deleted file mode 100644 index d9de257a3130..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getReadEndpointListItemSchemaMock } from './index.mock'; -import { ReadEndpointListItemSchema, readEndpointListItemSchema } from '.'; - -describe('read_endpoint_list_item_schema', () => { - test('it should validate a typical list request', () => { - const payload = getReadEndpointListItemSchemaMock(); - const decoded = readEndpointListItemSchema.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 accept an undefined for "id"', () => { - const payload = getReadEndpointListItemSchemaMock(); - delete payload.id; - const decoded = readEndpointListItemSchema.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 accept an undefined for "item_id"', () => { - const payload = getReadEndpointListItemSchemaMock(); - delete payload.item_id; - const decoded = readEndpointListItemSchema.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 NOT accept "namespace_type" since endpoint list items do not need it', () => { - const payload: ReadEndpointListItemSchema & { - namespace_type: string; - } = { ...getReadEndpointListItemSchemaMock(), namespace_type: 'single' }; - // @ts-expect-error - delete payload.namespace_type; - const decoded = readEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getReadEndpointListItemSchemaMock()); - }); - - test('it should accept an undefined for "id", "item_id"', () => { - const payload = getReadEndpointListItemSchemaMock(); - delete payload.id; - delete payload.item_id; - const decoded = readEndpointListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: ReadEndpointListItemSchema & { - extraKey?: string; - } = getReadEndpointListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = readEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.ts deleted file mode 100644 index dbf3a59d79b3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { item_id } from '../../common/item_id'; - -export const readEndpointListItemSchema = t.exact( - t.partial({ - id, - item_id, - }) -); - -export type ReadEndpointListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type ReadEndpointListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts deleted file mode 100644 index 00e72dc68f5f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, ITEM_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { ReadExceptionListItemSchema } from '.'; - -export const getReadExceptionListItemSchemaMock = (): ReadExceptionListItemSchema => ({ - id: ID, - item_id: ITEM_ID, - namespace_type: NAMESPACE_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts deleted file mode 100644 index e1c461551030..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,128 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getReadExceptionListItemSchemaMock } from './index.mock'; -import { ReadExceptionListItemSchema, readExceptionListItemSchema } from '.'; - -describe('read_exception_list_item_schema', () => { - test('it should validate a typical exception list request', () => { - const payload = getReadExceptionListItemSchemaMock(); - const decoded = readExceptionListItemSchema.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 accept an undefined for "id"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.id; - const decoded = readExceptionListItemSchema.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 accept an undefined for "item_id"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.item_id; - const decoded = readExceptionListItemSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.namespace_type; - const decoded = readExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getReadExceptionListItemSchemaMock()); - }); - - test('it should accept an undefined for "id", "item_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.id; - delete payload.namespace_type; - delete payload.item_id; - const output = getReadExceptionListItemSchemaMock(); - delete output.id; - delete output.item_id; - const decoded = readExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "id", "item_id"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.id; - delete payload.item_id; - const decoded = readExceptionListItemSchema.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 accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.id; - delete payload.namespace_type; - const output = getReadExceptionListItemSchemaMock(); - delete output.id; - const decoded = readExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "item_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListItemSchemaMock(); - delete payload.namespace_type; - delete payload.item_id; - const output = getReadExceptionListItemSchemaMock(); - delete output.item_id; - const decoded = readExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ReadExceptionListItemSchema & { - extraKey?: string; - } = getReadExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = readExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.ts deleted file mode 100644 index 6f54ede5ff51..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NamespaceType } from '../../common/default_namespace'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { item_id } from '../../common/item_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const readExceptionListItemSchema = t.exact( - t.partial({ - id, - item_id, - namespace_type, // defaults to 'single' if not set during decode - }) -); - -export type ReadExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type ReadExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceType; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts deleted file mode 100644 index 47fcba01fd95..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { ReadExceptionListSchema } from '.'; - -export const getReadExceptionListSchemaMock = (): ReadExceptionListSchema => ({ - id: ID, - list_id: LIST_ID, - namespace_type: NAMESPACE_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts deleted file mode 100644 index 2c5a93021b7c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts +++ /dev/null @@ -1,128 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getReadExceptionListSchemaMock } from './index.mock'; -import { ReadExceptionListSchema, readExceptionListSchema } from '.'; - -describe('read_exception_list_schema', () => { - test('it should validate a typical exception list request', () => { - const payload = getReadExceptionListSchemaMock(); - const decoded = readExceptionListSchema.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 accept an undefined for "id"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.id; - const decoded = readExceptionListSchema.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 accept an undefined for "list_id"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.list_id; - const decoded = readExceptionListSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.namespace_type; - const decoded = readExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getReadExceptionListSchemaMock()); - }); - - test('it should accept an undefined for "id", "list_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.id; - delete payload.namespace_type; - delete payload.list_id; - const output = getReadExceptionListSchemaMock(); - delete output.id; - delete output.list_id; - const decoded = readExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "id", "list_id"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.id; - delete payload.list_id; - const decoded = readExceptionListSchema.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 accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.id; - delete payload.namespace_type; - const output = getReadExceptionListSchemaMock(); - delete output.id; - const decoded = readExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "list_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getReadExceptionListSchemaMock(); - delete payload.namespace_type; - delete payload.list_id; - const output = getReadExceptionListSchemaMock(); - delete output.list_id; - const decoded = readExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ReadExceptionListSchema & { - extraKey?: string; - } = getReadExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = readExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.ts deleted file mode 100644 index fb2e66d2f1de..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NamespaceType } from '../../common/default_namespace'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const readExceptionListSchema = t.exact( - t.partial({ - id, - list_id, - namespace_type, // defaults to 'single' if not set during decode - }) -); - -export type ReadExceptionListSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type ReadExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceType; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts deleted file mode 100644 index d78bb6f44bc7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID, LIST_ITEM_ID, VALUE } from '../../constants/index.mock'; - -import { ReadListItemSchema } from '.'; - -export const getReadListItemSchemaMock = (): ReadListItemSchema => ({ - id: LIST_ITEM_ID, - list_id: LIST_ID, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts deleted file mode 100644 index 547537afc673..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts +++ /dev/null @@ -1,119 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getReadListItemSchemaMock } from './index.mock'; -import { ReadListItemSchema, readListItemSchema } from '.'; - -describe('read_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getReadListItemSchemaMock(); - const decoded = readListItemSchema.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 accept an undefined for "id"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.id; - const decoded = readListItemSchema.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 accept an undefined for "list_id"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.list_id; - const decoded = readListItemSchema.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 accept an undefined for "value"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.value; - const decoded = readListItemSchema.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 accept an undefined for "id", "list_id", "value"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.id; - delete payload.value; - delete payload.list_id; - const decoded = readListItemSchema.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 accept an undefined for "id", "list_id"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.id; - delete payload.list_id; - const decoded = readListItemSchema.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 accept an undefined for "id", "value"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.id; - delete payload.value; - const decoded = readListItemSchema.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 accept an undefined for "list_id", "value"', () => { - const payload = getReadListItemSchemaMock(); - delete payload.value; - delete payload.list_id; - const decoded = readListItemSchema.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 not allow an extra key to be sent in', () => { - const payload: ReadListItemSchema & { extraKey?: string } = getReadListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = readListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.ts deleted file mode 100644 index 3b45ebeea6ba..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { value } from '../../common/value'; - -export const readListItemSchema = t.exact(t.partial({ id, list_id, value })); - -export type ReadListItemSchema = t.OutputOf; -export type ReadListItemSchemaDecoded = RequiredKeepUndefined>; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts deleted file mode 100644 index 5eecbd49e472..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { LIST_ID } from '../../constants/index.mock'; - -import { ReadListSchema } from '.'; - -export const getReadListSchemaMock = (): ReadListSchema => ({ - id: LIST_ID, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.test.ts deleted file mode 100644 index d26f8206c498..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getReadListSchemaMock } from './index.mock'; -import { ReadListSchema, readListSchema } from '.'; - -describe('read_list_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getReadListSchemaMock(); - const decoded = readListSchema.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 NOT accept an undefined for "id"', () => { - const payload = getReadListSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = readListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ReadListSchema & { extraKey?: string } = getReadListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = readListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.ts deleted file mode 100644 index b9c008287139..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { id } from '../../common/id'; - -export const readListSchema = t.exact( - t.type({ - id, - }) -); - -export type ReadListSchema = t.OutputOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts deleted file mode 100644 index 61e8dfbae15f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FILTER, ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { SummaryExceptionListSchema } from '.'; - -export const getSummaryExceptionListSchemaMock = (): SummaryExceptionListSchema => ({ - filter: FILTER, - id: ID, - list_id: LIST_ID, - namespace_type: NAMESPACE_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts deleted file mode 100644 index 06db32fa2df3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts +++ /dev/null @@ -1,138 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getSummaryExceptionListSchemaMock } from './index.mock'; -import { SummaryExceptionListSchema, summaryExceptionListSchema } from '.'; - -describe('summary_exception_list_schema', () => { - test('it should validate a typical exception list request', () => { - const payload = getSummaryExceptionListSchemaMock(); - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "filter"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.filter; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "id"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "list_id"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.list_id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "namespace_type" but default to "single"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.namespace_type; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getSummaryExceptionListSchemaMock()); - }); - - test('it should accept an undefined for "id", "list_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.id; - delete payload.namespace_type; - delete payload.list_id; - const output = getSummaryExceptionListSchemaMock(); - delete output.id; - delete output.list_id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "id", "list_id"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.id; - delete payload.list_id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.id; - delete payload.namespace_type; - const output = getSummaryExceptionListSchemaMock(); - delete output.id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should accept an undefined for "list_id", "namespace_type" but default "namespace_type" to "single"', () => { - const payload = getSummaryExceptionListSchemaMock(); - delete payload.namespace_type; - delete payload.list_id; - const output = getSummaryExceptionListSchemaMock(); - delete output.list_id; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(output); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: SummaryExceptionListSchema & { - extraKey?: string; - } = getSummaryExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = summaryExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = foldLeftRight(checked); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts deleted file mode 100644 index 2815dfa05b27..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { NamespaceType } from '../../common/default_namespace'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { filter, Filter } from '../../common/filter'; -import { list_id } from '../../common/list_id'; -import { namespace_type } from '../../common/namespace_type'; - -export const summaryExceptionListSchema = t.exact( - t.partial({ - filter, - id, - list_id, - namespace_type, // defaults to 'single' if not set during decode - }) -); - -export type SummaryExceptionListSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type SummaryExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'namespace_type' -> & { - namespace_type: NamespaceType; - filter: Filter; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts deleted file mode 100644 index 8b34549a8c90..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - COMMENTS, - DESCRIPTION, - ENTRIES, - ID, - ITEM_TYPE, - LIST_ITEM_ID, - META, - NAME, - OS_TYPES, - TAGS, -} from '../../constants/index.mock'; - -import { UpdateEndpointListItemSchema } from '.'; - -export const getUpdateEndpointListItemSchemaMock = (): UpdateEndpointListItemSchema => ({ - _version: undefined, - comments: COMMENTS, - description: DESCRIPTION, - entries: ENTRIES, - id: ID, - item_id: LIST_ITEM_ID, - meta: META, - name: NAME, - os_types: OS_TYPES, - tags: TAGS, - type: ITEM_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts deleted file mode 100644 index f595ecd1ebbe..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { UpdateEndpointListItemSchema, updateEndpointListItemSchema } from '.'; -import { getUpdateEndpointListItemSchemaMock } from './index.mock'; - -describe('update_endpoint_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getUpdateEndpointListItemSchemaMock(); - const decoded = updateEndpointListItemSchema.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 not accept an undefined for "description"', () => { - const payload = getUpdateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "name"', () => { - const payload = getUpdateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "type"', () => { - const payload = getUpdateEndpointListItemSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept a value for "list_id"', () => { - const payload: UpdateEndpointListItemSchema & { - list_id?: string; - } = getUpdateEndpointListItemSchemaMock(); - payload.list_id = 'some new list_id'; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta" but strip it out', () => { - const payload = getUpdateEndpointListItemSchemaMock(); - const outputPayload = getUpdateEndpointListItemSchemaMock(); - delete payload.meta; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete outputPayload.meta; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "comments" but return an array', () => { - const inputPayload = getUpdateEndpointListItemSchemaMock(); - const outputPayload = getUpdateEndpointListItemSchemaMock(); - delete inputPayload.comments; - outputPayload.comments = []; - const decoded = updateEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should NOT accept an undefined for "entries"', () => { - const inputPayload = getUpdateEndpointListItemSchemaMock(); - const outputPayload = getUpdateEndpointListItemSchemaMock(); - // @ts-expect-error - delete inputPayload.entries; - outputPayload.entries = []; - const decoded = updateEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "tags" but return an array', () => { - const inputPayload = getUpdateEndpointListItemSchemaMock(); - const outputPayload = getUpdateEndpointListItemSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = updateEndpointListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: UpdateEndpointListItemSchema & { - extraKey?: string; - } = getUpdateEndpointListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = updateEndpointListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts deleted file mode 100644 index 7851d80ef2ef..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts +++ /dev/null @@ -1,59 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { DefaultUpdateCommentsArray } from '../../common/default_update_comments_array'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { description } from '../../common/description'; -import { name } from '../../common/name'; -import { _version } from '../../common/underscore_version'; -import { id } from '../../common/id'; -import { meta } from '../../common/meta'; -import { Tags, tags } from '../../common/tags'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { UpdateCommentsArray } from '../../common/update_comment'; -import { EntriesArray } from '../../common/entries'; - -export const updateEndpointListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEntriesArray, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - _version, // defaults to undefined if not set during decode - comments: DefaultUpdateCommentsArray, // defaults to empty array if not set during decode - id, // defaults to undefined if not set during decode - item_id: t.union([t.string, t.undefined]), - meta, // defaults to undefined if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - }) - ), -]); - -export type UpdateEndpointListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type UpdateEndpointListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'entries' | 'comments' -> & { - comments: UpdateCommentsArray; - tags: Tags; - entries: EntriesArray; - os_types: OsTypeArray; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.ts deleted file mode 100644 index fce5d2f7e18b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - COMMENTS, - DESCRIPTION, - ENTRIES, - ID, - ITEM_ID, - ITEM_TYPE, - LIST_ITEM_ID, - META, - NAME, - NAMESPACE_TYPE, - OS_TYPES, - TAGS, -} from '../../constants/index.mock'; - -import { UpdateExceptionListItemSchema } from '.'; - -export const getUpdateExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ - _version: undefined, - comments: COMMENTS, - description: DESCRIPTION, - entries: ENTRIES, - id: ID, - item_id: LIST_ITEM_ID, - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: ['linux'], - tags: TAGS, - type: ITEM_TYPE, -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - * after doing a get of the structure. - */ -export const getUpdateMinimalExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - name: NAME, - os_types: OS_TYPES, - type: ITEM_TYPE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts deleted file mode 100644 index 84e9b801c171..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,162 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { UpdateExceptionListItemSchema, updateExceptionListItemSchema } from '.'; -import { getUpdateExceptionListItemSchemaMock } from './index.mock'; - -describe('update_exception_list_item_schema', () => { - test('it should validate a typical exception list item request', () => { - const payload = getUpdateExceptionListItemSchemaMock(); - const decoded = updateExceptionListItemSchema.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 not accept an undefined for "description"', () => { - const payload = getUpdateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "name"', () => { - const payload = getUpdateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "type"', () => { - const payload = getUpdateExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept a value for "list_id"', () => { - const payload: UpdateExceptionListItemSchema & { - list_id?: string; - } = getUpdateExceptionListItemSchemaMock(); - payload.list_id = 'some new list_id'; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta" but strip it out', () => { - const payload = getUpdateExceptionListItemSchemaMock(); - const outputPayload = getUpdateExceptionListItemSchemaMock(); - delete payload.meta; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete outputPayload.meta; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "comments" but return an array', () => { - const inputPayload = getUpdateExceptionListItemSchemaMock(); - const outputPayload = getUpdateExceptionListItemSchemaMock(); - delete inputPayload.comments; - outputPayload.comments = []; - const decoded = updateExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should NOT accept an undefined for "entries"', () => { - const inputPayload = getUpdateExceptionListItemSchemaMock(); - const outputPayload = getUpdateExceptionListItemSchemaMock(); - // @ts-expect-error - delete inputPayload.entries; - outputPayload.entries = []; - const decoded = updateExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "namespace_type" but return enum "single"', () => { - const inputPayload = getUpdateExceptionListItemSchemaMock(); - const outputPayload = getUpdateExceptionListItemSchemaMock(); - delete inputPayload.namespace_type; - outputPayload.namespace_type = 'single'; - const decoded = updateExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "tags" but return an array', () => { - const inputPayload = getUpdateExceptionListItemSchemaMock(); - const outputPayload = getUpdateExceptionListItemSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = updateExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "item_id" and generate a correct body not counting the uuid', () => { - const inputPayload = getUpdateExceptionListItemSchemaMock(); - delete inputPayload.item_id; - const decoded = updateExceptionListItemSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as UpdateExceptionListItemSchema).item_id; - expect(message.schema).toEqual(inputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: UpdateExceptionListItemSchema & { - extraKey?: string; - } = getUpdateExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = updateExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts deleted file mode 100644 index b0190d8fa388..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts +++ /dev/null @@ -1,66 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { ExceptionListItemEntryArray } from '@kbn/securitysolution-exceptions-common/api'; -import { NamespaceType } from '../../common/default_namespace'; -import { DefaultUpdateCommentsArray } from '../../common/default_update_comments_array'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { Tags, tags } from '../../common/tags'; -import { UpdateCommentsArray } from '../../common/update_comment'; -import { description } from '../../common/description'; -import { name } from '../../common/name'; -import { _version } from '../../common/underscore_version'; -import { id } from '../../common/id'; -import { item_id } from '../../common/item_id'; -import { meta } from '../../common/meta'; -import { namespace_type } from '../../common/namespace_type'; -import { ExpireTimeOrUndefined, expireTimeOrUndefined } from '../../common'; - -export const updateExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - description, - entries: nonEmptyEntriesArray, - name, - type: exceptionListItemType, - }) - ), - t.exact( - t.partial({ - _version, // defaults to undefined if not set during decode - comments: DefaultUpdateCommentsArray, // defaults to empty array if not set during decode - expire_time: expireTimeOrUndefined, - id, // defaults to undefined if not set during decode - item_id, - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - }) - ), -]); - -export type UpdateExceptionListItemSchema = t.OutputOf; - -// This type is used after a decode since some things are defaults after a decode. -export type UpdateExceptionListItemSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags' | 'entries' | 'namespace_type' | 'comments' | 'os_types' | 'expire_time' -> & { - comments: UpdateCommentsArray; - tags: Tags; - entries: ExceptionListItemEntryArray; - namespace_type: NamespaceType; - os_types: OsTypeArray; - expire_time: ExpireTimeOrUndefined; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts deleted file mode 100644 index ff98cc71f03f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DESCRIPTION, ID, LIST_ID, META, NAME, NAMESPACE_TYPE } from '../../constants/index.mock'; - -import { UpdateExceptionListSchema } from '.'; - -export const getUpdateExceptionListSchemaMock = (): UpdateExceptionListSchema => ({ - _version: undefined, - description: DESCRIPTION, - id: ID, - list_id: LIST_ID, - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: [], - tags: ['malware'], - type: 'endpoint', -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - * after doing a get of the structure. - */ -export const getUpdateMinimalExceptionListSchemaMock = (): UpdateExceptionListSchema => ({ - description: DESCRIPTION, - list_id: LIST_ID, - name: NAME, - type: 'endpoint', -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts deleted file mode 100644 index 4821251f36d1..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts +++ /dev/null @@ -1,123 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { UpdateExceptionListSchema, updateExceptionListSchema } from '.'; -import { getUpdateExceptionListSchemaMock } from './index.mock'; - -describe('update_exception_list_schema', () => { - test('it should validate a typical exception list request', () => { - const payload = getUpdateExceptionListSchemaMock(); - const decoded = updateExceptionListSchema.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 not accept an undefined for "description"', () => { - const payload = getUpdateExceptionListSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = updateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "name"', () => { - const payload = getUpdateExceptionListSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = updateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not accept an undefined for "type"', () => { - const payload = getUpdateExceptionListSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = updateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta" but strip it out', () => { - const payload = getUpdateExceptionListSchemaMock(); - const outputPayload = getUpdateExceptionListSchemaMock(); - delete payload.meta; - const decoded = updateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete outputPayload.meta; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "namespace_type" but return enum "single"', () => { - const inputPayload = getUpdateExceptionListSchemaMock(); - const outputPayload = getUpdateExceptionListSchemaMock(); - delete inputPayload.namespace_type; - outputPayload.namespace_type = 'single'; - const decoded = updateExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "tags" but return an array', () => { - const inputPayload = getUpdateExceptionListSchemaMock(); - const outputPayload = getUpdateExceptionListSchemaMock(); - delete inputPayload.tags; - outputPayload.tags = []; - const decoded = updateExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should accept an undefined for "list_id" and generate a correct body not counting the uuid', () => { - const inputPayload = getUpdateExceptionListSchemaMock(); - delete inputPayload.list_id; - const decoded = updateExceptionListSchema.decode(inputPayload); - const checked = exactCheck(inputPayload, decoded); - const message = pipe(checked, foldLeftRight); - delete (message.schema as UpdateExceptionListSchema).list_id; - expect(message.schema).toEqual(inputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: UpdateExceptionListSchema & { - extraKey?: string; - } = getUpdateExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = updateExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts deleted file mode 100644 index 62add37568ba..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { version } from '@kbn/securitysolution-io-ts-types'; -import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { Tags, tags } from '../../common/tags'; -import { NamespaceType } from '../../common/default_namespace'; -import { description } from '../../common/description'; -import { name } from '../../common/name'; -import { _version } from '../../common/underscore_version'; -import { exceptionListType } from '../../common/exception_list'; -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { meta } from '../../common/meta'; -import { namespace_type } from '../../common/namespace_type'; - -export const updateExceptionListSchema = t.intersection([ - t.exact( - t.type({ - description, - name, - type: exceptionListType, - }) - ), - t.exact( - t.partial({ - _version, // defaults to undefined if not set during decode - id, // defaults to undefined if not set during decode - list_id, // defaults to undefined if not set during decode - meta, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode - os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode - tags, // defaults to empty array if not set during decode - version, // defaults to undefined if not set during decode - }) - ), -]); - -export type UpdateExceptionListSchema = t.OutputOf; - -// This type is used after a decode since the arrays turn into defaults of empty arrays. -export type UpdateExceptionListSchemaDecoded = Omit< - RequiredKeepUndefined>, - 'tags | namespace_type' | 'os_types' -> & { - tags: Tags; - namespace_type: NamespaceType; - os_types: OsTypeArray; -}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.ts deleted file mode 100644 index 9c3b2dbbd7d3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ID, LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; - -import { UpdateListItemSchema } from '.'; - -export const getUpdateListItemSchemaMock = (): UpdateListItemSchema => ({ - id: ID, - meta: META, - value: VALUE, -}); - -/** - * Useful for end to end testing - */ -export const getUpdateMinimalListItemSchemaMock = (): UpdateListItemSchema => ({ - id: LIST_ITEM_ID, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.ts deleted file mode 100644 index 6c7637cbde05..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { UpdateListItemSchema, updateListItemSchema } from '.'; -import { getUpdateListItemSchemaMock } from './index.mock'; - -describe('update_list_item_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getUpdateListItemSchemaMock(); - const decoded = updateListItemSchema.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 accept an undefined for "meta" but strip it out', () => { - const payload = getUpdateListItemSchemaMock(); - const outputPayload = getUpdateListItemSchemaMock(); - delete payload.meta; - const decoded = updateListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete outputPayload.meta; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: UpdateListItemSchema & { - extraKey?: string; - } = getUpdateListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = updateListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.ts deleted file mode 100644 index 613dde36ef0f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { _version } from '../../common/underscore_version'; -import { id } from '../../common/id'; -import { value } from '../../common/value'; -import { meta } from '../../common/meta'; - -export const updateListItemSchema = t.intersection([ - t.exact( - t.type({ - id, - value, - }) - ), - t.exact( - t.partial({ - _version, // defaults to undefined if not set during decode - meta, // defaults to undefined if not set during decode - }) - ), -]); - -export type UpdateListItemSchema = t.OutputOf; -export type UpdateListItemSchemaDecoded = RequiredKeepUndefined< - t.TypeOf ->; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.ts deleted file mode 100644 index 5f1fc8fe926d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DESCRIPTION, LIST_ID, META, NAME, _VERSION } from '../../constants/index.mock'; - -import { UpdateListSchema } from '.'; - -export const getUpdateListSchemaMock = (): UpdateListSchema => ({ - _version: _VERSION, - description: DESCRIPTION, - id: LIST_ID, - meta: META, - name: NAME, -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - * after doing a get of the structure. - */ -export const getUpdateMinimalListSchemaMock = (): UpdateListSchema => ({ - description: DESCRIPTION, - id: LIST_ID, - name: NAME, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.ts deleted file mode 100644 index cac97d7c32cf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { UpdateListSchema, updateListSchema } from '.'; -import { getUpdateListSchemaMock } from './index.mock'; - -describe('update_list_schema', () => { - test('it should validate a typical list request', () => { - const payload = getUpdateListSchemaMock(); - const decoded = updateListSchema.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 accept an undefined for "meta" but strip it out', () => { - const payload = getUpdateListSchemaMock(); - const outputPayload = getUpdateListSchemaMock(); - delete payload.meta; - const decoded = updateListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - delete outputPayload.meta; - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(outputPayload); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: UpdateListSchema & { - extraKey?: string; - } = getUpdateListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = updateListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.ts deleted file mode 100644 index 41ddb81c36e3..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { version } from '@kbn/securitysolution-io-ts-types'; -import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; -import { id } from '../../common/id'; -import { name } from '../../common/name'; -import { description } from '../../common/description'; -import { _version } from '../../common/underscore_version'; -import { meta } from '../../common/meta'; - -export const updateListSchema = t.intersection([ - t.exact( - t.type({ - description, - id, - name, - }) - ), - t.exact( - t.partial({ - _version, // defaults to undefined if not set during decode - meta, // defaults to undefined if not set during decode - version, // defaults to undefined if not set during decode - }) - ), -]); - -export type UpdateListSchema = t.OutputOf; -export type UpdateListSchemaDecoded = RequiredKeepUndefined>; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts deleted file mode 100644 index c532dd740197..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { AcknowledgeSchema } from '.'; - -export const getAcknowledgeSchemaResponseMock = (): AcknowledgeSchema => ({ - acknowledged: true, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.ts deleted file mode 100644 index 2d3086b02315..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getAcknowledgeSchemaResponseMock } from './index.mock'; -import { AcknowledgeSchema, acknowledgeSchema } from '.'; - -describe('acknowledge_schema', () => { - test('it should validate a typical response', () => { - const payload = getAcknowledgeSchemaResponseMock(); - const decoded = acknowledgeSchema.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 NOT accept an undefined for "ok"', () => { - const payload = getAcknowledgeSchemaResponseMock(); - // @ts-expect-error - delete payload.acknowledged; - const decoded = acknowledgeSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "acknowledged"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: AcknowledgeSchema & { extraKey?: string } = getAcknowledgeSchemaResponseMock(); - payload.extraKey = 'some new value'; - const decoded = acknowledgeSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts deleted file mode 100644 index d506f038534d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const acknowledgeSchema = t.exact(t.type({ acknowledged: t.boolean })); - -export type AcknowledgeSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts deleted file mode 100644 index 52c72cf0e8cb..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts +++ /dev/null @@ -1,75 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { CreateEndpointListSchema, createEndpointListSchema } from '.'; -import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; - -describe('create_endpoint_list_schema', () => { - test('it should validate a typical endpoint list response', () => { - const payload = getExceptionListSchemaMock(); - const decoded = createEndpointListSchema.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 accept an empty object when an endpoint list already exists', () => { - const payload: CreateEndpointListSchema = {}; - const decoded = createEndpointListSchema.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 NOT accept an undefined for "list_id"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = createEndpointListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'invalid keys "_version,created_at,created_by,description,id,immutable,meta,{},name,namespace_type,os_types,["linux"],tags,["user added string for a tag","malware"],tie_breaker_id,type,updated_at,updated_by,version"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT allow missing fields', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = createEndpointListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors)).length).toEqual(1); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: CreateEndpointListSchema & { - extraKey?: string; - } = getExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = createEndpointListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts deleted file mode 100644 index cdcdc8e67e07..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { exceptionListSchema } from '../exception_list_schema'; - -export const createEndpointListSchema = t.union([exceptionListSchema, t.exact(t.type({}))]); - -export type CreateEndpointListSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts deleted file mode 100644 index 2c0449ea900e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - COMMENTS, - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - ENTRIES, - ITEM_ID, - ITEM_TYPE, - LIST_ID, - META, - NAME, - NAMESPACE_TYPE, - OS_TYPES, - TIE_BREAKER, - USER, -} from '../../constants/index.mock'; - -import { ExceptionListItemSchema } from '.'; - -export const getExceptionListItemSchemaMock = ( - overrides?: Partial -): ExceptionListItemSchema => ({ - _version: undefined, - comments: COMMENTS, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - entries: ENTRIES, - expire_time: undefined, - id: '1', - item_id: 'endpoint_list_item', - list_id: 'endpoint_list_id', - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: ['linux'], - tags: ['user added string for a tag', 'malware'], - tie_breaker_id: TIE_BREAKER, - type: ITEM_TYPE, - updated_at: DATE_NOW, - updated_by: USER, - ...(overrides || {}), -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = - (): Partial => ({ - comments: [], - created_by: ELASTIC_USER, - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - list_id: LIST_ID, - name: NAME, - namespace_type: 'single', - os_types: OS_TYPES, - tags: [], - type: ITEM_TYPE, - updated_by: ELASTIC_USER, - }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts deleted file mode 100644 index 9c98d97a596a..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,242 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getExceptionListItemSchemaMock } from './index.mock'; -import { ExceptionListItemSchema, exceptionListItemSchema } from '.'; - -describe('exception_list_item_schema', () => { - test('it should validate a typical exception list item response', () => { - const payload = getExceptionListItemSchemaMock(); - const decoded = exceptionListItemSchema.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 NOT accept an undefined for "id"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "list_id"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "item_id"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.item_id; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "item_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "comments"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.comments; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "comments"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "entries"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.entries; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "name"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "namespace_type" and return "single" as a default value for "namespace_type"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.namespace_type; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect((message.schema as ExceptionListItemSchema).namespace_type).toEqual('single'); - }); - - test('it should NOT accept an undefined for "description"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getExceptionListItemSchemaMock(); - delete payload.meta; - const decoded = exceptionListItemSchema.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 NOT accept an undefined for "created_at"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.created_at; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "created_by"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.created_by; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "tie_breaker_id"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.tie_breaker_id; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "tie_breaker_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_at"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.updated_at; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_by"', () => { - const payload = getExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.updated_by; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ExceptionListItemSchema & { - extraKey?: string; - } = getExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = exceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts deleted file mode 100644 index 5408aa581bdf..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts +++ /dev/null @@ -1,56 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { namespace_type } from '../../common/namespace_type'; -import { metaOrUndefined } from '../../common/meta'; -import { name } from '../../common/name'; -import { created_at } from '../../common/created_at'; -import { created_by } from '../../common/created_by'; -import { id } from '../../common/id'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; -import { list_id } from '../../common/list_id'; -import { description } from '../../common/description'; -import { osTypeArray } from '../../common/os_type'; -import { tags } from '../../common/tags'; -import { _versionOrUndefined } from '../../common/underscore_version'; -import { commentsArray } from '../../common/comment'; -import { entriesArray } from '../../common/entries'; -import { item_id } from '../../common/item_id'; -import { exceptionListItemType } from '../../common/exception_list_item_type'; -import { expireTimeOrUndefined } from '../../common/expire_time'; - -export const exceptionListItemSchema = t.exact( - t.type({ - _version: _versionOrUndefined, - comments: commentsArray, - created_at, - created_by, - description, - entries: entriesArray, - expire_time: expireTimeOrUndefined, - id, - item_id, - list_id, - meta: metaOrUndefined, - name, - namespace_type, - os_types: osTypeArray, - tags, - tie_breaker_id, - type: exceptionListItemType, - updated_at, - updated_by, - }) -); - -export type ExceptionListItemSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts deleted file mode 100644 index de2efb85c337..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts +++ /dev/null @@ -1,79 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - ENDPOINT_TYPE, - IMMUTABLE, - LIST_ID, - META, - NAME, - TIE_BREAKER, - USER, - VERSION, - _VERSION, -} from '../../constants/index.mock'; -import { - ENDPOINT_LIST_ID, - ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION, - ENDPOINT_TRUSTED_APPS_LIST_ID, - ENDPOINT_TRUSTED_APPS_LIST_NAME, -} from '@kbn/securitysolution-list-constants'; - -import { ExceptionListSchema } from '.'; - -export const getExceptionListSchemaMock = (): ExceptionListSchema => ({ - _version: _VERSION, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - id: '1', - immutable: IMMUTABLE, - list_id: ENDPOINT_LIST_ID, - meta: META, - name: 'Sample Endpoint Exception List', - namespace_type: 'agnostic', - os_types: ['linux'], - tags: ['user added string for a tag', 'malware'], - tie_breaker_id: TIE_BREAKER, - type: ENDPOINT_TYPE, - updated_at: DATE_NOW, - updated_by: 'user_name', - version: VERSION, -}); - -export const getTrustedAppsListSchemaMock = (): ExceptionListSchema => { - return { - ...getExceptionListSchemaMock(), - description: ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION, - list_id: ENDPOINT_TRUSTED_APPS_LIST_ID, - name: ENDPOINT_TRUSTED_APPS_LIST_NAME, - }; -}; - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getExceptionResponseMockWithoutAutoGeneratedValues = - (): Partial => ({ - created_by: ELASTIC_USER, - description: DESCRIPTION, - immutable: IMMUTABLE, - list_id: LIST_ID, - name: NAME, - namespace_type: 'single', - os_types: [], - tags: [], - type: ENDPOINT_TYPE, - updated_by: ELASTIC_USER, - version: VERSION, - }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts deleted file mode 100644 index e8dc043bd6b0..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getExceptionListSchemaMock } from './index.mock'; -import { ExceptionListSchema, exceptionListSchema } from '.'; - -describe('exception_list_schema', () => { - test('it should validate a typical exception list response', () => { - const payload = getExceptionListSchemaMock(); - const decoded = exceptionListSchema.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 NOT accept an undefined for "id"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.id; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "list_id"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "name"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.name; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "namespace_type" and make "namespace_type" that of "single"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.namespace_type; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect((message.schema as ExceptionListSchema).namespace_type).toEqual('single'); - }); - - test('it should NOT accept an undefined for "description"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.description; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getExceptionListSchemaMock(); - delete payload.meta; - const decoded = exceptionListSchema.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 NOT accept an undefined for "created_at"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.created_at; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "created_by"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.created_by; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "tie_breaker_id"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.tie_breaker_id; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "tie_breaker_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.type; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_at"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.updated_at; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_by"', () => { - const payload = getExceptionListSchemaMock(); - // @ts-expect-error - delete payload.updated_by; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ExceptionListSchema & { - extraKey?: string; - } = getExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = exceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts deleted file mode 100644 index 0667153c2777..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { version } from '@kbn/securitysolution-io-ts-types'; -import { _versionOrUndefined } from '../../common/underscore_version'; -import { namespace_type } from '../../common/namespace_type'; -import { metaOrUndefined } from '../../common/meta'; -import { name } from '../../common/name'; -import { created_at } from '../../common/created_at'; -import { created_by } from '../../common/created_by'; -import { id } from '../../common/id'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; -import { immutable } from '../../common/immutable'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; -import { list_id } from '../../common/list_id'; -import { description } from '../../common/description'; -import { osTypeArray } from '../../common/os_type'; -import { exceptionListType } from '../../common/exception_list'; -import { tags } from '../../common/tags'; - -export const exceptionListSchema = t.exact( - t.type({ - _version: _versionOrUndefined, - created_at, - created_by, - description, - id, - immutable, - list_id, - meta: metaOrUndefined, - name, - namespace_type, - os_types: osTypeArray, - tags, - tie_breaker_id, - type: exceptionListType, - updated_at, - updated_by, - version, - }) -); - -export type ExceptionListSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts deleted file mode 100644 index 1decbde1374b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExceptionListSummarySchema } from '.'; - -export const getListSummaryResponseMock = (): ExceptionListSummarySchema => ({ - windows: 0, - linux: 1, - macos: 2, - total: 3, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.test.ts deleted file mode 100644 index ad1d8b737e46..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getListSummaryResponseMock } from './index.mock'; -import { ExceptionListSummarySchema, exceptionListSummarySchema } from '.'; - -describe('list_summary_schema', () => { - test('it should validate a typical list summary response', () => { - const payload = getListSummaryResponseMock(); - const decoded = exceptionListSummarySchema.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 NOT accept an undefined for "windows"', () => { - const payload = getListSummaryResponseMock(); - // @ts-expect-error - delete payload.windows; - const decoded = exceptionListSummarySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "windows"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "linux"', () => { - const payload = getListSummaryResponseMock(); - // @ts-expect-error - delete payload.linux; - const decoded = exceptionListSummarySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "linux"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "macos"', () => { - const payload = getListSummaryResponseMock(); - // @ts-expect-error - delete payload.macos; - const decoded = exceptionListSummarySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "macos"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "total"', () => { - const payload = getListSummaryResponseMock(); - // @ts-expect-error - delete payload.total; - const decoded = exceptionListSummarySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "total"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ExceptionListSummarySchema & { - extraKey?: string; - } = getListSummaryResponseMock(); - payload.extraKey = 'some new value'; - const decoded = exceptionListSummarySchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts deleted file mode 100644 index a14eaba10b78..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; -import * as t from 'io-ts'; - -export const exceptionListSummarySchema = t.exact( - t.type({ - windows: PositiveInteger, - linux: PositiveInteger, - macos: PositiveInteger, - total: PositiveInteger, - }) -); - -export type ExceptionListSummarySchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts deleted file mode 100644 index 7f6ec6e8bd5c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundAllListItemsSchema } from '.'; -import { getListItemResponseMock } from '../list_item_schema/index.mock'; - -export const getFoundAllListItemsSchemaMock = (): FoundAllListItemsSchema => ({ - data: [getListItemResponseMock()], - total: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts deleted file mode 100644 index f8e6dc43647f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { listItemSchema } from '../list_item_schema'; -import { total } from '../../common/total'; - -export const foundAllListItemsSchema = t.exact( - t.type({ - data: t.array(listItemSchema), - total, - }) -); - -export type FoundAllListItemsSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts deleted file mode 100644 index 8a7abc59a9cd..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundExceptionListItemSchema } from '.'; -import { getExceptionListItemSchemaMock } from '../exception_list_item_schema/index.mock'; - -export const getFoundExceptionListItemSchemaMock = (): FoundExceptionListItemSchema => ({ - data: [getExceptionListItemSchemaMock()], - page: 1, - per_page: 1, - total: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts deleted file mode 100644 index eeaeee26fac4..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts +++ /dev/null @@ -1,154 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getFoundExceptionListItemSchemaMock } from './index.mock'; -import { FoundExceptionListItemSchema, foundExceptionListItemSchema } from '.'; -import { ExceptionListItemSchema } from '../exception_list_item_schema'; -import { getExceptionListItemSchemaMock } from '../exception_list_item_schema/index.mock'; - -describe('found_exception_list_item_schema', () => { - test('it should validate a typical exception list response', () => { - const payload = getFoundExceptionListItemSchemaMock(); - const decoded = foundExceptionListItemSchema.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 NOT accept a malformed exception list item within "data"', () => { - const item: Omit & { - entries?: string; - } = { ...getExceptionListItemSchemaMock(), entries: 'I should be an array' }; - const payload: Omit & { - data?: Array< - Omit & { - entries?: string; - } - >; - } = { ...getFoundExceptionListItemSchemaMock(), data: [item] }; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "I should be an array" supplied to "data,entries"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "page"', () => { - const payload: Omit & { - page?: string; - } = { ...getFoundExceptionListItemSchemaMock(), page: '1' }; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "page"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "per_page"', () => { - const payload: Omit & { - per_page?: string; - } = { ...getFoundExceptionListItemSchemaMock(), per_page: '20' }; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "20" supplied to "per_page"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "total"', () => { - const payload: Omit & { - total?: string; - } = { ...getFoundExceptionListItemSchemaMock(), total: '1' }; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "total"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "page"', () => { - const payload = getFoundExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.page; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "page"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "per_page"', () => { - const payload = getFoundExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.per_page; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "per_page"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "total"', () => { - const payload = getFoundExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.total; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "total"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "data"', () => { - const payload = getFoundExceptionListItemSchemaMock(); - // @ts-expect-error - delete payload.data; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "data"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FoundExceptionListItemSchema & { - extraKey?: string; - } = getFoundExceptionListItemSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = foundExceptionListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.ts deleted file mode 100644 index 6e34672f3349..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { page } from '../../common/page'; -import { per_page } from '../../common/per_page'; -import { pitId } from '../../common/pit'; -import { total } from '../../common/total'; -import { exceptionListItemSchema } from '../exception_list_item_schema'; - -export const foundExceptionListItemSchema = t.intersection([ - t.exact( - t.type({ - data: t.array(exceptionListItemSchema), - page, - per_page, - total, - }) - ), - t.exact( - t.partial({ - pit: pitId, - }) - ), -]); - -export type FoundExceptionListItemSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts deleted file mode 100644 index 5a4aa9fcbe57..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts +++ /dev/null @@ -1,18 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundExceptionListSchema } from '.'; -import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; - -export const getFoundExceptionListSchemaMock = (): FoundExceptionListSchema => ({ - data: [getExceptionListSchemaMock()], - page: 1, - per_page: 1, - total: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts deleted file mode 100644 index 07b302c80170..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts +++ /dev/null @@ -1,154 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getFoundExceptionListSchemaMock } from './index.mock'; -import { FoundExceptionListSchema, foundExceptionListSchema } from '.'; -import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; -import { ExceptionListSchema } from '../exception_list_schema'; - -describe('exception_list_schema', () => { - test('it should validate a typical exception list response', () => { - const payload = getFoundExceptionListSchemaMock(); - const decoded = foundExceptionListSchema.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 NOT accept a malformed exception list item within "data"', () => { - const item: Omit & { - entries?: string[]; - } = { ...getExceptionListSchemaMock(), entries: ['I should not be here'] }; - const payload: Omit & { - data?: Array< - Omit & { - entries?: string[]; - } - >; - } = { ...getFoundExceptionListSchemaMock(), data: [item] }; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'invalid keys "entries,["I should not be here"]"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "page"', () => { - const payload: Omit & { - page?: string; - } = { ...getFoundExceptionListSchemaMock(), page: '1' }; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "page"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "per_page"', () => { - const payload: Omit & { - per_page?: string; - } = { ...getFoundExceptionListSchemaMock(), per_page: '20' }; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "20" supplied to "per_page"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept a string for "total"', () => { - const payload: Omit & { - total?: string; - } = { ...getFoundExceptionListSchemaMock(), total: '1' }; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "total"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "page"', () => { - const payload = getFoundExceptionListSchemaMock(); - // @ts-expect-error - delete payload.page; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "page"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "per_page"', () => { - const payload = getFoundExceptionListSchemaMock(); - // @ts-expect-error - delete payload.per_page; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "per_page"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "total"', () => { - const payload = getFoundExceptionListSchemaMock(); - // @ts-expect-error - delete payload.total; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "total"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "data"', () => { - const payload = getFoundExceptionListSchemaMock(); - // @ts-expect-error - delete payload.data; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "data"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: FoundExceptionListSchema & { - extraKey?: string; - } = getFoundExceptionListSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = foundExceptionListSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts deleted file mode 100644 index de4a222b61e7..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { page } from '../../common/page'; -import { per_page } from '../../common/per_page'; -import { pitId } from '../../common/pit'; -import { total } from '../../common/total'; - -import { exceptionListSchema } from '../exception_list_schema'; - -export const foundExceptionListSchema = t.intersection([ - t.exact( - t.type({ - data: t.array(exceptionListSchema), - page, - per_page, - total, - }) - ), - t.exact(t.partial({ pit: pitId })), -]); - -export type FoundExceptionListSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts deleted file mode 100644 index 3f2083565743..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundListItemSchema } from '.'; -import { getListItemResponseMock } from '../list_item_schema/index.mock'; - -export const getFoundListItemSchemaMock = (): FoundListItemSchema => ({ - cursor: 'WzI1LFsiNmE3NmI2OWQtODBkZi00YWIyLThjM2UtODVmNDY2YjA2YTBlIl1d', - data: [getListItemResponseMock()], - page: 1, - per_page: 25, - total: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.ts deleted file mode 100644 index 872a178b2f13..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { listItemSchema } from '../list_item_schema'; -import { cursor } from '../../common/cursor'; -import { page } from '../../common/page'; -import { per_page } from '../../common/per_page'; -import { total } from '../../common/total'; - -export const foundListItemSchema = t.exact( - t.type({ - cursor, - data: t.array(listItemSchema), - page, - per_page, - total, - }) -); - -export type FoundListItemSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts deleted file mode 100644 index 232de4d47c15..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundListSchema } from '.'; -import { getListResponseMock } from '../list_schema/index.mock'; - -export const getFoundListSchemaMock = (): FoundListSchema => ({ - cursor: '123', - data: [getListResponseMock()], - page: 1, - per_page: 1, - total: 1, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.ts deleted file mode 100644 index 6b97b8c73e63..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { listSchema } from '../list_schema'; -import { cursor } from '../../common/cursor'; -import { page } from '../../common/page'; -import { per_page } from '../../common/per_page'; -import { total } from '../../common/total'; - -export const foundListSchema = t.exact( - t.type({ - cursor, - data: t.array(listSchema), - page, - per_page, - total, - }) -); - -export type FoundListSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts deleted file mode 100644 index bd654ccde56e..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts +++ /dev/null @@ -1,16 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { FoundListsBySizeSchema } from '.'; -import { getListResponseMock } from '../list_schema/index.mock'; - -export const getFoundListsBySizeSchemaMock = (): FoundListsBySizeSchema => ({ - smallLists: [getListResponseMock()], - largeLists: [getListResponseMock()], -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.ts deleted file mode 100644 index b4d41484bf26..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { listSchema } from '../list_schema'; - -export const foundListsBySizeSchema = t.exact( - t.type({ - largeLists: t.array(listSchema), - smallLists: t.array(listSchema), - }) -); - -export type FoundListsBySizeSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.ts deleted file mode 100644 index b1502381013c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ImportExceptionsResponseSchema } from '.'; - -export const getImportExceptionsResponseSchemaMock = ( - success = 0, - lists = 0, - items = 0 -): ImportExceptionsResponseSchema => ({ - errors: [], - success: true, - success_count: success, - success_exception_lists: true, - success_count_exception_lists: lists, - success_exception_list_items: true, - success_count_exception_list_items: items, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts deleted file mode 100644 index 81dd87bf19a5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts +++ /dev/null @@ -1,130 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { importExceptionsResponseSchema, ImportExceptionsResponseSchema } from '.'; -import { getImportExceptionsResponseSchemaMock } from './index.mock'; - -describe('importExceptionsResponseSchema', () => { - test('it should validate a typical exceptions import response', () => { - const payload = getImportExceptionsResponseSchemaMock(); - const decoded = importExceptionsResponseSchema.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 NOT accept an undefined for "errors"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.errors; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "errors"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success_count"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success_count; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success_count"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success_exception_lists"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success_exception_lists; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success_exception_lists"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success_count_exception_lists"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success_count_exception_lists; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success_count_exception_lists"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success_exception_list_items"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success_exception_list_items; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success_exception_list_items"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "success_count_exception_list_items"', () => { - const payload: Partial> = - getImportExceptionsResponseSchemaMock(); - delete payload.success_count_exception_list_items; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "success_count_exception_list_items"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ImportExceptionsResponseSchema & { - extraKey?: string; - } = getImportExceptionsResponseSchemaMock(); - payload.extraKey = 'some new value'; - const decoded = importExceptionsResponseSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts deleted file mode 100644 index b976ab298e0c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; - -import { id } from '../../common/id'; -import { list_id } from '../../common/list_id'; -import { item_id } from '../../common/item_id'; - -export const bulkErrorErrorSchema = t.exact( - t.type({ - status_code: t.number, - message: t.string, - }) -); - -export const bulkErrorSchema = t.intersection([ - t.exact( - t.type({ - error: bulkErrorErrorSchema, - }) - ), - t.partial({ - id, - list_id, - item_id, - }), -]); - -export type BulkErrorSchema = t.TypeOf; - -export const importExceptionsResponseSchema = t.exact( - t.type({ - errors: t.array(bulkErrorSchema), - success: t.boolean, - success_count: PositiveInteger, - success_exception_lists: t.boolean, - success_count_exception_lists: PositiveInteger, - success_exception_list_items: t.boolean, - success_count_exception_list_items: PositiveInteger, - }) -); - -export type ImportExceptionsResponseSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/index.ts deleted file mode 100644 index 49c42783473d..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './acknowledge_schema'; -export * from './create_endpoint_list_schema'; -export * from './exception_list_schema'; -export * from './exception_list_item_schema'; -export * from './found_exception_list_item_schema'; -export * from './found_exception_list_schema'; -export * from './found_all_list_items_schema'; -export * from './found_lists_by_size_schema'; -export * from './found_list_item_schema'; -export * from './found_list_schema'; -export * from './import_exceptions_schema'; -export * from './list_item_schema'; -export * from './list_schema'; -export * from './exception_list_summary_schema'; -export * from './list_item_index_exist_schema'; -export * from './search_list_item_schema'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts deleted file mode 100644 index eff892b3f00b..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ListItemIndexExistSchema } from '.'; - -export const getListItemIndexExistSchemaResponseMock = (): ListItemIndexExistSchema => ({ - list_index: true, - list_item_index: true, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts deleted file mode 100644 index 2827cd362734..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts +++ /dev/null @@ -1,67 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getListItemIndexExistSchemaResponseMock } from './index.mock'; -import { ListItemIndexExistSchema, listItemIndexExistSchema } from '.'; - -describe('list_item_index_exist_schema', () => { - test('it should validate a typical list item request', () => { - const payload = getListItemIndexExistSchemaResponseMock(); - const decoded = listItemIndexExistSchema.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 NOT accept an undefined for "list_index"', () => { - const payload = getListItemIndexExistSchemaResponseMock(); - // @ts-expect-error - delete payload.list_index; - const decoded = listItemIndexExistSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_index"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "list_item_index"', () => { - const payload = getListItemIndexExistSchemaResponseMock(); - // @ts-expect-error - delete payload.list_item_index; - const decoded = listItemIndexExistSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_item_index"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ListItemIndexExistSchema & { - extraKey?: string; - } = getListItemIndexExistSchemaResponseMock(); - payload.extraKey = 'some new value'; - const decoded = listItemIndexExistSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts deleted file mode 100644 index 494af4e3e759..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -export const listItemIndexExistSchema = t.exact( - t.type({ - list_index: t.boolean, - list_item_index: t.boolean, - }) -); - -export type ListItemIndexExistSchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.ts deleted file mode 100644 index 22c2e5ae07f6..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ListItemSchema } from '.'; -import { - DATE_NOW, - ELASTIC_USER, - LIST_ID, - LIST_ITEM_ID, - META, - TIE_BREAKER, - TYPE, - USER, - VALUE, -} from '../../constants/index.mock'; - -export const getListItemResponseMock = (): ListItemSchema => ({ - _version: undefined, - '@timestamp': DATE_NOW, - created_at: DATE_NOW, - created_by: USER, - deserializer: undefined, - id: LIST_ITEM_ID, - list_id: LIST_ID, - meta: META, - serializer: undefined, - tie_breaker_id: TIE_BREAKER, - type: TYPE, - updated_at: DATE_NOW, - updated_by: USER, - value: VALUE, -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getListItemResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - created_by: ELASTIC_USER, - list_id: LIST_ID, - type: TYPE, - updated_by: ELASTIC_USER, - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts deleted file mode 100644 index 5b4238e136dc..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts +++ /dev/null @@ -1,194 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getListItemResponseMock } from './index.mock'; -import { ListItemSchema, listItemSchema } from '.'; - -describe('list_item_schema', () => { - test('it should validate a typical list item response', () => { - const payload = getListItemResponseMock(); - const decoded = listItemSchema.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 NOT accept an undefined for "id"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.id; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "list_id"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.list_id; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "list_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getListItemResponseMock(); - delete payload.meta; - const decoded = listItemSchema.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 accept an undefined for "serializer"', () => { - const payload = getListItemResponseMock(); - delete payload.serializer; - const decoded = listItemSchema.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 accept an undefined for "deserializer"', () => { - const payload = getListItemResponseMock(); - delete payload.deserializer; - const decoded = listItemSchema.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 NOT accept an undefined for "created_at"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.created_at; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "created_by"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.created_by; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "tie_breaker_id"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.tie_breaker_id; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "tie_breaker_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.type; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_at"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.updated_at; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_by"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.updated_by; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "value"', () => { - const payload = getListItemResponseMock(); - // @ts-expect-error - delete payload.value; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "value"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ListItemSchema & { extraKey?: string } = getListItemResponseMock(); - payload.extraKey = 'some new value'; - const decoded = listItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.ts deleted file mode 100644 index 869ca695fa42..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; - -import { _versionOrUndefined } from '../../common/underscore_version'; -import { deserializerOrUndefined } from '../../common/deserializer'; -import { metaOrUndefined } from '../../common/meta'; -import { timestampOrUndefined } from '../../common/timestamp'; -import { serializerOrUndefined } from '../../common/serializer'; -import { created_at } from '../../common/created_at'; -import { created_by } from '../../common/created_by'; -import { id } from '../../common/id'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; -import { type } from '../../common/type'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; -import { list_id } from '../../common/list_id'; -import { value } from '../../common/value'; - -export const listItemSchema = t.exact( - t.type({ - _version: _versionOrUndefined, - '@timestamp': timestampOrUndefined, - created_at, - created_by, - deserializer: deserializerOrUndefined, - id, - list_id, - meta: metaOrUndefined, - serializer: serializerOrUndefined, - tie_breaker_id, - type, - updated_at, - updated_by, - value, - }) -); - -export type ListItemSchema = t.TypeOf; - -export const listItemArraySchema = t.array(listItemSchema); -export type ListItemArraySchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts deleted file mode 100644 index 7a0b9e01b87c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts +++ /dev/null @@ -1,56 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ListSchema } from '.'; -import { - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - IMMUTABLE, - LIST_ID, - META, - NAME, - TIE_BREAKER, - TYPE, - USER, - VERSION, -} from '../../constants/index.mock'; - -export const getListResponseMock = (): ListSchema => ({ - _version: undefined, - '@timestamp': DATE_NOW, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - deserializer: undefined, - id: LIST_ID, - immutable: IMMUTABLE, - meta: META, - name: NAME, - serializer: undefined, - tie_breaker_id: TIE_BREAKER, - type: TYPE, - updated_at: DATE_NOW, - updated_by: USER, - version: VERSION, -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - created_by: ELASTIC_USER, - description: DESCRIPTION, - immutable: IMMUTABLE, - name: NAME, - type: TYPE, - updated_by: ELASTIC_USER, - version: VERSION, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts deleted file mode 100644 index 17f25de7d8ec..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts +++ /dev/null @@ -1,194 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getListResponseMock } from './index.mock'; -import { ListSchema, listSchema } from '.'; - -describe('list_schema', () => { - test('it should validate a typical list response', () => { - const payload = getListResponseMock(); - const decoded = listSchema.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 NOT accept an undefined for "id"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.id; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); - expect(message.schema).toEqual({}); - }); - - test('it should accept an undefined for "meta"', () => { - const payload = getListResponseMock(); - delete payload.meta; - const decoded = listSchema.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 accept an undefined for "serializer"', () => { - const payload = getListResponseMock(); - delete payload.serializer; - const decoded = listSchema.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 accept an undefined for "deserializer"', () => { - const payload = getListResponseMock(); - delete payload.deserializer; - const decoded = listSchema.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 NOT accept an undefined for "created_at"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.created_at; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "created_by"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.created_by; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "created_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "tie_breaker_id"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.tie_breaker_id; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "tie_breaker_id"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "type"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.type; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_at"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.updated_at; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_at"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "updated_by"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.updated_by; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "updated_by"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "name"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.name; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "name"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT accept an undefined for "description"', () => { - const payload = getListResponseMock(); - // @ts-expect-error - delete payload.description; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "description"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: ListSchema & { extraKey?: string } = getListResponseMock(); - payload.extraKey = 'some new value'; - const decoded = listSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts deleted file mode 100644 index 5029e55df324..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { version } from '@kbn/securitysolution-io-ts-types'; -import { _versionOrUndefined } from '../../common/underscore_version'; -import { deserializerOrUndefined } from '../../common/deserializer'; -import { metaOrUndefined } from '../../common/meta'; -import { serializerOrUndefined } from '../../common/serializer'; -import { created_at } from '../../common/created_at'; -import { timestampOrUndefined } from '../../common/timestamp'; -import { created_by } from '../../common/created_by'; -import { description } from '../../common/description'; -import { id } from '../../common/id'; -import { immutable } from '../../common/immutable'; -import { name } from '../../common/name'; -import { tie_breaker_id } from '../../common/tie_breaker_id'; -import { type } from '../../common/type'; -import { updated_at } from '../../common/updated_at'; -import { updated_by } from '../../common/updated_by'; - -export const listSchema = t.exact( - t.type({ - _version: _versionOrUndefined, - '@timestamp': timestampOrUndefined, - created_at, - created_by, - description, - deserializer: deserializerOrUndefined, - id, - immutable, - meta: metaOrUndefined, - name, - serializer: serializerOrUndefined, - tie_breaker_id, - type, - updated_at, - updated_by, - version, - }) -); - -export type ListSchema = t.TypeOf; - -export const listArraySchema = t.array(listSchema); -export type ListArraySchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts deleted file mode 100644 index 1cab9a6b827c..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { SearchListItemSchema } from '.'; -import { VALUE } from '../../constants/index.mock'; -import { getListItemResponseMock } from '../list_item_schema/index.mock'; - -export const getSearchListItemResponseMock = (): SearchListItemSchema => ({ - items: [getListItemResponseMock()], - value: VALUE, -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.test.ts deleted file mode 100644 index a6604f39b462..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { left } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; - -import { getSearchListItemResponseMock } from './index.mock'; -import { SearchListItemSchema, searchListItemSchema } from '.'; - -describe('search_list_item_schema', () => { - test('it should validate a typical search list item response', () => { - const payload = getSearchListItemResponseMock(); - const decoded = searchListItemSchema.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 NOT validate with an "undefined" for "items"', () => { - const { items, ...noItems } = getSearchListItemResponseMock(); - const decoded = searchListItemSchema.decode(noItems); - const checked = exactCheck(noItems, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "items"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not allow an extra key to be sent in', () => { - const payload: SearchListItemSchema & { extraKey?: string } = getSearchListItemResponseMock(); - payload.extraKey = 'some new value'; - const decoded = searchListItemSchema.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.ts deleted file mode 100644 index c5a07308dd0f..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import * as t from 'io-ts'; -import { listItemArraySchema } from '../list_item_schema'; - -/** - * NOTE: Although this is defined within "response" this does not expose a REST API - * endpoint right now for this particular response. Instead this is only used internally - * for the plugins at this moment. If this changes, please remove this message. - */ -export const searchListItemSchema = t.exact( - t.type({ - items: listItemArraySchema, - value: t.unknown, - }) -); - -export type SearchListItemSchema = t.TypeOf; - -export const searchListItemArraySchema = t.array(searchListItemSchema); -export type SearchListItemArraySchema = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts deleted file mode 100644 index 9a8cd1e4fab5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts +++ /dev/null @@ -1,244 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { HttpStart } from '@kbn/core-http-browser'; -import type { NotificationsStart } from '@kbn/core-notifications-browser'; -import type { Filter } from '@kbn/es-query'; -import { NamespaceType } from '../common/default_namespace'; -import { ExceptionListType, ExceptionListTypeEnum } from '../common/exception_list'; -import { Page } from '../common/page'; -import { PerPage } from '../common/per_page'; -import { TotalOrUndefined } from '../common/total'; -import { CreateExceptionListItemSchema } from '../request/create_exception_list_item_schema'; -import { CreateExceptionListSchema } from '../request/create_exception_list_schema'; -import { ExceptionListId } from '../request/get_exception_filter_schema'; -import { UpdateExceptionListItemSchema } from '../request/update_exception_list_item_schema'; -import { UpdateExceptionListSchema } from '../request/update_exception_list_schema'; -import { ExceptionListItemSchema } from '../response/exception_list_item_schema'; -import { ExceptionListSchema } from '../response/exception_list_schema'; - -interface BaseParams { - http: HttpStart; - signal: AbortSignal; -} - -export interface DuplicateExceptionListProps extends BaseParams { - listId: string; - namespaceType: NamespaceType; - includeExpiredExceptions: boolean; -} - -export interface ApiListDuplicateProps - extends Omit { - onError: (err: Error) => void; - onSuccess: (newList: ExceptionListSchema) => void; -} - -export interface ExceptionListFilter { - name?: string | null; - list_id?: string | null; - created_by?: string | null; - types?: ExceptionListTypeEnum[] | null; - tags?: string | null; -} - -export interface UseExceptionListsProps { - errorMessage: string; - filterOptions?: ExceptionListFilter; - http: HttpStart; - namespaceTypes: NamespaceType[]; - notifications: NotificationsStart; - initialPagination?: Pagination; - hideLists?: readonly string[]; - initialSort?: Sort; -} - -export interface UseExceptionListProps { - http: HttpStart; - lists: ExceptionListIdentifiers[]; - onError?: (arg: string[]) => void; - filterOptions: FilterExceptionsOptions[]; - pagination?: Pagination; - showDetectionsListsOnly: boolean; - showEndpointListsOnly: boolean; - matchFilters: boolean; - onSuccess?: (arg: UseExceptionListItemsSuccess) => void; - sort?: Sort; -} - -export interface FilterExceptionsOptions { - filter: string; - tags: string[]; -} - -export interface ApiCallMemoProps { - id: string; - namespaceType: NamespaceType; - onError: (arg: Error) => void; - onSuccess: () => void; -} - -// TODO: Switch to use ApiCallMemoProps -// after cleaning up exceptions/api file to -// remove unnecessary validation checks -export interface ApiListExportProps { - id: string; - includeExpiredExceptions: boolean; - listId: string; - namespaceType: NamespaceType; - onError: (err: Error) => void; - onSuccess: (blob: Blob) => void; -} - -export interface Sort { - field: string; - order: string; -} -export interface Pagination { - page: Page; - perPage: PerPage; - total: TotalOrUndefined; -} - -export interface UseExceptionListItemsSuccess { - exceptions: ExceptionListItemSchema[]; - pagination: Pagination; -} - -export interface ExceptionListIdentifiers { - id: string; - listId: string; - namespaceType: NamespaceType; - type: ExceptionListType; -} - -export interface ApiCallFindListsItemsMemoProps { - lists: ExceptionListIdentifiers[]; - pagination: Partial; - showDetectionsListsOnly: boolean; - showEndpointListsOnly: boolean; - filter?: string; - onError: (arg: string[]) => void; - onSuccess: (arg: UseExceptionListItemsSuccess) => void; -} - -export interface ApiCallGetExceptionFilterFromIdsMemoProps extends GetExceptionFilterOptionalProps { - exceptionListIds: ExceptionListId[]; - onError: (arg: string[]) => void; - onSuccess: (arg: Filter) => void; -} - -export interface ApiCallGetExceptionFilterFromExceptionsMemoProps - extends GetExceptionFilterOptionalProps { - exceptions: Array; - onError: (arg: string[]) => void; - onSuccess: (arg: Filter) => void; -} - -export interface ExportExceptionListProps { - http: HttpStart; - id: string; - listId: string; - namespaceType: NamespaceType; - includeExpiredExceptions: boolean; - signal: AbortSignal; -} - -export interface AddEndpointExceptionListProps { - http: HttpStart; - signal: AbortSignal; -} - -export interface UpdateExceptionListItemProps { - http: HttpStart; - listItem: UpdateExceptionListItemSchema; - signal: AbortSignal; -} - -export interface UpdateExceptionListProps { - http: HttpStart; - list: UpdateExceptionListSchema; - signal: AbortSignal; -} - -export interface AddExceptionListItemProps { - http: HttpStart; - listItem: CreateExceptionListItemSchema; - signal: AbortSignal; -} - -export interface AddExceptionListProps { - http: HttpStart; - list: CreateExceptionListSchema; - signal: AbortSignal; -} - -export interface UseExceptionListsSuccess { - exceptions: ExceptionListSchema[]; - pagination: Pagination; -} - -export interface ApiCallFetchExceptionListsProps { - http: HttpStart; - namespaceTypes: string; - pagination: Partial; - sort?: Sort; - filters: string; - signal: AbortSignal; -} - -export interface ApiCallByIdProps { - http: HttpStart; - id: string; - namespaceType: NamespaceType; - signal: AbortSignal; -} - -export interface ApiCallByListIdProps { - http: HttpStart; - listIds: string[]; - namespaceTypes: NamespaceType[]; - pagination: Partial; - search?: string; - filter?: string; - signal: AbortSignal; -} - -export type AddExceptionList = UpdateExceptionListSchema | CreateExceptionListSchema; - -export interface PersistHookProps { - http: HttpStart; - onError: (arg: Error) => void; -} - -export interface ExceptionList extends ExceptionListSchema { - totalItems: number; -} - -export interface GetExceptionFilterOptionalProps { - signal?: AbortSignal; - chunkSize?: number; - alias?: string; - excludeExceptions?: boolean; -} - -export interface GetExceptionFilterFromExceptionListIdsProps - extends GetExceptionFilterOptionalProps { - http: HttpStart; - exceptionListIds: ExceptionListId[]; -} - -export interface GetExceptionFilterFromExceptionsProps extends GetExceptionFilterOptionalProps { - http: HttpStart; - exceptions: Array; -} - -export interface ExceptionFilterResponse { - filter: Filter; -} diff --git a/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json b/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json deleted file mode 100644 index 706aa6e81fc5..000000000000 --- a/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/securitysolution-io-ts-types", - "@kbn/securitysolution-io-ts-utils", - "@kbn/securitysolution-list-constants", - "@kbn/es-query", - "@kbn/core-http-browser", - "@kbn/core-notifications-browser", - "@kbn/securitysolution-exceptions-common" - ], - "exclude": ["target/**/*"] -} diff --git a/packages/kbn-securitysolution-io-ts-types/jest.config.js b/packages/kbn-securitysolution-io-ts-types/jest.config.js deleted file mode 100644 index c6efe620b09f..000000000000 --- a/packages/kbn-securitysolution-io-ts-types/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-io-ts-types'], -}; diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_uuid/index.test.ts b/packages/kbn-securitysolution-io-ts-types/src/default_uuid/index.test.ts deleted file mode 100644 index c429529167e5..000000000000 --- a/packages/kbn-securitysolution-io-ts-types/src/default_uuid/index.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { DefaultUuid } from '.'; -import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/packages/kbn-securitysolution-io-ts-types/tsconfig.json b/packages/kbn-securitysolution-io-ts-types/tsconfig.json deleted file mode 100644 index 25b82d38b7dc..000000000000 --- a/packages/kbn-securitysolution-io-ts-types/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/securitysolution-io-ts-utils" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-io-ts-utils/jest.config.js b/packages/kbn-securitysolution-io-ts-utils/jest.config.js deleted file mode 100644 index 457ac315951b..000000000000 --- a/packages/kbn-securitysolution-io-ts-utils/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-io-ts-utils'], -}; diff --git a/packages/kbn-securitysolution-io-ts-utils/tsconfig.json b/packages/kbn-securitysolution-io-ts-utils/tsconfig.json deleted file mode 100644 index 13f8244edd1a..000000000000 --- a/packages/kbn-securitysolution-io-ts-utils/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/datemath" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-list-api/index.ts b/packages/kbn-securitysolution-list-api/index.ts deleted file mode 100644 index fc434f01c7ec..000000000000 --- a/packages/kbn-securitysolution-list-api/index.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/api'; -export * from './src/fp_utils'; -export * from './src/list_api'; -export * from './src/list_item_api'; -export * from './src/types'; diff --git a/packages/kbn-securitysolution-list-api/jest.config.js b/packages/kbn-securitysolution-list-api/jest.config.js deleted file mode 100644 index 434cef2b7ca3..000000000000 --- a/packages/kbn-securitysolution-list-api/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-list-api'], -}; diff --git a/packages/kbn-securitysolution-list-api/package.json b/packages/kbn-securitysolution-list-api/package.json deleted file mode 100644 index bcb7a79accdc..000000000000 --- a/packages/kbn-securitysolution-list-api/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@kbn/securitysolution-list-api", - "version": "1.0.0", - "description": "security solution list REST API", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-list-api/src/api/index.ts b/packages/kbn-securitysolution-list-api/src/api/index.ts deleted file mode 100644 index 4bd188672e5a..000000000000 --- a/packages/kbn-securitysolution-list-api/src/api/index.ts +++ /dev/null @@ -1,666 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { chain, fromEither, tryCatch } from 'fp-ts/lib/TaskEither'; -import { flow } from 'fp-ts/lib/function'; -import { validateEither } from '@kbn/securitysolution-io-ts-utils'; -import { - CreateEndpointListSchema, - ExceptionListItemSchema, - ExceptionListSchema, - FoundExceptionListItemSchema, - FoundExceptionListSchema, - createEndpointListSchema, - exceptionListItemSchema, - exceptionListSchema, - foundExceptionListItemSchema, - foundExceptionListSchema, - AddEndpointExceptionListProps, - AddExceptionListItemProps, - AddExceptionListProps, - ApiCallByIdProps, - ApiCallByListIdProps, - ApiCallFetchExceptionListsProps, - ExportExceptionListProps, - UpdateExceptionListItemProps, - UpdateExceptionListProps, - GetExceptionFilterFromExceptionListIdsProps, - GetExceptionFilterFromExceptionsProps, - ExceptionFilterResponse, - DuplicateExceptionListProps, -} from '@kbn/securitysolution-io-ts-list-types'; - -import { - ENDPOINT_LIST_URL, - INTERNAL_EXCEPTION_FILTER, - EXCEPTION_LIST_ITEM_URL, - EXCEPTION_LIST_URL, -} from '@kbn/securitysolution-list-constants'; -import { toError, toPromise } from '../fp_utils'; - -const version = '2023-10-31'; - -/** - * Add new ExceptionList - * - * @param http Kibana http service - * @param list exception list to add - * @param signal to cancel request - * - * @throws An error if response is not OK - * - */ -const addExceptionList = async ({ - http, - list, - signal, -}: AddExceptionListProps): Promise => - http.fetch(EXCEPTION_LIST_URL, { - body: JSON.stringify(list), - method: 'POST', - signal, - version, - }); - -const addExceptionListWithValidation = async ({ - http, - list, - signal, -}: AddExceptionListProps): Promise => - flow( - () => - tryCatch( - () => - addExceptionList({ - http, - list, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(exceptionListSchema, response))), - flow(toPromise) - )(); - -export { addExceptionListWithValidation as addExceptionList }; - -/** - * Add new ExceptionListItem - * - * @param http Kibana http service - * @param listItem exception list item to add - * @param signal to cancel request - * - * @throws An error if response is not OK - * - */ -const addExceptionListItem = async ({ - http, - listItem, - signal, -}: AddExceptionListItemProps): Promise => - http.fetch(EXCEPTION_LIST_ITEM_URL, { - body: JSON.stringify(listItem), - method: 'POST', - signal, - version, - }); - -const addExceptionListItemWithValidation = async ({ - http, - listItem, - signal, -}: AddExceptionListItemProps): Promise => - flow( - () => - tryCatch( - () => - addExceptionListItem({ - http, - listItem, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), - flow(toPromise) - )(); - -export { addExceptionListItemWithValidation as addExceptionListItem }; - -/** - * Update existing ExceptionList - * - * @param http Kibana http service - * @param list exception list to add - * @param signal to cancel request - * - * @throws An error if response is not OK - * - */ -const updateExceptionList = async ({ - http, - list, - signal, -}: UpdateExceptionListProps): Promise => - http.fetch(EXCEPTION_LIST_URL, { - body: JSON.stringify(list), - method: 'PUT', - signal, - version, - }); - -const updateExceptionListWithValidation = async ({ - http, - list, - signal, -}: UpdateExceptionListProps): Promise => - flow( - () => - tryCatch( - () => - updateExceptionList({ - http, - list, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(exceptionListSchema, response))), - flow(toPromise) - )(); - -export { updateExceptionListWithValidation as updateExceptionList }; - -/** - * Update existing ExceptionListItem - * - * @param http Kibana http service - * @param listItem exception list item to add - * @param signal to cancel request - * - * @throws An error if response is not OK - * - */ -const updateExceptionListItem = async ({ - http, - listItem, - signal, -}: UpdateExceptionListItemProps): Promise => - http.fetch(EXCEPTION_LIST_ITEM_URL, { - body: JSON.stringify(listItem), - method: 'PUT', - signal, - version, - }); - -const updateExceptionListItemWithValidation = async ({ - http, - listItem, - signal, -}: UpdateExceptionListItemProps): Promise => - flow( - () => - tryCatch( - () => - updateExceptionListItem({ - http, - listItem, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), - flow(toPromise) - )(); - -export { updateExceptionListItemWithValidation as updateExceptionListItem }; - -/** - * Fetch all ExceptionLists (optionally by namespaceType) - * - * @param http Kibana http service - * @param namespaceTypes ExceptionList namespace_types of lists to find - * @param filters search bar filters - * @param pagination optional - * @param signal to cancel request - * - * @throws An error if request params or response is not OK - */ -const fetchExceptionLists = async ({ - http, - filters, - namespaceTypes, - pagination, - signal, - sort, -}: ApiCallFetchExceptionListsProps): Promise => { - const query = { - filter: filters || undefined, - namespace_type: namespaceTypes, - page: pagination.page ? `${pagination.page}` : '1', - per_page: pagination.perPage ? `${pagination.perPage}` : '20', - sort_field: sort?.field ? sort?.field : 'exception-list.created_at', - sort_order: sort?.order ? sort?.order : 'desc', - }; - - return http.fetch(`${EXCEPTION_LIST_URL}/_find`, { - method: 'GET', - query, - signal, - version, - }); -}; - -const fetchExceptionListsWithValidation = async ({ - filters, - http, - namespaceTypes, - pagination, - signal, - sort, -}: ApiCallFetchExceptionListsProps): Promise => - flow( - () => - tryCatch( - () => - fetchExceptionLists({ - filters, - http, - namespaceTypes, - pagination, - signal, - sort, - }), - toError - ), - chain((response) => fromEither(validateEither(foundExceptionListSchema, response))), - flow(toPromise) - )(); - -export { fetchExceptionListsWithValidation as fetchExceptionLists }; - -/** - * Fetch an ExceptionList by providing a ExceptionList ID - * - * @param http Kibana http service - * @param id ExceptionList ID (not list_id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -const fetchExceptionListById = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - http.fetch(EXCEPTION_LIST_URL, { - method: 'GET', - query: { id, namespace_type: namespaceType }, - signal, - version, - }); - -const fetchExceptionListByIdWithValidation = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - flow( - () => - tryCatch( - () => - fetchExceptionListById({ - http, - id, - namespaceType, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(exceptionListSchema, response))), - flow(toPromise) - )(); - -export { fetchExceptionListByIdWithValidation as fetchExceptionListById }; - -/** - * Fetch an ExceptionList's ExceptionItems by providing a ExceptionList list_id - * - * @param http Kibana http service - * @param listIds ExceptionList list_ids (not ID) - * @param namespaceTypes ExceptionList namespace_types - * @param search optional - simple search string - * @param filter optional - * @param pagination optional - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -const fetchExceptionListsItemsByListIds = async ({ - http, - listIds, - namespaceTypes, - filter, - pagination, - search, - signal, -}: ApiCallByListIdProps): Promise => { - const query = { - list_id: listIds.join(','), - namespace_type: namespaceTypes.join(','), - page: pagination.page ? `${pagination.page}` : '1', - per_page: pagination.perPage ? `${pagination.perPage}` : '20', - search, - sort_field: 'exception-list.created_at', - sort_order: 'desc', - filter, - }; - - return http.fetch(`${EXCEPTION_LIST_ITEM_URL}/_find`, { - method: 'GET', - query, - signal, - version, - }); -}; - -const fetchExceptionListsItemsByListIdsWithValidation = async ({ - filter, - http, - listIds, - namespaceTypes, - pagination, - search, - signal, -}: ApiCallByListIdProps): Promise => - flow( - () => - tryCatch( - () => - fetchExceptionListsItemsByListIds({ - filter, - http, - listIds, - namespaceTypes, - pagination, - search, - signal, - }), - toError - ), - chain((response) => fromEither(validateEither(foundExceptionListItemSchema, response))), - flow(toPromise) - )(); - -export { fetchExceptionListsItemsByListIdsWithValidation as fetchExceptionListsItemsByListIds }; - -/** - * Fetch an ExceptionListItem by providing a ExceptionListItem ID - * - * @param http Kibana http service - * @param id ExceptionListItem ID (not item_id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -const fetchExceptionListItemById = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - http.fetch(EXCEPTION_LIST_ITEM_URL, { - method: 'GET', - query: { id, namespace_type: namespaceType }, - signal, - version, - }); - -const fetchExceptionListItemByIdWithValidation = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - flow( - () => tryCatch(() => fetchExceptionListItemById({ http, id, namespaceType, signal }), toError), - chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), - flow(toPromise) - )(); - -export { fetchExceptionListItemByIdWithValidation as fetchExceptionListItemById }; - -/** - * Delete an ExceptionList by providing a ExceptionList ID - * - * @param http Kibana http service - * @param id ExceptionList ID (not list_id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -const deleteExceptionListById = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - http.fetch(EXCEPTION_LIST_URL, { - method: 'DELETE', - query: { id, namespace_type: namespaceType }, - signal, - version, - }); - -const deleteExceptionListByIdWithValidation = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - flow( - () => tryCatch(() => deleteExceptionListById({ http, id, namespaceType, signal }), toError), - chain((response) => fromEither(validateEither(exceptionListSchema, response))), - flow(toPromise) - )(); - -export { deleteExceptionListByIdWithValidation as deleteExceptionListById }; - -/** - * Delete an ExceptionListItem by providing a ExceptionListItem ID - * - * @param http Kibana http service - * @param id ExceptionListItem ID (not item_id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -const deleteExceptionListItemById = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - http.fetch(EXCEPTION_LIST_ITEM_URL, { - method: 'DELETE', - query: { id, namespace_type: namespaceType }, - signal, - version, - }); - -const deleteExceptionListItemByIdWithValidation = async ({ - http, - id, - namespaceType, - signal, -}: ApiCallByIdProps): Promise => - flow( - () => tryCatch(() => deleteExceptionListItemById({ http, id, namespaceType, signal }), toError), - chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), - flow(toPromise) - )(); - -export { deleteExceptionListItemByIdWithValidation as deleteExceptionListItemById }; - -/** - * Add new Endpoint ExceptionList - * - * @param http Kibana http service - * @param signal to cancel request - * - * @throws An error if response is not OK - * - */ -const addEndpointExceptionList = async ({ - http, - signal, -}: AddEndpointExceptionListProps): Promise => - http.fetch(ENDPOINT_LIST_URL, { - method: 'POST', - signal, - version, - }); - -const addEndpointExceptionListWithValidation = async ({ - http, - signal, -}: AddEndpointExceptionListProps): Promise => - flow( - () => tryCatch(() => addEndpointExceptionList({ http, signal }), toError), - chain((response) => fromEither(validateEither(createEndpointListSchema, response))), - flow(toPromise) - )(); - -export { addEndpointExceptionListWithValidation as addEndpointExceptionList }; - -/** - * Export an ExceptionList by providing a ExceptionList ID - * - * @param http Kibana http service - * @param id ExceptionList ID (not list_id) - * @param includeExpiredExceptions boolean for including expired exceptions - * @param listId ExceptionList LIST_ID (not id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -export const exportExceptionList = async ({ - http, - id, - includeExpiredExceptions, - listId, - namespaceType, - signal, -}: ExportExceptionListProps): Promise => - http.fetch(`${EXCEPTION_LIST_URL}/_export`, { - method: 'POST', - query: { - id, - list_id: listId, - namespace_type: namespaceType, - include_expired_exceptions: includeExpiredExceptions, - }, - signal, - version, - }); - -/** - * Create a Filter query from an exception list id - * - * @param exceptionListId The id of the exception list from which create a Filter query - * @param signal AbortSignal for cancelling request - * - * @throws An error if response is not OK - */ -export const getExceptionFilterFromExceptionListIds = async ({ - alias, - chunkSize, - exceptionListIds, - excludeExceptions, - http, - signal, -}: GetExceptionFilterFromExceptionListIdsProps): Promise => - http.fetch(INTERNAL_EXCEPTION_FILTER, { - method: 'POST', - version: '1', - body: JSON.stringify({ - exception_list_ids: exceptionListIds, - type: 'exception_list_ids', - alias, - exclude_exceptions: excludeExceptions, - chunk_size: chunkSize, - }), - signal, - }); - -/** - * Create a Filter query from a list of exceptions - * - * @param exceptions Exception items to be made into a `Filter` query - * @param signal AbortSignal for cancelling request - * - * @throws An error if response is not OK - */ -export const getExceptionFilterFromExceptions = async ({ - exceptions, - alias, - excludeExceptions, - http, - chunkSize, - signal, -}: GetExceptionFilterFromExceptionsProps): Promise => - http.fetch(INTERNAL_EXCEPTION_FILTER, { - method: 'POST', - version: '1', - body: JSON.stringify({ - exceptions, - type: 'exception_items', - alias, - exclude_exceptions: excludeExceptions, - chunk_size: chunkSize, - }), - signal, - }); - -/** - * Duplicate an ExceptionList and its items by providing a ExceptionList list_id - * - * @param http Kibana http service - * @param includeExpiredExceptions boolean for including exception items with expired TTL - * @param listId ExceptionList LIST_ID (not id) - * @param namespaceType ExceptionList namespace_type - * @param signal to cancel request - * - * @throws An error if response is not OK - */ -export const duplicateExceptionList = async ({ - http, - includeExpiredExceptions, - listId, - namespaceType, - signal, -}: DuplicateExceptionListProps): Promise => - http.fetch(`${EXCEPTION_LIST_URL}/_duplicate`, { - method: 'POST', - query: { - list_id: listId, - namespace_type: namespaceType, - include_expired_exceptions: includeExpiredExceptions, - }, - signal, - version, - }); diff --git a/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.ts b/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.ts deleted file mode 100644 index 98872f45cb77..000000000000 --- a/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { tryCatch } from 'fp-ts/lib/TaskEither'; - -import { toPromise } from '.'; - -describe('toPromise', () => { - it('rejects with left if TaskEither is left', async () => { - const task = tryCatch(() => Promise.reject(new Error('whoops')), String); - - await expect(toPromise(task)).rejects.toEqual('Error: whoops'); - }); - - it('resolves with right if TaskEither is right', async () => { - const task = tryCatch(() => Promise.resolve('success'), String); - - await expect(toPromise(task)).resolves.toEqual('success'); - }); -}); diff --git a/packages/kbn-securitysolution-list-api/src/fp_utils/index.ts b/packages/kbn-securitysolution-list-api/src/fp_utils/index.ts deleted file mode 100644 index 5614a3e7cb8d..000000000000 --- a/packages/kbn-securitysolution-list-api/src/fp_utils/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { TaskEither } from 'fp-ts/lib/TaskEither'; -import { fold } from 'fp-ts/lib/Either'; - -// TODO: This is copied in a few other spots and probably should live within its own kbn package -// rather than living here. A package such as kbn-security-solution-fp-utils -export const toPromise = async (taskEither: TaskEither): Promise => - pipe( - await taskEither(), - fold( - (e) => Promise.reject(e), - (a) => Promise.resolve(a) - ) - ); - -export const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e))); diff --git a/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts b/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts deleted file mode 100644 index 6b8698a707aa..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts +++ /dev/null @@ -1,445 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { createListIndex, deleteList, exportList, findLists, importList, readListIndex } from '.'; -import { - ApiPayload, - DeleteListParams, - ExportListParams, - FindListsParams, - ImportListParams, -} from '../types'; - -import { HttpFetchOptions } from '@kbn/core-http-browser'; -import { httpServiceMock } from '@kbn/core-http-browser-mocks'; - -import { getFoundListSchemaMock } from './mocks/response/found_list_schema.mock'; -import { getListResponseMock } from './mocks/response/list_schema.mock'; -import { getListItemIndexExistSchemaResponseMock } from './mocks/response/list_item_index_exist_schema.mock'; -import { getAcknowledgeSchemaResponseMock } from './mocks/response/acknowledge_schema.mock'; - -describe('Value Lists API', () => { - let httpMock: ReturnType; - - beforeEach(() => { - httpMock = httpServiceMock.createStartContract(); - }); - describe('deleteList', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getListResponseMock()); - }); - - it('DELETEs specifying the id as a query parameter', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { - deleteReferences: false, - id: 'list-id', - ignoreReferences: true, - }; - await deleteList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists', - expect.objectContaining({ - method: 'DELETE', - query: { deleteReferences: false, id: 'list-id', ignoreReferences: true }, - }) - ); - }); - - it('rejects with an error if request payload is invalid (and does not make API call)', async () => { - const abortCtrl = new AbortController(); - const payload: Omit, 'id'> & { - id: number; - } = { id: 23 }; - - await expect( - deleteList({ - http: httpMock, - ...(payload as unknown as ApiPayload), - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "23" supplied to "id"')); - expect(httpMock.fetch).not.toHaveBeenCalled(); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { id: 'list-id' }; - const badResponse = { ...getListResponseMock(), id: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - deleteList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); - }); - }); - describe('findLists', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getFoundListSchemaMock()); - }); - - it('GETs from the lists endpoint', async () => { - const abortCtrl = new AbortController(); - await findLists({ - http: httpMock, - pageIndex: 1, - pageSize: 10, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/_find', - expect.objectContaining({ - method: 'GET', - }) - ); - }); - - it('sends pagination as query parameters', async () => { - const abortCtrl = new AbortController(); - await findLists({ - cursor: 'cursor', - http: httpMock, - pageIndex: 1, - pageSize: 10, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/_find', - expect.objectContaining({ - query: { - cursor: 'cursor', - page: 1, - per_page: 10, - }, - }) - ); - }); - - it('sends sort_field and sort_order as query parameters', async () => { - const abortCtrl = new AbortController(); - await findLists({ - cursor: 'cursor', - http: httpMock, - pageIndex: 1, - pageSize: 10, - signal: abortCtrl.signal, - sortField: 'created_at', - sortOrder: 'desc', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/_find', - expect.objectContaining({ - query: { - cursor: 'cursor', - page: 1, - per_page: 10, - sort_field: 'created_at', - sort_order: 'desc', - }, - }) - ); - }); - - it('rejects with an error if request payload is invalid (and does not make API call)', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { - pageIndex: 10, - pageSize: 0, - }; - - await expect( - findLists({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "0" supplied to "per_page"')); - expect(httpMock.fetch).not.toHaveBeenCalled(); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { - pageIndex: 1, - pageSize: 10, - }; - const badResponse = { ...getFoundListSchemaMock(), cursor: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - findLists({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "cursor"')); - }); - }); - describe('importList', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getListResponseMock()); - }); - - it('POSTs the file', async () => { - const abortCtrl = new AbortController(); - const file = new File([], 'name'); - - await importList({ - file, - http: httpMock, - listId: 'my_list', - signal: abortCtrl.signal, - type: 'keyword', - }); - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items/_import', - expect.objectContaining({ - method: 'POST', - }) - ); - - // httpmock's fetch signature is inferred incorrectly - const [[, { body }]] = httpMock.fetch.mock.calls as unknown as Array< - [unknown, HttpFetchOptions] - >; - const actualFile = (body as FormData).get('file'); - expect(actualFile).toEqual(file); - }); - - it('sends type and id as query parameters', async () => { - const abortCtrl = new AbortController(); - const file = new File([], 'name'); - - await importList({ - file, - http: httpMock, - listId: 'my_list', - signal: abortCtrl.signal, - type: 'keyword', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items/_import', - expect.objectContaining({ - query: { list_id: 'my_list', type: 'keyword' }, - }) - ); - }); - - it('rejects with an error if request body is invalid (and does not make API call)', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { - file: undefined as unknown as File, - listId: 'list-id', - type: 'ip', - }; - - await expect( - importList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "file"')); - expect(httpMock.fetch).not.toHaveBeenCalled(); - }); - - it('rejects with an error if request params are invalid (and does not make API call)', async () => { - const abortCtrl = new AbortController(); - const file = new File([], 'name'); - const payload: ApiPayload = { - file, - listId: 'list-id', - type: 'other' as 'ip', - }; - - await expect( - importList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "other" supplied to "type"')); - expect(httpMock.fetch).not.toHaveBeenCalled(); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const file = new File([], 'name'); - const payload: ApiPayload = { - file, - listId: 'list-id', - type: 'ip', - }; - const badResponse = { ...getListResponseMock(), id: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - importList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); - }); - }); - describe('exportList', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue({}); - }); - - it('POSTs to the export endpoint', async () => { - const abortCtrl = new AbortController(); - - await exportList({ - http: httpMock, - listId: 'my_list', - signal: abortCtrl.signal, - }); - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items/_export', - expect.objectContaining({ - method: 'POST', - }) - ); - }); - - it('sends type and id as query parameters', async () => { - const abortCtrl = new AbortController(); - - await exportList({ - http: httpMock, - listId: 'my_list', - signal: abortCtrl.signal, - }); - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items/_export', - expect.objectContaining({ - query: { list_id: 'my_list' }, - }) - ); - }); - - it('rejects with an error if request params are invalid (and does not make API call)', async () => { - const abortCtrl = new AbortController(); - const payload: ApiPayload = { - listId: 23 as unknown as string, - }; - - await expect( - exportList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "23" supplied to "list_id"')); - expect(httpMock.fetch).not.toHaveBeenCalled(); - }); - }); - - describe('readListIndex', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getListItemIndexExistSchemaResponseMock()); - }); - - it('GETs the list index', async () => { - const abortCtrl = new AbortController(); - await readListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/index', - expect.objectContaining({ - method: 'GET', - }) - ); - }); - - it('returns the response when valid', async () => { - const abortCtrl = new AbortController(); - const result = await readListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }); - - expect(result).toEqual(getListItemIndexExistSchemaResponseMock()); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const badResponse = { ...getListItemIndexExistSchemaResponseMock(), list_index: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - readListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "list_index"')); - }); - }); - - describe('createListIndex', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getAcknowledgeSchemaResponseMock()); - }); - - it('GETs the list index', async () => { - const abortCtrl = new AbortController(); - await createListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/index', - expect.objectContaining({ - method: 'POST', - }) - ); - }); - - it('returns the response when valid', async () => { - const abortCtrl = new AbortController(); - const result = await createListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }); - - expect(result).toEqual(getAcknowledgeSchemaResponseMock()); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const badResponse = { acknowledged: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - createListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "acknowledged"')); - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_api/index.ts b/packages/kbn-securitysolution-list-api/src/list_api/index.ts deleted file mode 100644 index 3087ed5333cc..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/index.ts +++ /dev/null @@ -1,344 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { chain, fromEither, map, tryCatch } from 'fp-ts/lib/TaskEither'; -import { flow } from 'fp-ts/lib/function'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { validateEither } from '@kbn/securitysolution-io-ts-utils'; -import { - AcknowledgeSchema, - DeleteListSchemaEncoded, - ExportListItemQuerySchemaEncoded, - FindListSchemaEncoded, - FoundListSchema, - ImportListItemQuerySchemaEncoded, - ImportListItemSchemaEncoded, - ListItemIndexExistSchema, - ListSchema, - ReadListSchema, - acknowledgeSchema, - deleteListSchema, - readListSchema, - exportListItemQuerySchema, - findListSchema, - foundListSchema, - importListItemQuerySchema, - importListItemSchema, - listItemIndexExistSchema, - listSchema, - foundListsBySizeSchema, - FoundListsBySizeSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { - LIST_INDEX, - LIST_ITEM_URL, - LIST_PRIVILEGES_URL, - LIST_URL, - INTERNAL_FIND_LISTS_BY_SIZE, -} from '@kbn/securitysolution-list-constants'; -import { toError, toPromise } from '../fp_utils'; - -import { - ApiParams, - DeleteListParams, - ExportListParams, - FindListsParams, - ImportListParams, - GetListByIdParams, -} from '../types'; - -export type { - ApiParams, - DeleteListParams, - ExportListParams, - FindListsParams, - ImportListParams, -} from '../types'; - -const version = '2023-10-31'; - -const findLists = async ({ - http, - cursor, - page, - // eslint-disable-next-line @typescript-eslint/naming-convention - per_page, - signal, - // eslint-disable-next-line @typescript-eslint/naming-convention - sort_field, - // eslint-disable-next-line @typescript-eslint/naming-convention - sort_order, -}: ApiParams & FindListSchemaEncoded): Promise => { - return http.fetch(`${LIST_URL}/_find`, { - method: 'GET', - query: { - cursor, - page, - per_page, - sort_field, - sort_order, - }, - signal, - version, - }); -}; - -const findListsWithValidation = async ({ - cursor, - http, - pageIndex, - pageSize, - signal, - sortField, - sortOrder, -}: FindListsParams): Promise => - pipe( - { - cursor: cursor != null ? cursor.toString() : undefined, - page: pageIndex != null ? pageIndex.toString() : undefined, - per_page: pageSize != null ? pageSize.toString() : undefined, - sort_field: sortField != null ? sortField.toString() : undefined, - sort_order: sortOrder, - }, - (payload) => fromEither(validateEither(findListSchema, payload)), - chain((payload) => tryCatch(() => findLists({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(foundListSchema, response))), - flow(toPromise) - ); - -export { findListsWithValidation as findLists }; - -const findListsBySize = async ({ - http, - cursor, - page, - // eslint-disable-next-line @typescript-eslint/naming-convention - per_page, - signal, -}: ApiParams & FindListSchemaEncoded): Promise => { - return http.fetch(`${INTERNAL_FIND_LISTS_BY_SIZE}`, { - method: 'GET', - version: '1', - query: { - cursor, - page, - per_page, - }, - signal, - }); -}; - -const findListsBySizeWithValidation = async ({ - cursor, - http, - pageIndex, - pageSize, - signal, -}: FindListsParams): Promise => - pipe( - { - cursor: cursor != null ? cursor.toString() : undefined, - page: pageIndex != null ? pageIndex.toString() : undefined, - per_page: pageSize != null ? pageSize.toString() : undefined, - }, - (payload) => fromEither(validateEither(findListSchema, payload)), - chain((payload) => tryCatch(() => findListsBySize({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(foundListsBySizeSchema, response))), - flow(toPromise) - ); - -export { findListsBySizeWithValidation as findListsBySize }; - -const importList = async ({ - file, - http, - // eslint-disable-next-line @typescript-eslint/naming-convention - list_id, - type, - signal, - refresh, -}: ApiParams & - ImportListItemSchemaEncoded & - ImportListItemQuerySchemaEncoded): Promise => { - const formData = new FormData(); - formData.append('file', file as Blob); - - return http.fetch(`${LIST_ITEM_URL}/_import`, { - body: formData, - headers: { 'Content-Type': undefined }, - method: 'POST', - query: { list_id, type, refresh }, - signal, - version, - }); -}; - -const importListWithValidation = async ({ - file, - http, - listId, - type, - signal, - refresh, -}: ImportListParams): Promise => - pipe( - { - list_id: listId, - type, - refresh, - }, - (query) => fromEither(validateEither(importListItemQuerySchema, query)), - chain((query) => - pipe( - fromEither(validateEither(importListItemSchema, { file })), - map((body) => ({ ...body, ...query })) - ) - ), - chain((payload) => tryCatch(() => importList({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(listSchema, response))), - toPromise - ); - -export { importListWithValidation as importList }; - -const deleteList = async ({ - deleteReferences = false, - http, - id, - ignoreReferences = false, - signal, -}: ApiParams & DeleteListSchemaEncoded): Promise => - http.fetch(LIST_URL, { - method: 'DELETE', - query: { deleteReferences, id, ignoreReferences }, - signal, - version, - }); - -const deleteListWithValidation = async ({ - deleteReferences, - http, - id, - ignoreReferences, - signal, -}: DeleteListParams): Promise => - pipe( - { deleteReferences, id, ignoreReferences }, - (payload) => fromEither(validateEither(deleteListSchema, payload)), - chain((payload) => tryCatch(() => deleteList({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(listSchema, response))), - flow(toPromise) - ); - -export { deleteListWithValidation as deleteList }; - -const exportList = async ({ - http, - // eslint-disable-next-line @typescript-eslint/naming-convention - list_id, - signal, -}: ApiParams & ExportListItemQuerySchemaEncoded): Promise => - http.fetch(`${LIST_ITEM_URL}/_export`, { - method: 'POST', - query: { list_id }, - signal, - version, - }); - -const exportListWithValidation = async ({ - http, - listId, - signal, -}: ExportListParams): Promise => - pipe( - { list_id: listId }, - (payload) => fromEither(validateEither(exportListItemQuerySchema, payload)), - chain((payload) => tryCatch(() => exportList({ http, signal, ...payload }), toError)), - flow(toPromise) - ); - -export { exportListWithValidation as exportList }; - -const readListIndex = async ({ http, signal }: ApiParams): Promise => - http.fetch(LIST_INDEX, { - method: 'GET', - signal, - version, - }); - -const readListIndexWithValidation = async ({ - http, - signal, -}: ApiParams): Promise => - flow( - () => tryCatch(() => readListIndex({ http, signal }), toError), - chain((response) => fromEither(validateEither(listItemIndexExistSchema, response))), - flow(toPromise) - )(); - -export { readListIndexWithValidation as readListIndex }; - -// TODO add types and validation -export const readListPrivileges = async ({ http, signal }: ApiParams): Promise => - http.fetch(LIST_PRIVILEGES_URL, { - method: 'GET', - signal, - version, - }); - -const createListIndex = async ({ http, signal }: ApiParams): Promise => - http.fetch(LIST_INDEX, { - method: 'POST', - signal, - version, - }); - -const createListIndexWithValidation = async ({ - http, - signal, -}: ApiParams): Promise => - flow( - () => tryCatch(() => createListIndex({ http, signal }), toError), - chain((response) => fromEither(validateEither(acknowledgeSchema, response))), - flow(toPromise) - )(); - -export { createListIndexWithValidation as createListIndex }; - -const getListById = async ({ - http, - signal, - id, -}: ApiParams & ReadListSchema): Promise => { - return http.fetch(`${LIST_URL}`, { - method: 'GET', - query: { - id, - }, - signal, - version, - }); -}; - -const getListByIdWithValidation = async ({ - http, - signal, - id, -}: GetListByIdParams): Promise => - pipe( - { - id, - }, - (payload) => fromEither(validateEither(readListSchema, payload)), - chain((payload) => tryCatch(() => getListById({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(listSchema, response))), - flow(toPromise) - ); - -export { getListByIdWithValidation as getListById }; diff --git a/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.ts b/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.ts deleted file mode 100644 index 3043cc70642c..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const DATE_NOW = '2020-04-20T15:25:31.830Z'; -export const USER = 'some user'; -export const ELASTIC_USER = 'elastic'; -export const NAME = 'some name'; -export const DESCRIPTION = 'some description'; -export const LIST_ID = 'some-list-id'; -export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; - -export const META = {}; -export const TYPE = 'ip'; - -export const VERSION = 1; -export const IMMUTABLE = false; diff --git a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/acknowledge_schema.mock.ts b/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/acknowledge_schema.mock.ts deleted file mode 100644 index 788fab714e2d..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/acknowledge_schema.mock.ts +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { AcknowledgeSchema } from '@kbn/securitysolution-io-ts-list-types'; - -export const getAcknowledgeSchemaResponseMock = (): AcknowledgeSchema => ({ - acknowledged: true, -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/found_list_schema.mock.ts b/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/found_list_schema.mock.ts deleted file mode 100644 index 436ddcd7a83d..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/found_list_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { FoundListSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { getListResponseMock } from './list_schema.mock'; - -export const getFoundListSchemaMock = (): FoundListSchema => ({ - cursor: '123', - data: [getListResponseMock()], - page: 1, - per_page: 1, - total: 1, -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_item_index_exist_schema.mock.ts b/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_item_index_exist_schema.mock.ts deleted file mode 100644 index 27a54a5fd96f..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_item_index_exist_schema.mock.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ListItemIndexExistSchema } from '@kbn/securitysolution-io-ts-list-types'; - -export const getListItemIndexExistSchemaResponseMock = (): ListItemIndexExistSchema => ({ - list_index: true, - list_item_index: true, -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.ts b/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.ts deleted file mode 100644 index 79ed25641977..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - IMMUTABLE, - LIST_ID, - META, - NAME, - TIE_BREAKER, - TYPE, - USER, - VERSION, -} from '../constants.mock'; - -export const getListResponseMock = (): ListSchema => ({ - '@timestamp': DATE_NOW, - _version: undefined, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - deserializer: undefined, - id: LIST_ID, - immutable: IMMUTABLE, - meta: META, - name: NAME, - serializer: undefined, - tie_breaker_id: TIE_BREAKER, - type: TYPE, - updated_at: DATE_NOW, - updated_by: USER, - version: VERSION, -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - created_by: ELASTIC_USER, - description: DESCRIPTION, - immutable: IMMUTABLE, - name: NAME, - type: TYPE, - updated_by: ELASTIC_USER, - version: VERSION, -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts b/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts deleted file mode 100644 index 95e37ec43410..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts +++ /dev/null @@ -1,173 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { createListItem, deleteListItem, findListItems, patchListItem } from '.'; -import { httpServiceMock } from '@kbn/core-http-browser-mocks'; -import { - getFoundListSchemaMock, - getCreateListItemResponseMock, - getUpdatedListItemResponseMock, - getDeletedListItemResponseMock, -} from './mocks/response'; - -describe('Value list item API', () => { - let httpMock: ReturnType; - beforeEach(() => { - httpMock = httpServiceMock.createStartContract(); - }); - - describe('findListItems', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getFoundListSchemaMock()); - }); - - it('GETs from the lists endpoint with query params', async () => { - const abortCtrl = new AbortController(); - await findListItems({ - http: httpMock, - pageIndex: 1, - pageSize: 10, - signal: abortCtrl.signal, - filter: '*:*', - listId: 'list_id', - sortField: 'updated_at', - sortOrder: 'asc', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items/_find', - expect.objectContaining({ - method: 'GET', - query: { - cursor: undefined, - filter: '*:*', - list_id: 'list_id', - page: 1, - per_page: 10, - sort_field: 'updated_at', - sort_order: 'asc', - }, - }) - ); - }); - }); - - describe('createListItem', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getCreateListItemResponseMock()); - }); - - it('POSTs to the lists endpoint with the list item', async () => { - const abortCtrl = new AbortController(); - await createListItem({ - http: httpMock, - signal: abortCtrl.signal, - value: '123', - listId: 'list_id', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items', - expect.objectContaining({ - method: 'POST', - body: JSON.stringify({ - value: '123', - list_id: 'list_id', - }), - }) - ); - }); - - it('returns the created list item', async () => { - const abortCtrl = new AbortController(); - const result = await createListItem({ - http: httpMock, - signal: abortCtrl.signal, - value: '123', - listId: 'list_id', - }); - - expect(result).toEqual(getCreateListItemResponseMock()); - }); - }); - - describe('patchListItem', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getUpdatedListItemResponseMock()); - }); - - it('PATCH to the lists endpoint with the list item', async () => { - const abortCtrl = new AbortController(); - await patchListItem({ - http: httpMock, - signal: abortCtrl.signal, - id: 'item_id', - value: '123', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items', - expect.objectContaining({ - method: 'PATCH', - body: JSON.stringify({ - id: 'item_id', - value: '123', - }), - }) - ); - }); - - it('returns the updated list item', async () => { - const abortCtrl = new AbortController(); - const result = await patchListItem({ - http: httpMock, - signal: abortCtrl.signal, - id: 'item_id', - value: '123', - }); - - expect(result).toEqual(getUpdatedListItemResponseMock()); - }); - }); - - describe('deleteListItem', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getCreateListItemResponseMock()); - }); - - it('DELETE to the lists endpoint with the list item', async () => { - const abortCtrl = new AbortController(); - await deleteListItem({ - http: httpMock, - signal: abortCtrl.signal, - id: 'item_id', - refresh: 'true', - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/items', - expect.objectContaining({ - method: 'DELETE', - query: { id: 'item_id', refresh: 'true' }, - }) - ); - }); - - it('returns the deleted list item', async () => { - const abortCtrl = new AbortController(); - const result = await deleteListItem({ - http: httpMock, - signal: abortCtrl.signal, - id: 'item_id', - }); - - expect(result).toEqual(getDeletedListItemResponseMock()); - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts b/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts deleted file mode 100644 index 8c6cdc358f70..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts +++ /dev/null @@ -1,227 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - FindListItemSchema, - ListItemSchema, - deleteListItemSchema, - patchListItemSchema, - createListItemSchema, - findListItemSchema, - foundListItemSchema, - listItemSchema, - FoundListItemSchema, - DeleteListItemSchema, - PatchListItemSchema, - CreateListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { chain, fromEither, tryCatch } from 'fp-ts/lib/TaskEither'; -import { flow } from 'fp-ts/lib/function'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { validateEither } from '@kbn/securitysolution-io-ts-utils'; - -import { LIST_ITEM_URL } from '@kbn/securitysolution-list-constants'; -import { - ApiParams, - FindListItemsParams, - DeleteListItemParams, - PatchListItemParams, - CreateListItemParams, -} from '../types'; -import { toError, toPromise } from '../fp_utils'; - -const version = '2023-10-31'; - -/** - * Fetch list items - */ -const findListItems = async ({ - http, - cursor, - page, - // eslint-disable-next-line @typescript-eslint/naming-convention - list_id, - // eslint-disable-next-line @typescript-eslint/naming-convention - per_page, - signal, - // eslint-disable-next-line @typescript-eslint/naming-convention - sort_field, - // eslint-disable-next-line @typescript-eslint/naming-convention - sort_order, - filter, -}: ApiParams & FindListItemSchema): Promise => { - return http.fetch(`${LIST_ITEM_URL}/_find`, { - method: 'GET', - query: { - cursor, - page, - per_page, - sort_field, - sort_order, - list_id, - filter, - }, - signal, - version, - }); -}; - -const findListItemsWithValidation = async ({ - cursor, - http, - pageIndex, - pageSize, - signal, - sortField, - sortOrder, - filter, - listId, -}: FindListItemsParams): Promise => - pipe( - { - cursor: cursor != null ? cursor.toString() : undefined, - page: pageIndex != null ? pageIndex.toString() : undefined, - per_page: pageSize != null ? pageSize.toString() : undefined, - sort_field: sortField != null ? sortField.toString() : undefined, - filter: filter != null ? filter.toString() : undefined, - sort_order: sortOrder, - list_id: listId, - }, - (payload) => fromEither(validateEither(findListItemSchema, payload)), - chain((payload) => tryCatch(() => findListItems({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(foundListItemSchema, response))), - flow(toPromise) - ); - -export { findListItemsWithValidation as findListItems }; - -const deleteListItem = async ({ - http, - id, - signal, - refresh, -}: ApiParams & DeleteListItemSchema): Promise => - http.fetch(LIST_ITEM_URL, { - method: 'DELETE', - query: { id, refresh }, - signal, - version, - }); - -const deleteListItemWithValidation = async ({ - http, - id, - signal, - refresh, -}: DeleteListItemParams): Promise => - pipe( - { id, refresh }, - (payload) => fromEither(validateEither(deleteListItemSchema, payload)), - chain((payload) => - tryCatch( - () => - deleteListItem({ - http, - signal, - ...payload, - value: undefined, - list_id: undefined, - }), - toError - ) - ), - chain((response) => fromEither(validateEither(listItemSchema, response))), - flow(toPromise) - ); - -export { deleteListItemWithValidation as deleteListItem }; - -const patchListItem = async ({ - http, - id, - signal, - value, - _version, -}: ApiParams & PatchListItemSchema): Promise => - http.fetch(LIST_ITEM_URL, { - method: 'PATCH', - body: JSON.stringify({ id, value, _version }), - signal, - version, - }); - -const patchListItemWithValidation = async ({ - http, - id, - signal, - value, - refresh, - _version, -}: PatchListItemParams): Promise => - pipe( - { id, value, _version, refresh }, - (payload) => fromEither(validateEither(patchListItemSchema, payload)), - chain((payload) => - tryCatch( - () => - patchListItem({ - http, - signal, - ...payload, - }), - toError - ) - ), - chain((response) => fromEither(validateEither(listItemSchema, response))), - flow(toPromise) - ); - -export { patchListItemWithValidation as patchListItem }; - -const createListItem = async ({ - http, - signal, - value, - // eslint-disable-next-line @typescript-eslint/naming-convention - list_id, - refresh, -}: ApiParams & CreateListItemSchema): Promise => - http.fetch(LIST_ITEM_URL, { - method: 'POST', - body: JSON.stringify({ value, list_id, refresh }), - signal, - version, - }); - -const createListItemWithValidation = async ({ - http, - signal, - value, - refresh, - listId, -}: CreateListItemParams): Promise => - pipe( - { list_id: listId, value, refresh }, - (payload) => fromEither(validateEither(createListItemSchema, payload)), - chain((payload) => - tryCatch( - () => - createListItem({ - http, - signal, - ...payload, - }), - toError - ) - ), - chain((response) => fromEither(validateEither(listItemSchema, response))), - flow(toPromise) - ); - -export { createListItemWithValidation as createListItem }; diff --git a/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/index.ts b/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/index.ts deleted file mode 100644 index 5ef4e52adbe8..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { FoundListItemSchema, ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { getListItemResponseMock } from './list_item_schema.mock'; - -export const getFoundListSchemaMock = (): FoundListItemSchema => ({ - cursor: '123', - data: [getListItemResponseMock()], - page: 1, - per_page: 1, - total: 1, -}); - -export const getCreateListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); -export const getUpdatedListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); -export const getDeletedListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); diff --git a/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.ts b/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.ts deleted file mode 100644 index eb67b9777354..000000000000 --- a/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -export const getListItemResponseMock = (): ListItemSchema => ({ - _version: '1', - '@timestamp': '2020-08-11T11:22:13.670Z', - created_at: '2020-08-11T11:22:13.670Z', - created_by: 'elastic', - deserializer: 'some deserializer', - id: 'bpdB3XMBx7pemMHopQ6M', - list_id: 'list_id', - meta: {}, - serializer: 'some serializer', - tie_breaker_id: '17d3befb-dc22-4b3c-a286-b5504c4fbeeb', - type: 'keyword', - updated_at: '2020-08-11T11:22:13.670Z', - updated_by: 'elastic', - value: 'some keyword', -}); diff --git a/packages/kbn-securitysolution-list-api/src/types.ts b/packages/kbn-securitysolution-list-api/src/types.ts deleted file mode 100644 index c78071bb5824..000000000000 --- a/packages/kbn-securitysolution-list-api/src/types.ts +++ /dev/null @@ -1,86 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { - SortFieldOrUndefined, - SortOrderOrUndefined, - Type, - Refresh, - RefreshWithWaitFor, -} from '@kbn/securitysolution-io-ts-list-types'; - -// TODO: Replace these with kbn packaged versions once we have those available to us -// These originally came from this location below before moving them to this hacked "any" types: -// import { HttpStart, NotificationsStart } from '../../../../../src/core/public'; -interface HttpStart { - fetch: (...args: any) => any; -} - -export interface ApiParams { - http: HttpStart; - signal: AbortSignal; -} -export type ApiPayload = Omit; - -export interface FindListsParams extends ApiParams { - cursor?: string | undefined; - pageSize: number | undefined; - pageIndex: number | undefined; - sortOrder?: SortOrderOrUndefined; - sortField?: SortFieldOrUndefined; -} - -export interface FindListItemsParams extends ApiParams { - cursor?: string | undefined; - pageSize: number | undefined; - pageIndex: number | undefined; - sortOrder?: SortOrderOrUndefined; - sortField?: SortFieldOrUndefined; - filter: string | undefined; - listId: string; -} - -export interface ImportListParams extends ApiParams { - file: File; - listId: string | undefined; - type: Type | undefined; - refresh?: RefreshWithWaitFor; -} - -export interface DeleteListParams extends ApiParams { - deleteReferences?: boolean; - id: string; - ignoreReferences?: boolean; -} - -export interface DeleteListItemParams extends ApiParams { - refresh?: Refresh; - id: string; -} - -export interface PatchListItemParams extends ApiParams { - refresh?: Refresh; - id: string; - value: string; - _version?: string; -} - -export interface CreateListItemParams extends ApiParams { - refresh?: RefreshWithWaitFor; - value: string; - listId: string; -} - -export interface ExportListParams extends ApiParams { - listId: string; -} - -export interface GetListByIdParams extends ApiParams { - id: string; -} diff --git a/packages/kbn-securitysolution-list-api/tsconfig.json b/packages/kbn-securitysolution-list-api/tsconfig.json deleted file mode 100644 index 2c2ca29316fc..000000000000 --- a/packages/kbn-securitysolution-list-api/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-io-ts-utils", - "@kbn/securitysolution-list-constants", - "@kbn/core-http-browser", - "@kbn/core-http-browser-mocks", - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-list-constants/index.ts b/packages/kbn-securitysolution-list-constants/index.ts deleted file mode 100644 index 6f1e8d01b830..000000000000 --- a/packages/kbn-securitysolution-list-constants/index.ts +++ /dev/null @@ -1,148 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { deepFreeze } from '@kbn/std'; - -/** - * Value list routes - */ -export const LIST_URL = '/api/lists'; -export const LIST_INDEX = `${LIST_URL}/index`; -export const LIST_ITEM_URL = `${LIST_URL}/items`; -export const LIST_PRIVILEGES_URL = `${LIST_URL}/privileges`; - -/** - * Internal value list routes - */ -export const INTERNAL_LIST_URL = '/internal/lists'; -export const INTERNAL_FIND_LISTS_BY_SIZE = `${INTERNAL_LIST_URL}/_find_lists_by_size` as const; -export const INTERNAL_EXCEPTION_FILTER = `${INTERNAL_LIST_URL}/_create_filter` as const; - -/** - * Exception list routes - */ -export const EXCEPTION_LIST_URL = '/api/exception_lists'; -export const EXCEPTION_LIST_ITEM_URL = '/api/exception_lists/items'; - -/** - * Internal exception list routes - */ -export const INTERNAL_EXCEPTION_LIST_URL = `/internal${EXCEPTION_LIST_URL}`; -export const INTERNAL_EXCEPTIONS_LIST_ENSURE_CREATED_URL = `${INTERNAL_EXCEPTION_LIST_URL}/_create`; - -/** - * Exception list spaces - */ -export const EXCEPTION_LIST_NAMESPACE_AGNOSTIC = 'exception-list-agnostic'; -export const EXCEPTION_LIST_NAMESPACE = 'exception-list'; - -/** - * Specific routes for the single global space agnostic endpoint list - */ -export const ENDPOINT_LIST_URL = '/api/endpoint_list'; - -/** - * Specific routes for the single global space agnostic endpoint list. These are convenience - * routes where they are going to try and create the global space agnostic endpoint list if it - * does not exist yet or if it was deleted at some point and re-create it before adding items to - * the list - */ -export const ENDPOINT_LIST_ITEM_URL = '/api/endpoint_list/items'; - -/** - * This ID is used for _both_ the Saved Object ID and for the list_id - * for the single global space agnostic endpoint list - */ -export const ENDPOINT_LIST_ID = 'endpoint_list'; - -/** The name of the single global space agnostic endpoint list */ -export const ENDPOINT_LIST_NAME = 'Endpoint Security Exception List'; - -/** The description of the single global space agnostic endpoint list */ -export const ENDPOINT_LIST_DESCRIPTION = 'Endpoint Security Exception List'; - -export const MAX_EXCEPTION_LIST_SIZE = 10000; - -export const MAXIMUM_SMALL_VALUE_LIST_SIZE = 65536; - -export const MAXIMUM_SMALL_IP_RANGE_VALUE_LIST_DASH_SIZE = 200; - -/** - * List definitions for Endpoint Artifact - */ -export const ENDPOINT_ARTIFACT_LISTS = deepFreeze({ - trustedApps: { - id: 'endpoint_trusted_apps', - name: 'Endpoint Security Trusted Apps List', - description: 'Endpoint Security Trusted Apps List', - }, - eventFilters: { - id: 'endpoint_event_filters', - name: 'Endpoint Security Event Filters List', - description: 'Endpoint Security Event Filters List', - }, - hostIsolationExceptions: { - id: 'endpoint_host_isolation_exceptions', - name: 'Endpoint Security Host isolation exceptions List', - description: 'Endpoint Security Host isolation exceptions List', - }, - blocklists: { - id: 'endpoint_blocklists', - name: 'Endpoint Security Blocklists List', - description: 'Endpoint Security Blocklists List', - }, -}); - -/** - * The IDs of all Endpoint artifact lists - */ -export const ENDPOINT_ARTIFACT_LIST_IDS = Object.freeze( - Object.values(ENDPOINT_ARTIFACT_LISTS).map(({ id }) => id) -); - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_TRUSTED_APPS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.trustedApps.id; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_TRUSTED_APPS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.trustedApps.name; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION = - ENDPOINT_ARTIFACT_LISTS.trustedApps.description; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_EVENT_FILTERS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.eventFilters.id; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_EVENT_FILTERS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.eventFilters.name; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_EVENT_FILTERS_LIST_DESCRIPTION = - ENDPOINT_ARTIFACT_LISTS.eventFilters.description; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID = - ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.id; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_NAME = - ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.name; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_DESCRIPTION = - ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.description; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_BLOCKLISTS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.blocklists.id; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_BLOCKLISTS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.blocklists.name; - -/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ -export const ENDPOINT_BLOCKLISTS_LIST_DESCRIPTION = ENDPOINT_ARTIFACT_LISTS.blocklists.description; diff --git a/packages/kbn-securitysolution-list-constants/package.json b/packages/kbn-securitysolution-list-constants/package.json deleted file mode 100644 index 1b03f95f0f15..000000000000 --- a/packages/kbn-securitysolution-list-constants/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@kbn/securitysolution-list-constants", - "version": "1.0.0", - "description": "security solution list constants to use across plugins such lists, security_solution, cases, etc...", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-list-constants/tsconfig.json b/packages/kbn-securitysolution-list-constants/tsconfig.json deleted file mode 100644 index 0cd8de173ed4..000000000000 --- a/packages/kbn-securitysolution-list-constants/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/std" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-list-hooks/index.ts b/packages/kbn-securitysolution-list-hooks/index.ts deleted file mode 100644 index 5ec2cb85d8c2..000000000000 --- a/packages/kbn-securitysolution-list-hooks/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/transforms'; -export * from './src/use_api'; -export * from './src/use_create_list_index'; -export * from './src/use_cursor'; -export * from './src/use_delete_list'; -export * from './src/use_exception_lists'; -export * from './src/use_export_list'; -export * from './src/use_find_lists'; -export * from './src/use_find_lists_by_size'; -export * from './src/use_import_list'; -export * from './src/use_persist_exception_item'; -export * from './src/use_persist_exception_list'; -export * from './src/use_read_list_index'; -export * from './src/use_read_list_privileges'; -export * from './src/use_find_list_items'; -export * from './src/use_create_list_item'; -export * from './src/use_delete_list_item'; -export * from './src/use_patch_list_item'; -export * from './src/use_get_list_by_id'; diff --git a/packages/kbn-securitysolution-list-hooks/jest.config.js b/packages/kbn-securitysolution-list-hooks/jest.config.js deleted file mode 100644 index f5fadd8bf399..000000000000 --- a/packages/kbn-securitysolution-list-hooks/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-list-hooks'], -}; diff --git a/packages/kbn-securitysolution-list-hooks/package.json b/packages/kbn-securitysolution-list-hooks/package.json deleted file mode 100644 index 3d9f2019d3f2..000000000000 --- a/packages/kbn-securitysolution-list-hooks/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-list-hooks", - "version": "1.0.0", - "description": "Security solution list ReactJS hooks", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-list-hooks/src/constants.ts b/packages/kbn-securitysolution-list-hooks/src/constants.ts deleted file mode 100644 index 333fb40ca4ca..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/constants.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const READ_INDEX_QUERY_KEY = ['detectionEngine', 'listIndex']; diff --git a/packages/kbn-securitysolution-list-hooks/src/index.ts b/packages/kbn-securitysolution-list-hooks/src/index.ts deleted file mode 100644 index 852d138b8931..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './transforms'; -export * from './use_api'; -export * from './use_create_list_index'; -export * from './use_cursor'; -export * from './use_delete_list'; -export * from './use_exception_lists'; -export * from './use_export_list'; -export * from './use_find_lists'; -export * from './use_import_list'; -export * from './use_persist_exception_item'; -export * from './use_persist_exception_list'; -export * from './use_read_list_index'; -export * from './use_read_list_privileges'; -export * from './use_find_list_items'; -export * from './use_create_list_item'; -export * from './use_delete_list_item'; -export * from './use_patch_list_item'; -export * from './use_get_list_by_id'; diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts b/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts deleted file mode 100644 index 67dcac046c8d..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts +++ /dev/null @@ -1,101 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - CommentsArray, - EntriesArray, - Entry, - EntryMatch, - EntryNested, - OsTypeArray, -} from '@kbn/securitysolution-io-ts-list-types'; - -export const DATE_NOW = '2020-04-20T15:25:31.830Z'; -export const USER = 'some user'; -export const ELASTIC_USER = 'elastic'; -export const NAME = 'some name'; -export const DESCRIPTION = 'some description'; -export const LIST_ID = 'some-list-id'; -export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; - -export const META = {}; -export const TYPE = 'ip'; - -export const VERSION = 1; -export const IMMUTABLE = false; -// Exception List specific -export const ID = 'uuid_here'; -export const NAMESPACE_TYPE = 'single'; -export const OS_TYPES: OsTypeArray = ['windows']; -export const TAGS = []; -export const UPDATED_COMMENTS = [ - { - comment: 'old comment', - id: 'old_created_id', - }, - { - comment: 'new comment', - id: 'new_id', - }, -]; -export const COMMENTS = []; -export const ENTRIES: EntriesArray = [ - { - entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], - field: 'some.parentField', - type: 'nested', - }, - { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, -]; -export const ITEM_ID = 'some-list-item-id'; -export const ITEM_TYPE = 'simple'; -export const LIST_ITEM_ID = 'some-list-item-id'; -// ENTRIES_WITH_IDS should only be used to mock out functionality of a collection of transforms -// that are UI specific and useful for UI concerns that are inserted between the -// API and the actual user interface. In some ways these might be viewed as -// technical debt or to compensate for the differences and preferences -// of how ReactJS might prefer data vs. how we want to model data. -export const ENTRIES_WITH_IDS: EntriesArray = [ - { - entries: [ - { - field: 'nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as EntryMatch & { id: string }, - ], - field: 'some.parentField', - id: '123', - type: 'nested', - } as EntryNested & { id: string }, - { - field: 'some.not.nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as Entry & { id: string }, -]; - -export const COMMENTS_WITH_CREATEDAT_CREATEDBY: CommentsArray = [ - { - comment: 'old comment', - id: 'old_created_id', - created_at: '2022-01-08T15:25:31.830Z', - created_by: 'elastic', - }, - { - comment: 'new comment', - id: 'new_id', - created_at: '2022-05-14T15:25:31.830Z', - created_by: 'elastic', - }, -]; diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.ts b/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.ts deleted file mode 100644 index 916ce0c81dac..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { UpdateExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { - DESCRIPTION, - ENTRIES, - ID, - ITEM_ID, - ITEM_TYPE, - LIST_ITEM_ID, - META, - NAME, - NAMESPACE_TYPE, - OS_TYPES, - TAGS, - UPDATED_COMMENTS, -} from '../constants.mock'; - -export const getUpdateExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ - _version: undefined, - comments: UPDATED_COMMENTS, - description: DESCRIPTION, - entries: ENTRIES, - id: ID, - item_id: LIST_ITEM_ID, - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: ['linux'], - tags: TAGS, - type: ITEM_TYPE, -}); - -/** - * Useful for end to end tests and other mechanisms which want to fill in the values - * after doing a get of the structure. - */ -export const getUpdateMinimalExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - name: NAME, - os_types: OS_TYPES, - type: ITEM_TYPE, -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts b/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts deleted file mode 100644 index 0c5e732a1f30..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { - COMMENTS, - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - ENTRIES, - ITEM_ID, - ITEM_TYPE, - LIST_ID, - META, - NAME, - NAMESPACE_TYPE, - OS_TYPES, - TIE_BREAKER, - USER, -} from '../constants.mock'; - -export const getExceptionListItemSchemaMock = ( - overrides?: Partial -): ExceptionListItemSchema => ({ - _version: undefined, - comments: COMMENTS, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - entries: ENTRIES, - expire_time: undefined, - id: '1', - item_id: 'endpoint_list_item', - list_id: 'endpoint_list_id', - meta: META, - name: NAME, - namespace_type: NAMESPACE_TYPE, - os_types: [], - tags: ['user added string for a tag', 'malware'], - tie_breaker_id: TIE_BREAKER, - type: ITEM_TYPE, - updated_at: DATE_NOW, - updated_by: USER, - ...(overrides || {}), -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = - (): Partial => ({ - comments: [], - created_by: ELASTIC_USER, - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - list_id: LIST_ID, - name: NAME, - namespace_type: 'single', - os_types: OS_TYPES, - tags: [], - type: ITEM_TYPE, - updated_by: ELASTIC_USER, - }); diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.ts b/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.ts deleted file mode 100644 index 436ddcd7a83d..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { FoundListSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { getListResponseMock } from './list_schema.mock'; - -export const getFoundListSchemaMock = (): FoundListSchema => ({ - cursor: '123', - data: [getListResponseMock()], - page: 1, - per_page: 1, - total: 1, -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.ts b/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.ts deleted file mode 100644 index 79ed25641977..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; - -import { - DATE_NOW, - DESCRIPTION, - ELASTIC_USER, - IMMUTABLE, - LIST_ID, - META, - NAME, - TIE_BREAKER, - TYPE, - USER, - VERSION, -} from '../constants.mock'; - -export const getListResponseMock = (): ListSchema => ({ - '@timestamp': DATE_NOW, - _version: undefined, - created_at: DATE_NOW, - created_by: USER, - description: DESCRIPTION, - deserializer: undefined, - id: LIST_ID, - immutable: IMMUTABLE, - meta: META, - name: NAME, - serializer: undefined, - tie_breaker_id: TIE_BREAKER, - type: TYPE, - updated_at: DATE_NOW, - updated_by: USER, - version: VERSION, -}); - -/** - * This is useful for end to end tests where we remove the auto generated parts for comparisons - * such as created_at, updated_at, and id. - */ -export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - created_by: ELASTIC_USER, - description: DESCRIPTION, - immutable: IMMUTABLE, - name: NAME, - type: TYPE, - updated_by: ELASTIC_USER, - version: VERSION, -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts b/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts deleted file mode 100644 index bb0cb6e6e907..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts +++ /dev/null @@ -1,299 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { - CreateExceptionListItemSchema, - Entry, - EntryMatch, - EntryNested, - ExceptionListItemSchema, - UpdateExceptionListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { - addIdToExceptionItemEntries, - removeIdFromExceptionItemsEntries, - transformInput, - transformOutput, -} from '../..'; - -import { getCreateExceptionListItemSchemaMock } from '../mocks/request/create_exception_list_item_schema.mock'; -import { getUpdateExceptionListItemSchemaMock } from '../mocks/request/update_exception_list_item_schema.mock'; -import { getExceptionListItemSchemaMock } from '../mocks/response/exception_list_item_schema.mock'; -import { COMMENTS_WITH_CREATEDAT_CREATEDBY, ENTRIES_WITH_IDS } from '../mocks/constants.mock'; - -jest.mock('uuid', () => ({ - v4: jest.fn().mockReturnValue('123'), -})); - -describe('Exceptions transforms', () => { - describe('transformOutput', () => { - it('should return same output as input with stripped ids per entry - CreateExceptionListItemSchema', () => { - const mockCreateExceptionItem = { - ...getCreateExceptionListItemSchemaMock(), - entries: ENTRIES_WITH_IDS, - }; - const output = transformOutput(mockCreateExceptionItem); - const expectedOutput: CreateExceptionListItemSchema = getCreateExceptionListItemSchemaMock(); - - expect(output).toEqual(expectedOutput); - }); - - it('should return same output as input with stripped ids per entry - UpdateExceptionListItemSchema', () => { - const mockUpdateExceptionItem = { - ...getUpdateExceptionListItemSchemaMock(), - entries: ENTRIES_WITH_IDS, - }; - const output = transformOutput(mockUpdateExceptionItem); - const expectedOutput: UpdateExceptionListItemSchema = getUpdateExceptionListItemSchemaMock(); - - expect(output).toEqual(expectedOutput); - }); - it('should return output as input with stripped createdAt and createdBy per entry - UpdateExceptionListItemSchema', () => { - const mockUpdateExceptionItem = { - ...getUpdateExceptionListItemSchemaMock(), - entries: ENTRIES_WITH_IDS, - comments: COMMENTS_WITH_CREATEDAT_CREATEDBY, - }; - const output = transformOutput(mockUpdateExceptionItem); - const expectedOutput: UpdateExceptionListItemSchema = getUpdateExceptionListItemSchemaMock(); - - expect(output).toEqual(expectedOutput); - }); - }); - - describe('transformInput', () => { - it('should return same output as input with added ids per entry', () => { - const mockExceptionItem = getExceptionListItemSchemaMock(); - const output = transformInput(mockExceptionItem); - const expectedOutput: ExceptionListItemSchema = { - ...getExceptionListItemSchemaMock(), - entries: ENTRIES_WITH_IDS, - }; - - expect(output).toEqual(expectedOutput); - }); - }); - - describe('addIdToExceptionItemEntries', () => { - it('should return same output as input with added ids per entry', () => { - const mockExceptionItem: ExceptionListItemSchema = { - ...getExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - }; - const output = addIdToExceptionItemEntries(mockExceptionItem); - const expectedOutput: ExceptionListItemSchema = { - ...getExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as Entry & { id: string }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - - it('should return same output as input with added ids per nested entry', () => { - const mockExceptionItem: ExceptionListItemSchema = { - ...getExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - field: 'some.parentField', - type: 'nested', - }, - ], - }; - const output = addIdToExceptionItemEntries(mockExceptionItem); - const expectedOutput: ExceptionListItemSchema = { - ...getExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as EntryMatch & { id: string }, - ], - field: 'some.parentField', - id: '123', - type: 'nested', - } as EntryNested & { id: string }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - }); - - describe('removeIdFromExceptionItemsEntries', () => { - it('should return same output as input with stripped ids per entry - CreateExceptionListItemSchema', () => { - const mockCreateExceptionItem = { - ...getCreateExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as Entry & { id: string }, - ], - }; - const output = removeIdFromExceptionItemsEntries(mockCreateExceptionItem); - const expectedOutput: CreateExceptionListItemSchema = { - ...getCreateExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - - it('should return same output as input with stripped ids per nested entry - CreateExceptionListItemSchema', () => { - const mockCreateExceptionItem = { - ...getCreateExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as EntryMatch & { id: string }, - ], - field: 'some.parentField', - id: '123', - type: 'nested', - } as EntryNested & { id: string }, - ], - }; - const output = removeIdFromExceptionItemsEntries(mockCreateExceptionItem); - const expectedOutput: CreateExceptionListItemSchema = { - ...getCreateExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - field: 'some.parentField', - type: 'nested', - }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - - it('should return same output as input with stripped ids per entry - UpdateExceptionListItemSchema', () => { - const mockUpdateExceptionItem = { - ...getUpdateExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as Entry & { id: string }, - ], - }; - const output = removeIdFromExceptionItemsEntries(mockUpdateExceptionItem); - const expectedOutput: UpdateExceptionListItemSchema = { - ...getUpdateExceptionListItemSchemaMock(), - entries: [ - { - field: 'some.not.nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - - it('should return same output as input with stripped ids per nested entry - UpdateExceptionListItemSchema', () => { - const mockUpdateExceptionItem = { - ...getUpdateExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - id: '123', - operator: 'included', - type: 'match', - value: 'some value', - } as EntryMatch & { id: string }, - ], - field: 'some.parentField', - id: '123', - type: 'nested', - } as EntryNested & { id: string }, - ], - }; - const output = removeIdFromExceptionItemsEntries(mockUpdateExceptionItem); - const expectedOutput: UpdateExceptionListItemSchema = { - ...getUpdateExceptionListItemSchemaMock(), - entries: [ - { - entries: [ - { - field: 'nested.field', - operator: 'included', - type: 'match', - value: 'some value', - }, - ], - field: 'some.parentField', - type: 'nested', - }, - ], - }; - - expect(output).toEqual(expectedOutput); - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts b/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts deleted file mode 100644 index c30ea9ad8679..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts +++ /dev/null @@ -1,138 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { flow } from 'fp-ts/lib/function'; -import { addIdToItem, removeIdFromItem } from '@kbn/securitysolution-utils'; -import type { - CreateExceptionListItemSchema, - EntriesArray, - Entry, - ExceptionListItemSchema, - UpdateExceptionListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; - -// These are a collection of transforms that are UI specific and useful for UI concerns -// that are inserted between the API and the actual user interface. In some ways these -// might be viewed as technical debt or to compensate for the differences and preferences -// of how ReactJS might prefer data vs. how we want to model data. Each function should have -// a description giving context around the transform. - -/** - * Transforms the output of exception items to compensate for technical debt or UI concerns such as - * ReactJS preferences for having ids within arrays if the data is not modeled that way. - * - * If you add a new transform of the output called "myNewTransform" do it - * in the form of: - * flow(removeIdFromExceptionItemsEntries, myNewTransform)(exceptionItem) - * - * @param exceptionItem The exceptionItem to transform the output of - * @returns The exceptionItem transformed from the output - */ -export const transformOutput = ( - exceptionItem: UpdateExceptionListItemSchema | ExceptionListItemSchema -): UpdateExceptionListItemSchema | ExceptionListItemSchema => - flow( - removeCreatedAtCreatedByFromCommentsOnUpdate, - removeIdFromExceptionItemsEntries - )(exceptionItem); - -export const transformNewItemOutput = ( - exceptionItem: CreateExceptionListItemSchema -): CreateExceptionListItemSchema => flow(removeIdFromExceptionItemsEntries)(exceptionItem); - -/** - * Transforms the output of rules to compensate for technical debt or UI concerns such as - * ReactJS preferences for having ids within arrays if the data is not modeled that way. - * - * If you add a new transform of the input called "myNewTransform" do it - * in the form of: - * flow(addIdToExceptionItemEntries, myNewTransform)(exceptionItem) - * - * @param exceptionItem The exceptionItem to transform the output of - * @returns The exceptionItem transformed from the output - */ -export const transformInput = (exceptionItem: ExceptionListItemSchema): ExceptionListItemSchema => - flow(addIdToExceptionItemEntries)(exceptionItem); - -/** - * This adds an id to the incoming exception item entries as ReactJS prefers to have - * an id added to them for use as a stable id. Later if we decide to change the data - * model to have id's within the array then this code should be removed. If not, then - * this code should stay as an adapter for ReactJS. - * - * This does break the type system slightly as we are lying a bit to the type system as we return - * the same exceptionItem as we have previously but are augmenting the arrays with an id which TypeScript - * doesn't mind us doing here. However, downstream you will notice that you have an id when the type - * does not indicate it. In that case use (ExceptionItem & { id: string }) temporarily if you're using the id. If you're not, - * you can ignore the id and just use the normal TypeScript with ReactJS. - * - * @param exceptionItem The exceptionItem to add an id to the threat matches. - * @returns exceptionItem The exceptionItem but with id added to the exception item entries - */ -export const addIdToExceptionItemEntries = ( - exceptionItem: ExceptionListItemSchema -): ExceptionListItemSchema => { - const entries = exceptionItem.entries.map((entry) => { - if (entry.type === 'nested') { - return addIdToItem({ - ...entry, - entries: entry.entries.map((nestedEntry) => addIdToItem(nestedEntry)), - }); - } else { - return addIdToItem(entry); - } - }); - return { ...exceptionItem, entries }; -}; - -/** - * This removes an id from the exceptionItem entries as ReactJS prefers to have - * an id added to them for use as a stable id. Later if we decide to change the data - * model to have id's within the array then this code should be removed. If not, then - * this code should stay as an adapter for ReactJS. - * - * @param exceptionItem The exceptionItem to remove an id from the entries. - * @returns exceptionItem The exceptionItem but with id removed from the entries - */ -export const removeIdFromExceptionItemsEntries = ( - exceptionItem: T -): T => { - const { entries } = exceptionItem; - const entriesNoId = entries.map((entry) => { - if (entry.type === 'nested') { - return removeIdFromItem({ - ...entry, - entries: entry.entries.map((nestedEntry) => removeIdFromItem(nestedEntry)), - }); - } else { - return removeIdFromItem(entry); - } - }); - return { ...exceptionItem, entries: entriesNoId }; -}; - -/** - * This removes createdAt, createdBy from the exceptionItem if a comment was added to - * the Exception item, and return the comment message with id to prevent creating the commet - * twice - * @param exceptionItem The exceptionItem to remove createdAt, createdBy from the comments array. - * @returns exceptionItem The exceptionItem with comments do not have createdAt, createdBy. - */ -export const removeCreatedAtCreatedByFromCommentsOnUpdate = ( - exceptionItem: UpdateExceptionListItemSchema | ExceptionListItemSchema -) => { - const { comments } = exceptionItem; - if (!comments || !comments.length) return exceptionItem; - - const entriesNoCreatedAtAndBy = comments.map(({ comment, id }) => ({ - comment, - id, - })); - return { ...exceptionItem, comments: entriesNoCreatedAtAndBy }; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts deleted file mode 100644 index 4ce917f5ad95..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts +++ /dev/null @@ -1,317 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useMemo } from 'react'; -import type { - CreateExceptionListItemSchema, - ExceptionListItemSchema, - ExceptionListSchema, - UpdateExceptionListItemSchema, - ApiCallFindListsItemsMemoProps, - ApiCallMemoProps, - ApiListExportProps, - ApiCallGetExceptionFilterFromIdsMemoProps, - ApiCallGetExceptionFilterFromExceptionsMemoProps, - ApiListDuplicateProps, -} from '@kbn/securitysolution-io-ts-list-types'; -import * as Api from '@kbn/securitysolution-list-api'; -import { getIdsAndNamespaces } from '@kbn/securitysolution-list-utils'; -import type { HttpStart } from '@kbn/core-http-browser'; - -import { transformInput, transformNewItemOutput, transformOutput } from '../transforms'; - -export interface ExceptionsApi { - addExceptionListItem: (arg: { - listItem: CreateExceptionListItemSchema; - }) => Promise; - updateExceptionListItem: (arg: { - listItem: UpdateExceptionListItemSchema; - }) => Promise; - deleteExceptionItem: (arg: ApiCallMemoProps) => Promise; - deleteExceptionList: (arg: ApiCallMemoProps) => Promise; - duplicateExceptionList: (arg: ApiListDuplicateProps) => Promise; - getExceptionItem: ( - arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void } - ) => Promise; - getExceptionList: ( - arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void } - ) => Promise; - getExceptionListsItems: (arg: ApiCallFindListsItemsMemoProps) => Promise; - getExceptionFilterFromIds: (arg: ApiCallGetExceptionFilterFromIdsMemoProps) => Promise; - getExceptionFilterFromExceptions: ( - arg: ApiCallGetExceptionFilterFromExceptionsMemoProps - ) => Promise; - exportExceptionList: (arg: ApiListExportProps) => Promise; -} - -export const useApi = (http: HttpStart): ExceptionsApi => { - return useMemo( - (): ExceptionsApi => ({ - async addExceptionListItem({ - listItem, - }: { - listItem: CreateExceptionListItemSchema; - }): Promise { - const abortCtrl = new AbortController(); - const sanitizedItem: CreateExceptionListItemSchema = transformNewItemOutput(listItem); - - return Api.addExceptionListItem({ - http, - listItem: sanitizedItem, - signal: abortCtrl.signal, - }); - }, - async deleteExceptionItem({ - id, - namespaceType, - onSuccess, - onError, - }: ApiCallMemoProps): Promise { - const abortCtrl = new AbortController(); - - try { - await Api.deleteExceptionListItemById({ - http, - id, - namespaceType, - signal: abortCtrl.signal, - }); - onSuccess(); - } catch (error) { - onError(error); - } - }, - async deleteExceptionList({ - id, - namespaceType, - onSuccess, - onError, - }: ApiCallMemoProps): Promise { - const abortCtrl = new AbortController(); - - try { - await Api.deleteExceptionListById({ - http, - id, - namespaceType, - signal: abortCtrl.signal, - }); - onSuccess(); - } catch (error) { - onError(error); - } - }, - async duplicateExceptionList({ - includeExpiredExceptions, - listId, - namespaceType, - onError, - onSuccess, - }: ApiListDuplicateProps): Promise { - const abortCtrl = new AbortController(); - - try { - const newList = await Api.duplicateExceptionList({ - http, - includeExpiredExceptions, - listId, - namespaceType, - signal: abortCtrl.signal, - }); - onSuccess(newList); - } catch (error) { - onError(error); - } - }, - async exportExceptionList({ - id, - includeExpiredExceptions, - listId, - namespaceType, - onError, - onSuccess, - }: ApiListExportProps): Promise { - const abortCtrl = new AbortController(); - - try { - const blob = await Api.exportExceptionList({ - http, - id, - includeExpiredExceptions, - listId, - namespaceType, - signal: abortCtrl.signal, - }); - onSuccess(blob); - } catch (error) { - onError(error); - } - }, - async getExceptionItem({ - id, - namespaceType, - onSuccess, - onError, - }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void }): Promise { - const abortCtrl = new AbortController(); - - try { - const item = transformInput( - await Api.fetchExceptionListItemById({ - http, - id, - namespaceType, - signal: abortCtrl.signal, - }) - ); - onSuccess(item); - } catch (error) { - onError(error); - } - }, - async getExceptionList({ - id, - namespaceType, - onSuccess, - onError, - }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void }): Promise { - const abortCtrl = new AbortController(); - - try { - const list = await Api.fetchExceptionListById({ - http, - id, - namespaceType, - signal: abortCtrl.signal, - }); - onSuccess(list); - } catch (error) { - onError(error); - } - }, - async getExceptionListsItems({ - lists, - filter, - pagination, - showDetectionsListsOnly, - showEndpointListsOnly, - onSuccess, - onError, - }: ApiCallFindListsItemsMemoProps): Promise { - const abortCtrl = new AbortController(); - const { ids, namespaces } = getIdsAndNamespaces({ - lists, - showDetection: showDetectionsListsOnly, - showEndpoint: showEndpointListsOnly, - }); - - try { - if (ids.length > 0 && namespaces.length > 0) { - const { - data, - page, - per_page: perPage, - total, - } = await Api.fetchExceptionListsItemsByListIds({ - filter, - http, - listIds: ids, - namespaceTypes: namespaces, - pagination, - signal: abortCtrl.signal, - }); - onSuccess({ - // This data transform is UI specific and useful for UI concerns - // to compensate for the differences and preferences of how ReactJS might prefer - // data vs. how we want to model data. View `transformInput` for more details - exceptions: data.map((item) => transformInput(item)), - pagination: { - page, - perPage, - total, - }, - }); - } else { - onSuccess({ - exceptions: [], - pagination: { - page: 0, - perPage: pagination.perPage != null ? pagination.perPage : 0, - total: 0, - }, - }); - } - } catch (error) { - onError(error); - } - }, - async getExceptionFilterFromIds({ - exceptionListIds, - chunkSize, - alias, - excludeExceptions, - onSuccess, - onError, - }: ApiCallGetExceptionFilterFromIdsMemoProps): Promise { - const abortCtrl = new AbortController(); - try { - const { filter } = await Api.getExceptionFilterFromExceptionListIds({ - http, - exceptionListIds, - signal: abortCtrl.signal, - chunkSize, - alias, - excludeExceptions, - }); - onSuccess(filter); - } catch (error) { - onError(error); - } - }, - async getExceptionFilterFromExceptions({ - exceptions, - chunkSize, - alias, - excludeExceptions, - onSuccess, - onError, - }: ApiCallGetExceptionFilterFromExceptionsMemoProps): Promise { - const abortCtrl = new AbortController(); - try { - const { filter } = await Api.getExceptionFilterFromExceptions({ - http, - exceptions, - signal: abortCtrl.signal, - chunkSize, - alias, - excludeExceptions, - }); - onSuccess(filter); - } catch (error) { - onError(error); - } - }, - async updateExceptionListItem({ - listItem, - }: { - listItem: UpdateExceptionListItemSchema; - }): Promise { - const abortCtrl = new AbortController(); - const sanitizedItem: UpdateExceptionListItemSchema = transformOutput(listItem); - - return Api.updateExceptionListItem({ - http, - listItem: sanitizedItem, - signal: abortCtrl.signal, - }); - }, - }), - [http] - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.ts deleted file mode 100644 index 06b87f510796..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useMutation, useQueryClient } from '@tanstack/react-query'; - -import { createListIndex, ApiParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -import { READ_INDEX_QUERY_KEY } from '../constants'; - -const createListIndexWithOptionalSignal = withOptionalSignal(createListIndex); - -export const useCreateListIndex = ({ - http, - onError, -}: { - http: ApiParams['http']; - onError?: (err: unknown) => void; -}) => { - const queryClient = useQueryClient(); - - const { mutate, isLoading, error } = useMutation( - () => createListIndexWithOptionalSignal({ http }), - { - onSuccess: () => { - queryClient.invalidateQueries(READ_INDEX_QUERY_KEY); - }, - onError, - } - ); - - return { - start: mutate, - loading: isLoading, - error, - }; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.ts deleted file mode 100644 index 98939d93185d..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { UseMutationOptions } from '@tanstack/react-query'; -import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; -import { useMutation } from '@tanstack/react-query'; -import { createListItem } from '@kbn/securitysolution-list-api'; -import type { CreateListItemParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -import { useInvalidateListItemQuery } from '../use_find_list_items'; - -const createListItemWithOptionalSignal = withOptionalSignal(createListItem); - -export const CREATE_LIST_ITEM_MUTATION_KEY = ['POST', 'LIST_ITEM_CREATE']; -type CreateListMutationParams = Omit; - -export const useCreateListItemMutation = ( - options?: UseMutationOptions, CreateListMutationParams> -) => { - const invalidateListItemQuery = useInvalidateListItemQuery(); - return useMutation, CreateListMutationParams>( - ({ listId, value, http }) => - createListItemWithOptionalSignal({ listId, value, http, refresh: 'wait_for' }), - { - ...options, - mutationKey: CREATE_LIST_ITEM_MUTATION_KEY, - onSettled: (...args) => { - invalidateListItemQuery(); - if (options?.onSettled) { - options.onSettled(...args); - } - }, - } - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts b/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts deleted file mode 100644 index ca94eda81f95..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts +++ /dev/null @@ -1,121 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { renderHook, act } from '@testing-library/react'; - -import { UseCursorProps, useCursor } from '.'; - -describe('useCursor', () => { - it('returns undefined cursor if no values have been set', () => { - const { result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - - expect(result.current[0]).toBeUndefined(); - }); - - it('retrieves a cursor for the next page of a given page size', () => { - const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - rerender({ pageIndex: 1, pageSize: 1 }); - act(() => { - result.current[1]('new_cursor'); - }); - - expect(result.current[0]).toBeUndefined(); - - rerender({ pageIndex: 2, pageSize: 1 }); - expect(result.current[0]).toEqual('new_cursor'); - }); - - it('returns undefined cursor for an unknown search', () => { - const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - act(() => { - result.current[1]('new_cursor'); - }); - - rerender({ pageIndex: 1, pageSize: 2 }); - expect(result.current[0]).toBeUndefined(); - }); - - it('remembers cursor through rerenders', () => { - const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - - rerender({ pageIndex: 1, pageSize: 1 }); - act(() => { - result.current[1]('new_cursor'); - }); - - rerender({ pageIndex: 2, pageSize: 1 }); - expect(result.current[0]).toEqual('new_cursor'); - - rerender({ pageIndex: 0, pageSize: 0 }); - expect(result.current[0]).toBeUndefined(); - - rerender({ pageIndex: 2, pageSize: 1 }); - expect(result.current[0]).toEqual('new_cursor'); - }); - - it('remembers multiple cursors', () => { - const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - - rerender({ pageIndex: 1, pageSize: 1 }); - act(() => { - result.current[1]('new_cursor'); - }); - rerender({ pageIndex: 2, pageSize: 2 }); - act(() => { - result.current[1]('another_cursor'); - }); - - rerender({ pageIndex: 2, pageSize: 1 }); - expect(result.current[0]).toEqual('new_cursor'); - - rerender({ pageIndex: 3, pageSize: 2 }); - expect(result.current[0]).toEqual('another_cursor'); - }); - - it('returns the "nearest" cursor for the given page size', () => { - const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { - initialProps: { pageIndex: 0, pageSize: 0 }, - }); - - rerender({ pageIndex: 1, pageSize: 2 }); - act(() => { - result.current[1]('cursor1'); - }); - rerender({ pageIndex: 2, pageSize: 2 }); - act(() => { - result.current[1]('cursor2'); - }); - rerender({ pageIndex: 3, pageSize: 2 }); - act(() => { - result.current[1]('cursor3'); - }); - - rerender({ pageIndex: 2, pageSize: 2 }); - expect(result.current[0]).toEqual('cursor1'); - - rerender({ pageIndex: 3, pageSize: 2 }); - expect(result.current[0]).toEqual('cursor2'); - - rerender({ pageIndex: 4, pageSize: 2 }); - expect(result.current[0]).toEqual('cursor3'); - - rerender({ pageIndex: 6, pageSize: 2 }); - expect(result.current[0]).toEqual('cursor3'); - }); -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts deleted file mode 100644 index b8e8df043882..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback, useState } from 'react'; - -export interface UseCursorProps { - pageIndex: number; - pageSize: number; -} -type Cursor = string | undefined; -type SetCursor = (cursor: Cursor) => void; -type UseCursor = (props: UseCursorProps) => [Cursor, SetCursor]; - -const hash = (props: UseCursorProps): string => JSON.stringify(props); - -export const useCursor: UseCursor = ({ pageIndex, pageSize }) => { - const [cache, setCache] = useState>({}); - - const setCursor = useCallback( - (cursor) => { - setCache({ - ...cache, - [hash({ pageIndex: pageIndex + 1, pageSize })]: cursor, - }); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [pageIndex, pageSize] - ); - - let cursor: Cursor; - for (let i = pageIndex; i >= 0; i--) { - const currentProps = { pageIndex: i, pageSize }; - cursor = cache[hash(currentProps)]; - if (cursor) { - break; - } - } - - return [cursor, setCursor]; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts deleted file mode 100644 index fe88e19f8489..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { deleteList } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const deleteListWithOptionalSignal = withOptionalSignal(deleteList); - -export const useDeleteList = () => useAsync(deleteListWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts deleted file mode 100644 index 63107edda73a..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { UseMutationOptions } from '@tanstack/react-query'; -import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { useMutation } from '@tanstack/react-query'; -import { deleteListItem } from '@kbn/securitysolution-list-api'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; -import type { DeleteListItemParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; -import { useInvalidateListItemQuery } from '../use_find_list_items'; - -const deleteListItemWithOptionalSignal = withOptionalSignal(deleteListItem); - -export const DELETE_LIST_ITEM_MUTATION_KEY = ['POST', ' DELETE_LIST_ITEM_MUTATION']; -type DeleteListMutationParams = Omit; - -export const useDeleteListItemMutation = ( - options?: UseMutationOptions, DeleteListMutationParams> -) => { - const invalidateListItemQuery = useInvalidateListItemQuery(); - return useMutation, DeleteListMutationParams>( - ({ id, http }) => deleteListItemWithOptionalSignal({ id, http }), - { - ...options, - mutationKey: DELETE_LIST_ITEM_MUTATION_KEY, - onSettled: (...args) => { - invalidateListItemQuery(); - if (options?.onSettled) { - options.onSettled(...args); - } - }, - } - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts deleted file mode 100644 index 2907de45eba4..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts +++ /dev/null @@ -1,142 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import type { - ExceptionListSchema, - UseExceptionListsProps, - Pagination, - Sort, -} from '@kbn/securitysolution-io-ts-list-types'; -import { fetchExceptionLists } from '@kbn/securitysolution-list-api'; - -import { getFilters } from '@kbn/securitysolution-list-utils'; - -export type Func = () => void; -export type ReturnExceptionLists = [ - loading: boolean, - exceptionLists: ExceptionListSchema[], - pagination: Pagination, - setPagination: React.Dispatch>, - fetchLists: Func | null, - sort: Sort, - setSort: React.Dispatch> -]; - -const DEFAULT_PAGINATION = { - page: 1, - perPage: 20, - total: 0, -}; - -const DEFAULT_SORT = { - field: 'created_at', - order: 'desc', -}; - -/** - * Hook for fetching ExceptionLists - * - * @param http Kibana http service - * @param errorMessage message shown to user if error occurs - * @param filterOptions filter by certain fields - * @param namespaceTypes spaces to be searched - * @param notifications kibana service for displaying toasters - * @param hideLists a list of listIds we don't want to query - * @param initialPagination - * - */ -export const useExceptionLists = ({ - errorMessage, - http, - initialPagination = DEFAULT_PAGINATION, - filterOptions = {}, - namespaceTypes, - notifications, - hideLists = [], - initialSort = DEFAULT_SORT, -}: UseExceptionListsProps): ReturnExceptionLists => { - const [exceptionLists, setExceptionLists] = useState([]); - const [pagination, setPagination] = useState(initialPagination); - const [sort, setSort] = useState(initialSort); - const [loading, setLoading] = useState(true); - const abortCtrlRef = useRef(); - - const namespaceTypesAsString = useMemo(() => namespaceTypes.join(','), [namespaceTypes]); - const filters = useMemo( - (): string => - getFilters({ - filters: filterOptions, - namespaceTypes, - hideLists, - }), - [namespaceTypes, filterOptions, hideLists] - ); - - const fetchData = useCallback(async (): Promise => { - try { - setLoading(true); - - abortCtrlRef.current = new AbortController(); - - const { - page, - per_page: perPage, - total, - data, - } = await fetchExceptionLists({ - filters, - http, - namespaceTypes: namespaceTypesAsString, - pagination: { - page: pagination.page, - perPage: pagination.perPage, - }, - sort, - signal: abortCtrlRef.current.signal, - }); - - setPagination({ - page, - perPage, - total, - }); - setExceptionLists(data); - setLoading(false); - } catch (error) { - if (error.name !== 'AbortError') { - notifications.toasts.addError(error, { - title: errorMessage, - }); - setExceptionLists([]); - setPagination(DEFAULT_PAGINATION); - setLoading(false); - } - } - }, [ - errorMessage, - filters, - http, - namespaceTypesAsString, - notifications.toasts, - pagination.page, - pagination.perPage, - sort, - ]); - - useEffect(() => { - fetchData(); - - return (): void => { - abortCtrlRef.current?.abort(); - }; - }, [fetchData]); - - return [loading, exceptionLists, pagination, setPagination, fetchData, sort, setSort]; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts deleted file mode 100644 index 77a213cc47b9..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { exportList } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const exportListWithOptionalSignal = withOptionalSignal(exportList); - -export const useExportList = () => useAsync(exportListWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts deleted file mode 100644 index f385408d26fd..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts +++ /dev/null @@ -1,75 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useCallback } from 'react'; -import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { findListItems, ApiParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; -import { useCursor } from '../use_cursor'; - -const findListItemsWithOptionalSignal = withOptionalSignal(findListItems); - -const FIND_LIST_ITEMS_QUERY_KEY = 'FIND_LIST_ITEMS'; - -export const useInvalidateListItemQuery = () => { - const queryClient = useQueryClient(); - - return useCallback(() => { - queryClient.invalidateQueries([FIND_LIST_ITEMS_QUERY_KEY], { - refetchType: 'active', - }); - }, [queryClient]); -}; - -export const useFindListItems = ({ - pageIndex, - pageSize, - sortField, - sortOrder, - listId, - filter, - http, -}: { - pageIndex: number; - pageSize: number; - sortField: string; - sortOrder: 'asc' | 'desc'; - listId: string; - filter: string; - http: ApiParams['http']; -}) => { - const [cursor, setCursor] = useCursor({ pageIndex, pageSize }); - return useQuery( - [FIND_LIST_ITEMS_QUERY_KEY, pageIndex, pageSize, sortField, sortOrder, listId, filter], - async ({ signal }) => { - const response = await findListItemsWithOptionalSignal({ - http, - signal, - pageIndex, - pageSize, - sortField, - sortOrder, - listId, - cursor, - filter, - }); - return response; - }, - { - keepPreviousData: true, - refetchOnWindowFocus: false, - retry: false, - onSuccess: (data) => { - if (data?.cursor) { - setCursor(data?.cursor); - } - }, - } - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts b/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts deleted file mode 100644 index fcce54ac3be3..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts +++ /dev/null @@ -1,39 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { waitFor, renderHook, act } from '@testing-library/react'; - -import { useFindLists } from '.'; -import { httpServiceMock } from '@kbn/core-http-browser-mocks'; -import * as Api from '@kbn/securitysolution-list-api'; - -import { getFoundListSchemaMock } from '../mocks/response/found_list_schema.mock'; - -jest.mock('@kbn/securitysolution-list-api'); - -describe('useFindLists', () => { - let httpMock: ReturnType; - - beforeEach(() => { - httpMock = httpServiceMock.createStartContract(); - (Api.findLists as jest.Mock).mockResolvedValue(getFoundListSchemaMock()); - }); - - it('invokes Api.findLists', async () => { - const { result } = renderHook(() => useFindLists()); - act(() => { - result.current.start({ http: httpMock, pageIndex: 1, pageSize: 10 }); - }); - await waitFor(() => - expect(Api.findLists).toHaveBeenCalledWith( - expect.objectContaining({ http: httpMock, pageIndex: 1, pageSize: 10 }) - ) - ); - }); -}); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts deleted file mode 100644 index a33e3ba9f860..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { findLists } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const findListsWithOptionalSignal = withOptionalSignal(findLists); - -export const useFindLists = () => useAsync(findListsWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts deleted file mode 100644 index 25027ee3901d..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { findListsBySize } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const findListsBySizeWithOptionalSignal = withOptionalSignal(findListsBySize); - -export const useFindListsBySize = () => useAsync(findListsBySizeWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.ts deleted file mode 100644 index 030fbcfae829..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useQuery } from '@tanstack/react-query'; -import { getListById, ApiParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const getListByIdWithOptionalSignal = withOptionalSignal(getListById); - -const GET_LIST_BY_ID_QUERY_KEY = 'GET_LIST_BY_ID'; -export const useGetListById = ({ http, id }: { http: ApiParams['http']; id: string }) => { - return useQuery( - [GET_LIST_BY_ID_QUERY_KEY, id], - async ({ signal }) => { - const respone = await getListByIdWithOptionalSignal({ http, signal, id }); - return respone; - }, - { - refetchOnWindowFocus: false, - } - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts deleted file mode 100644 index 1bbccd144801..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { importList } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const importListWithOptionalSignal = withOptionalSignal(importList); - -export const useImportList = () => useAsync(importListWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.ts deleted file mode 100644 index cdae3015cff8..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { UseMutationOptions } from '@tanstack/react-query'; -import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import { useMutation } from '@tanstack/react-query'; -import type { PatchListItemParams } from '@kbn/securitysolution-list-api'; -import { patchListItem } from '@kbn/securitysolution-list-api'; -import type { IHttpFetchError } from '@kbn/core-http-browser'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; -import { useInvalidateListItemQuery } from '../use_find_list_items'; - -const patchListItemWithOptionalSignal = withOptionalSignal(patchListItem); - -export const PATCH_LIST_ITEM_MUTATION_KEY = ['PATCH', 'LIST_ITEM_MUTATION']; -type PatchListMutationParams = Omit; - -export const usePatchListItemMutation = ( - options?: UseMutationOptions, PatchListMutationParams> -) => { - const invalidateListItemQuery = useInvalidateListItemQuery(); - return useMutation, PatchListMutationParams>( - ({ id, value, _version, http }: PatchListMutationParams) => - patchListItemWithOptionalSignal({ id, value, http, refresh: 'true', _version }), - { - ...options, - mutationKey: PATCH_LIST_ITEM_MUTATION_KEY, - onSettled: (...args) => { - invalidateListItemQuery(); - if (options?.onSettled) { - options.onSettled(...args); - } - }, - } - ); -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts deleted file mode 100644 index 79f8748345fd..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Dispatch, useEffect, useRef, useState } from 'react'; -import type { - CreateExceptionListItemSchema, - PersistHookProps, - UpdateExceptionListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { addExceptionListItem, updateExceptionListItem } from '@kbn/securitysolution-list-api'; - -import { transformNewItemOutput, transformOutput } from '../transforms'; - -interface PersistReturnExceptionItem { - isLoading: boolean; - isSaved: boolean; -} - -export type ReturnPersistExceptionItem = [ - PersistReturnExceptionItem, - Dispatch -]; - -// TODO: Add this to @kbn/securitysolution-list-hooks - -/** - * Hook for creating or updating ExceptionListItem - * - * @param http Kibana http service - * @param onError error callback - * - */ -export const usePersistExceptionItem = ({ - http, - onError, -}: PersistHookProps): ReturnPersistExceptionItem => { - const [exceptionListItem, setExceptionItem] = useState< - CreateExceptionListItemSchema | UpdateExceptionListItemSchema | null - >(null); - const [isSaved, setIsSaved] = useState(false); - const [isLoading, setIsLoading] = useState(false); - const isUpdateExceptionItem = (item: unknown): item is UpdateExceptionListItemSchema => - Boolean(item && (item as UpdateExceptionListItemSchema).id != null); - const isSubscribed = useRef(false); - - useEffect(() => { - let abortCtrl: AbortController | null = null; - isSubscribed.current = true; - setIsSaved(false); - - const saveExceptionItem = async (): Promise => { - if (exceptionListItem === null) { - return; - } - - try { - abortCtrl = new AbortController(); - setIsLoading(true); - - if (isUpdateExceptionItem(exceptionListItem)) { - // Please see `x-pack/plugins/lists/public/exceptions/transforms.ts` doc notes - // for context around the temporary `id` - const transformedList = transformOutput(exceptionListItem); - - await updateExceptionListItem({ - http, - listItem: transformedList, - signal: abortCtrl.signal, - }); - } else { - // Please see `x-pack/plugins/lists/public/exceptions/transforms.ts` doc notes - // for context around the temporary `id` - const transformedList = transformNewItemOutput(exceptionListItem); - - await addExceptionListItem({ - http, - listItem: transformedList, - signal: abortCtrl.signal, - }); - } - - if (isSubscribed.current) { - setIsSaved(true); - } - } catch (error) { - if (isSubscribed.current) { - onError(error); - } - } finally { - if (isSubscribed.current) { - setIsLoading(false); - } - } - }; - - saveExceptionItem(); - - return (): void => { - isSubscribed.current = false; - abortCtrl?.abort(); - }; - }, [http, exceptionListItem, onError]); - - return [{ isLoading, isSaved }, setExceptionItem]; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.ts deleted file mode 100644 index 8648516d008c..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { Dispatch, useEffect, useState } from 'react'; -import type { - AddExceptionList, - PersistHookProps, - UpdateExceptionListSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { addExceptionList, updateExceptionList } from '@kbn/securitysolution-list-api'; - -interface PersistReturnExceptionList { - isLoading: boolean; - isSaved: boolean; -} - -export type ReturnPersistExceptionList = [ - PersistReturnExceptionList, - Dispatch -]; - -/** - * Hook for creating or updating ExceptionList - * - * @param http Kibana http service - * @param onError error callback - * - */ -export const usePersistExceptionList = ({ - http, - onError, -}: PersistHookProps): ReturnPersistExceptionList => { - const [exceptionList, setExceptionList] = useState(null); - const [isSaved, setIsSaved] = useState(false); - const [isLoading, setIsLoading] = useState(false); - const isUpdateExceptionList = (item: unknown): item is UpdateExceptionListSchema => - Boolean(item && (item as UpdateExceptionListSchema).id != null); - - useEffect(() => { - let isSubscribed = true; - const abortCtrl = new AbortController(); - setIsSaved(false); - - const saveExceptionList = async (): Promise => { - if (exceptionList != null) { - try { - setIsLoading(true); - if (isUpdateExceptionList(exceptionList)) { - await updateExceptionList({ http, list: exceptionList, signal: abortCtrl.signal }); - } else { - await addExceptionList({ http, list: exceptionList, signal: abortCtrl.signal }); - } - if (isSubscribed) { - setIsSaved(true); - } - } catch (error) { - if (isSubscribed) { - onError(error); - } - } - if (isSubscribed) { - setIsLoading(false); - } - } - }; - - saveExceptionList(); - return (): void => { - isSubscribed = false; - abortCtrl.abort(); - }; - }, [http, exceptionList, onError]); - - return [{ isLoading, isSaved }, setExceptionList]; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.ts deleted file mode 100644 index 4853f0a7480a..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { useQuery } from '@tanstack/react-query'; - -import { readListIndex, ApiParams } from '@kbn/securitysolution-list-api'; -import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -import { READ_INDEX_QUERY_KEY } from '../constants'; - -const readListIndexWithOptionalSignal = withOptionalSignal(readListIndex); - -export const useReadListIndex = ({ - http, - isEnabled, - onError, -}: { - isEnabled: boolean; - http: ApiParams['http']; - onError?: (err: unknown) => void; -}) => { - const query = useQuery( - READ_INDEX_QUERY_KEY, - async ({ signal }) => { - if (!isEnabled) { - return null; - } - - return readListIndexWithOptionalSignal({ http, signal }); - }, - { - onError, - retry: false, - refetchOnWindowFocus: false, - enabled: isEnabled, - staleTime: Infinity, - } - ); - - return { - result: query.data, - loading: query.isFetching, - error: query.error, - }; -}; diff --git a/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts deleted file mode 100644 index 42a055c16808..000000000000 --- a/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { readListPrivileges } from '@kbn/securitysolution-list-api'; -import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; - -const readListPrivilegesWithOptionalSignal = withOptionalSignal(readListPrivileges); - -export const useReadListPrivileges = () => useAsync(readListPrivilegesWithOptionalSignal); diff --git a/packages/kbn-securitysolution-list-hooks/tsconfig.json b/packages/kbn-securitysolution-list-hooks/tsconfig.json deleted file mode 100644 index 53e105e60975..000000000000 --- a/packages/kbn-securitysolution-list-hooks/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts", - ], - "kbn_references": [ - "@kbn/securitysolution-hook-utils", - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-list-api", - "@kbn/securitysolution-list-utils", - "@kbn/securitysolution-utils", - "@kbn/core-http-browser-mocks", - "@kbn/core-http-browser", - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-list-utils/index.ts b/packages/kbn-securitysolution-list-utils/index.ts deleted file mode 100644 index c5999a044a18..000000000000 --- a/packages/kbn-securitysolution-list-utils/index.ts +++ /dev/null @@ -1,19 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/autocomplete_operators'; -export * from './src/get_exception_list_type'; -export * from './src/get_filters'; -export * from './src/get_general_filters'; -export * from './src/get_ids_and_namespaces'; -export * from './src/get_saved_object_type'; -export * from './src/get_saved_object_types'; -export * from './src/has_large_value_list'; -export * from './src/helpers'; -export * from './src/types'; diff --git a/packages/kbn-securitysolution-list-utils/jest.config.js b/packages/kbn-securitysolution-list-utils/jest.config.js deleted file mode 100644 index b24a4fa543f7..000000000000 --- a/packages/kbn-securitysolution-list-utils/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-list-utils'], -}; diff --git a/packages/kbn-securitysolution-list-utils/package.json b/packages/kbn-securitysolution-list-utils/package.json deleted file mode 100644 index e9ace6e30234..000000000000 --- a/packages/kbn-securitysolution-list-utils/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-list-utils", - "version": "1.0.0", - "description": "security solution list utilities", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts b/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts deleted file mode 100644 index b4b1eec6be34..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts +++ /dev/null @@ -1,160 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { i18n } from '@kbn/i18n'; -import { - ListOperatorEnum as OperatorEnum, - ListOperatorTypeEnum as OperatorTypeEnum, -} from '@kbn/securitysolution-io-ts-list-types'; -import { OperatorOption } from '../types'; - -export const isOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isOperatorLabel', { - defaultMessage: 'is', - }), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.MATCH, - value: 'is', -}; - -export const isNotOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isNotOperatorLabel', { - defaultMessage: 'is not', - }), - operator: OperatorEnum.EXCLUDED, - type: OperatorTypeEnum.MATCH, - value: 'is_not', -}; - -export const isOneOfOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isOneOfOperatorLabel', { - defaultMessage: 'is one of', - }), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.MATCH_ANY, - value: 'is_one_of', -}; - -export const isNotOneOfOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isNotOneOfOperatorLabel', { - defaultMessage: 'is not one of', - }), - operator: OperatorEnum.EXCLUDED, - type: OperatorTypeEnum.MATCH_ANY, - value: 'is_not_one_of', -}; - -export const existsOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.existsOperatorLabel', { - defaultMessage: 'exists', - }), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.EXISTS, - value: 'exists', -}; - -export const doesNotExistOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.doesNotExistOperatorLabel', { - defaultMessage: 'does not exist', - }), - operator: OperatorEnum.EXCLUDED, - type: OperatorTypeEnum.EXISTS, - value: 'does_not_exist', -}; - -export const isInListOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isInListOperatorLabel', { - defaultMessage: 'is in list', - }), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.LIST, - value: 'is_in_list', -}; - -export const isNotInListOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.isNotInListOperatorLabel', { - defaultMessage: 'is not in list', - }), - operator: OperatorEnum.EXCLUDED, - type: OperatorTypeEnum.LIST, - value: 'is_not_in_list', -}; - -export const matchesOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.matchesOperatorLabel', { - defaultMessage: 'matches', - }), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.WILDCARD, - value: 'matches', -}; - -export const doesNotMatchOperator: OperatorOption = { - message: i18n.translate('lists.exceptions.doesNotMatchOperatorLabel', { - defaultMessage: 'does not match', - }), - operator: OperatorEnum.EXCLUDED, - type: OperatorTypeEnum.WILDCARD, - value: 'does_not_match', -}; - -export const EVENT_FILTERS_OPERATORS: OperatorOption[] = [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - matchesOperator, - doesNotMatchOperator, -]; - -/* - * !IMPORTANT! - Please only add to this list if it is an operator - * supported by the detection engine. - */ -export const DETECTION_ENGINE_EXCEPTION_OPERATORS: OperatorOption[] = [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - existsOperator, - doesNotExistOperator, - isInListOperator, - isNotInListOperator, - matchesOperator, - doesNotMatchOperator, -]; - -export const ALL_OPERATORS: OperatorOption[] = [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - existsOperator, - doesNotExistOperator, - isInListOperator, - isNotInListOperator, - matchesOperator, - doesNotMatchOperator, -]; - -export const EXCEPTION_OPERATORS_SANS_LISTS: OperatorOption[] = [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - existsOperator, - doesNotExistOperator, - matchesOperator, - doesNotMatchOperator, -]; - -export const EXCEPTION_OPERATORS_ONLY_LISTS: OperatorOption[] = [ - isInListOperator, - isNotInListOperator, -]; diff --git a/packages/kbn-securitysolution-list-utils/src/get_exception_list_type/index.ts b/packages/kbn-securitysolution-list-utils/src/get_exception_list_type/index.ts deleted file mode 100644 index 568436c487de..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_exception_list_type/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; - -import { exceptionListAgnosticSavedObjectType } from '../types'; - -export const getExceptionListType = ({ - savedObjectType, -}: { - savedObjectType: string; -}): NamespaceType => { - if (savedObjectType === exceptionListAgnosticSavedObjectType) { - return 'agnostic'; - } else { - return 'single'; - } -}; diff --git a/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts b/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts deleted file mode 100644 index 76b9eeda44f8..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts +++ /dev/null @@ -1,209 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { getFilters } from '.'; - -describe('getFilters', () => { - describe('single', () => { - test('it properly formats when no filters and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(not exception-list.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when no filters and hide lists contains one list id', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual('(not exception-list.attributes.list_id: listId-1*)'); - }); - test('it properly formats when no filters and no hide lists', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single'], - hideLists: [], - }); - - expect(filter).toEqual(''); - }); - test('it properly formats when filters passed and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when filters passed and hide lists contains one list id', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1*)' - ); - }); - test('it properly formats when filters passed and no hide lists', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single'], - hideLists: [], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample)' - ); - }); - }); - - describe('agnostic', () => { - test('it properly formats when no filters and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['agnostic'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list-agnostic.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when no filters and hide lists contains one list id', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['agnostic'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual('(not exception-list-agnostic.attributes.list_id: listId-1*)'); - }); - test('it properly formats when no filters and no hide lists', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['agnostic'], - hideLists: [], - }); - - expect(filter).toEqual(''); - }); - test('it properly formats when filters passed and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['agnostic'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list-agnostic.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when filters passed and hide lists contains one list id', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['agnostic'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual( - '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list-agnostic.attributes.list_id: listId-1*)' - ); - }); - test('it properly formats when filters passed and no hide lists', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['agnostic'], - hideLists: [], - }); - - expect(filter).toEqual( - '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample)' - ); - }); - }); - - describe('single, agnostic', () => { - test('it properly formats when no filters and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single', 'agnostic'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2* AND not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3* AND not exception-list-agnostic.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when no filters and hide lists contains one list id', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single', 'agnostic'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual( - '(not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*)' - ); - }); - test('it properly formats when no filters and no hide lists', () => { - const filter = getFilters({ - filters: {}, - namespaceTypes: ['single', 'agnostic'], - hideLists: [], - }); - - expect(filter).toEqual(''); - }); - test('it properly formats when filters passed and hide lists contains few list ids', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single', 'agnostic'], - hideLists: ['listId-1', 'listId-2', 'listId-3'], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2* AND not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3* AND not exception-list-agnostic.attributes.list_id: listId-3*)' - ); - }); - test('it properly formats when filters passed and hide lists contains one list id', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single', 'agnostic'], - hideLists: ['listId-1'], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*)' - ); - }); - test('it properly formats when filters passed and no hide lists', () => { - const filter = getFilters({ - filters: { created_by: 'moi', name: 'Sample' }, - namespaceTypes: ['single', 'agnostic'], - hideLists: [], - }); - - expect(filter).toEqual( - '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample)' - ); - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-utils/src/get_filters/index.ts b/packages/kbn-securitysolution-list-utils/src/get_filters/index.ts deleted file mode 100644 index 6ca3119855b3..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_filters/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExceptionListFilter, NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; -import { getGeneralFilters } from '../get_general_filters'; -import { getSavedObjectTypes } from '../get_saved_object_types'; -export interface GetFiltersParams { - filters: ExceptionListFilter; - namespaceTypes: NamespaceType[]; - hideLists: readonly string[]; -} - -export const getFilters = ({ filters, namespaceTypes, hideLists }: GetFiltersParams): string => { - const namespaces = getSavedObjectTypes({ namespaceType: namespaceTypes }); - const generalFilters = getGeneralFilters(filters, namespaces); - const hideListsFilters = hideLists.map((listId) => { - const filtersByNamespace = namespaces.map((namespace) => { - return `not ${namespace}.attributes.list_id: ${listId}*`; - }); - return `(${filtersByNamespace.join(' AND ')})`; - }); - - return [generalFilters, ...hideListsFilters] - .filter((filter) => filter.trim() !== '') - .join(' AND '); -}; diff --git a/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.test.ts b/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.test.ts deleted file mode 100644 index b349c57ab386..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; -import { getGeneralFilters } from '.'; - -describe('getGeneralFilters', () => { - test('it returns empty string if no filters', () => { - const filters = getGeneralFilters({}, ['exception-list']); - - expect(filters).toEqual(''); - }); - - test('it properly formats filters when one namespace type passed in', () => { - const filters = getGeneralFilters({ created_by: 'moi', name: 'Sample' }, ['exception-list']); - - expect(filters).toEqual( - '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample)' - ); - }); - - test('it properly formats filters when two namespace types passed in', () => { - const filters = getGeneralFilters({ created_by: 'moi', name: 'Sample' }, [ - 'exception-list', - 'exception-list-agnostic', - ]); - - expect(filters).toEqual( - '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample)' - ); - }); - - test('it properly formats filters when two types are passed in', () => { - const filters = getGeneralFilters( - { - created_by: 'moi', - name: 'Sample', - types: [ExceptionListTypeEnum.DETECTION, ExceptionListTypeEnum.RULE_DEFAULT], - }, - ['exception-list', 'exception-list-agnostic'] - ); - - expect(filters).toEqual( - '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (exception-list.attributes.type:detection OR exception-list.attributes.type:rule_default OR exception-list-agnostic.attributes.type:detection OR exception-list-agnostic.attributes.type:rule_default)' - ); - }); -}); diff --git a/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts b/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts deleted file mode 100644 index cc9b46728cbc..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExceptionListFilter } from '@kbn/securitysolution-io-ts-list-types'; -import { isArray } from 'lodash'; -import { get } from 'lodash/fp'; -import { SavedObjectType } from '../types'; - -export const getGeneralFilters = ( - filters: ExceptionListFilter, - namespaceTypes: SavedObjectType[] -): string => { - return Object.keys(filters) - .map((filterKey) => { - const value = get(filterKey, filters); - if (isArray(value) || (value != null && value.trim() !== '')) { - const filtersByNamespace = namespaceTypes - .map((namespace) => { - const fieldToSearch = - filterKey === 'name' ? 'name.text' : filterKey === 'types' ? 'type' : filterKey; - return isArray(value) - ? value.map((val) => `${namespace}.attributes.${fieldToSearch}:${val}`).join(' OR ') - : `${namespace}.attributes.${fieldToSearch}:${value}`; - }) - .join(' OR '); - return `(${filtersByNamespace})`; - } else return null; - }) - .filter((item) => item != null) - .join(' AND '); -}; diff --git a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts b/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts deleted file mode 100644 index df5bedc2d2b4..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts +++ /dev/null @@ -1,106 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { getIdsAndNamespaces } from '.'; - -describe('getIdsAndNamespaces', () => { - test('it returns empty arrays if no lists found', async () => { - const output = getIdsAndNamespaces({ - lists: [], - showDetection: false, - showEndpoint: false, - }); - - expect(output).toEqual({ ids: [], namespaces: [] }); - }); - - test('it returns all lists if "showDetection" and "showEndpoint" are "false"', async () => { - const output = getIdsAndNamespaces({ - lists: [ - { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, - { - id: 'myListIdEndpoint', - listId: 'list_id_endpoint', - namespaceType: 'agnostic', - type: 'endpoint', - }, - ], - showDetection: false, - showEndpoint: false, - }); - - expect(output).toEqual({ - ids: ['list_id', 'list_id_endpoint'], - namespaces: ['single', 'agnostic'], - }); - }); - - test('it returns only detections lists if "showDetection" is "true"', async () => { - const output = getIdsAndNamespaces({ - lists: [ - { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, - { - id: 'myListIdEndpoint', - listId: 'list_id_endpoint', - namespaceType: 'agnostic', - type: 'endpoint', - }, - ], - showDetection: true, - showEndpoint: false, - }); - - expect(output).toEqual({ - ids: ['list_id'], - namespaces: ['single'], - }); - }); - - test('it returns only endpoint lists if "showEndpoint" is "true"', async () => { - const output = getIdsAndNamespaces({ - lists: [ - { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, - { - id: 'myListIdEndpoint', - listId: 'list_id_endpoint', - namespaceType: 'agnostic', - type: 'endpoint', - }, - ], - showDetection: false, - showEndpoint: true, - }); - - expect(output).toEqual({ - ids: ['list_id_endpoint'], - namespaces: ['agnostic'], - }); - }); - - test('it returns only detection lists if both "showEndpoint" and "showDetection" are "true"', async () => { - const output = getIdsAndNamespaces({ - lists: [ - { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, - { - id: 'myListIdEndpoint', - listId: 'list_id_endpoint', - namespaceType: 'agnostic', - type: 'endpoint', - }, - ], - showDetection: true, - showEndpoint: true, - }); - - expect(output).toEqual({ - ids: ['list_id'], - namespaces: ['single'], - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts b/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts deleted file mode 100644 index bc18dff7d33e..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ExceptionListIdentifiers, NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; - -export const getIdsAndNamespaces = ({ - lists, - showDetection, - showEndpoint, -}: { - lists: ExceptionListIdentifiers[]; - showDetection: boolean; - showEndpoint: boolean; -}): { ids: string[]; namespaces: NamespaceType[] } => - lists - .filter((list) => { - if (showDetection) { - return list.type === 'detection'; - } else if (showEndpoint) { - return list.type === 'endpoint'; - } else { - return true; - } - }) - .reduce<{ ids: string[]; namespaces: NamespaceType[] }>( - (acc, { listId, namespaceType }) => ({ - ids: [...acc.ids, listId], - namespaces: [...acc.namespaces, namespaceType], - }), - { ids: [], namespaces: [] } - ); diff --git a/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.ts b/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.ts deleted file mode 100644 index 3e6cd312cb96..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; - -import { - exceptionListAgnosticSavedObjectType, - exceptionListSavedObjectType, - SavedObjectType, -} from '../types'; - -export const getSavedObjectType = ({ - namespaceType, -}: { - namespaceType: NamespaceType; -}): SavedObjectType => { - if (namespaceType === 'agnostic') { - return exceptionListAgnosticSavedObjectType; - } else { - return exceptionListSavedObjectType; - } -}; diff --git a/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts b/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts deleted file mode 100644 index ec09fc25bd77..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { NamespaceTypeArray } from '@kbn/securitysolution-io-ts-list-types'; - -import { SavedObjectType } from '../types'; -import { getSavedObjectType } from '../get_saved_object_type'; - -export const getSavedObjectTypes = ({ - namespaceType, -}: { - namespaceType: NamespaceTypeArray; -}): SavedObjectType[] => { - return namespaceType.map((singleNamespaceType) => - getSavedObjectType({ namespaceType: singleNamespaceType }) - ); -}; diff --git a/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts b/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts deleted file mode 100644 index ef774b5c8cf1..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { EntriesArray } from '@kbn/securitysolution-io-ts-list-types'; - -export const hasLargeValueList = (entries: EntriesArray): boolean => { - const found = entries.filter(({ type }) => type === 'list'); - return found.length > 0; -}; diff --git a/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts b/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts deleted file mode 100644 index fffcabbf4157..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts +++ /dev/null @@ -1,377 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - getMappingConflictsInfo, - fieldSupportsMatches, - hasWrongOperatorWithWildcard, - hasPartialCodeSignatureEntry, -} from '.'; - -describe('Helpers', () => { - describe('getMappingConflictsInfo', () => { - test('it return null if there are not conflicts', () => { - const field = { - name: 'field1', - type: 'string', - }; - const conflictsInfo = getMappingConflictsInfo(field); - - expect(conflictsInfo).toBeNull(); - }); - test('it groups ".ds-" data stream indices', () => { - const field = { - name: 'field1', - type: 'conflict', - conflictDescriptions: { - text: [ - '.ds-logs-default-2023.01.18-000001', - '.ds-logs-default-2023.01.18-000002', - '.ds-logs-tortilla.process-default-2022.11.20-000011', - '.ds-logs-tortilla.process-default-2022.11.20-000012', - '.ds-logs-tortilla.process-default-2022.11.20-000016', - ], - long: [ - '.ds-logs-default-2023.01.18-000004', - '.ds-logs-default-2023.01.18-000005', - 'partial-.ds-logs-gcp.audit-2021.12.22-000240', - 'partial-.ds-logs-gcp.audit-2021.12.22-000242', - ], - }, - }; - const conflictsInfo = getMappingConflictsInfo(field); - - expect(conflictsInfo).toEqual([ - { - type: 'text', - totalIndexCount: 5, - groupedIndices: [ - { name: 'logs-tortilla.process-default', count: 3 }, - { name: 'logs-default', count: 2 }, - ], - }, - { - type: 'long', - totalIndexCount: 4, - groupedIndices: [ - { name: 'logs-default', count: 2 }, - { name: 'logs-gcp.audit', count: 2 }, - ], - }, - ]); - }); - test('it groups old ".siem-" indices', () => { - const field = { - name: 'field1', - type: 'conflict', - conflictDescriptions: { - text: [ - '.siem-signals-default-000001', - '.siem-signals-default-000002', - '.siem-signals-default-000011', - '.siem-signals-default-000012', - ], - unmapped: [ - '.siem-signals-default-000004', - '.siem-signals-default-000005', - '.siem-signals-default-000240', - ], - }, - }; - const conflictsInfo = getMappingConflictsInfo(field); - - expect(conflictsInfo).toEqual([ - { - type: 'text', - totalIndexCount: 4, - groupedIndices: [{ name: '.siem-signals-default', count: 4 }], - }, - { - type: 'unmapped', - totalIndexCount: 3, - groupedIndices: [{ name: '.siem-signals-default', count: 3 }], - }, - ]); - }); - test('it groups mixed indices', () => { - const field = { - name: 'field1', - type: 'conflict', - conflictDescriptions: { - boolean: [ - '.ds-logs-default-2023.01.18-000001', - '.ds-logs-tortilla.process-default-2022.11.20-000011', - '.ds-logs-tortilla.process-default-2022.11.20-000012', - '.ds-logs-tortilla.process-default-2022.11.20-000016', - '.siem-signals-default-000001', - '.siem-signals-default-000002', - '.siem-signals-default-000012', - 'my-own-index-1', - 'my-own-index-2', - ], - unmapped: [ - '.siem-signals-default-000004', - 'partial-.ds-logs-gcp.audit-2021.12.22-000240', - 'partial-.ds-logs-gcp.audit-2021.12.22-000242', - 'my-own-index-3', - ], - }, - }; - const conflictsInfo = getMappingConflictsInfo(field); - - expect(conflictsInfo).toEqual([ - { - type: 'boolean', - totalIndexCount: 9, - groupedIndices: [ - { name: 'logs-tortilla.process-default', count: 3 }, - { name: '.siem-signals-default', count: 3 }, - { name: 'logs-default', count: 1 }, - { name: 'my-own-index-1', count: 1 }, - { name: 'my-own-index-2', count: 1 }, - ], - }, - { - type: 'unmapped', - totalIndexCount: 4, - groupedIndices: [ - { name: 'logs-gcp.audit', count: 2 }, - { name: '.siem-signals-default', count: 1 }, - { name: 'my-own-index-3', count: 1 }, - ], - }, - ]); - }); - }); - - describe('fieldSupportsMatches', () => { - test('it returns true if esTypes is keyword', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword'] }) - ).toBeTruthy(); - }); - - test('it returns true if one of the esTypes is kibana type string and another is not', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword', 'object'] }) - ).toBeTruthy(); - }); - - test('it returns true if one of the esTypes is keyword', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword', 'unmapped'] }) - ).toBeTruthy(); - }); - - test('it returns true if one of the esTypes is text', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['text', 'unmapped'] }) - ).toBeTruthy(); - }); - - test('it returns true if all of the esTypes is map to kibana type string', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['text', 'keyword'] }) - ).toBeTruthy(); - }); - - test('it returns false if none of the esTypes map to kibana type string', () => { - expect( - fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['bool', 'unmapped'] }) - ).toBeFalsy(); - }); - }); - describe('hasWrongOperatorWithWildcard', () => { - test('it returns true if there is at least one exception entry with a wildcard and the wrong operator', () => { - expect( - hasWrongOperatorWithWildcard([ - { - description: '', - name: '', - type: 'simple', - entries: [{ type: 'match', value: 'withwildcard*', field: '', operator: 'included' }], - }, - ]) - ).toBeTruthy(); - expect( - hasWrongOperatorWithWildcard([ - { - description: '', - name: '', - type: 'simple', - entries: [{ type: 'match', value: 'withwildcard?', field: '', operator: 'included' }], - }, - ]) - ).toBeTruthy(); - }); - - test('it returns true if there are entries joined with an OR that have a wildcard and the wrong operator', () => { - expect( - hasWrongOperatorWithWildcard([ - { - description: '', - name: '', - type: 'simple', - entries: [{ type: 'match', value: 'withwildcard?', field: '', operator: 'included' }], - }, - { - description: '', - name: '', - type: 'simple', - entries: [{ type: 'match', value: 'withwildcard?*', field: '', operator: 'included' }], - }, - ]) - ).toBeTruthy(); - }); - - test('it returns false if there are no exception entries with a wildcard and the wrong operator', () => { - expect( - hasWrongOperatorWithWildcard([ - { - description: '', - name: '', - type: 'simple', - entries: [ - { type: 'match', value: 'nowildcard', field: '', operator: 'excluded' }, - { type: 'wildcard', value: 'withwildcard*?', field: '', operator: 'included' }, - ], - }, - ]) - ).toBeFalsy(); - }); - - test('it returns true if there are nested entries with a wildcard and the wrong operator', () => { - expect( - hasWrongOperatorWithWildcard([ - { - description: '', - name: '', - type: 'simple', - entries: [ - { type: 'match', value: 'nowildcard', field: '', operator: 'excluded' }, - { - field: '', - type: 'nested', - entries: [{ type: 'match', value: 'wildcard?', field: '', operator: 'excluded' }], - }, - ], - }, - ]) - ).toBeTruthy(); - }); - }); - - describe('hasPartialCodeSignatureEntry', () => { - it('returns false if the entry has neither code signature subject name nor trusted field', () => { - expect( - hasPartialCodeSignatureEntry([ - { - description: '', - name: '', - type: 'simple', - os_types: ['windows'], - entries: [{ type: 'match', value: 'asdf', field: 'someField', operator: 'excluded' }], - }, - ]) - ).toBeFalsy(); - }); - it('returns true if the entry has code signature subject name but not trusted field', () => { - expect( - hasPartialCodeSignatureEntry([ - { - description: '', - name: '', - type: 'simple', - os_types: ['windows'], - entries: [ - { - type: 'match', - value: 'asdf', - field: 'process.code_signature.subject_name', - operator: 'excluded', - }, - ], - }, - ]) - ).toBeTruthy(); - }); - it('returns true if the entry has code signature trusted but not the subject name field', () => { - expect( - hasPartialCodeSignatureEntry([ - { - description: '', - name: '', - type: 'simple', - os_types: ['windows'], - entries: [ - { - type: 'match', - value: 'asdf', - field: 'process.code_signature.trusted', - operator: 'excluded', - }, - ], - }, - ]) - ).toBeTruthy(); - }); - it('returns false if the entry has both code signature subject name and trusted field', () => { - expect( - hasPartialCodeSignatureEntry([ - { - description: '', - name: '', - type: 'simple', - os_types: ['windows'], - entries: [ - { - type: 'match', - value: 'asdf', - field: 'process.code_signature.subject_name', - operator: 'excluded', - }, - { - type: 'match', - value: 'true', - field: 'process.code_signature.trusted', - operator: 'excluded', - }, - ], - }, - ]) - ).toBeFalsy(); - }); - it('returns false if the entry has both code signature team_id and trusted fields for mac os', () => { - expect( - hasPartialCodeSignatureEntry([ - { - description: '', - name: '', - type: 'simple', - os_types: ['macos'], - entries: [ - { - type: 'match', - value: 'asdf', - field: 'process.code_signature.team_id', - operator: 'excluded', - }, - { - type: 'match', - value: 'true', - field: 'process.code_signature.trusted', - operator: 'excluded', - }, - ], - }, - ]) - ).toBeFalsy(); - }); - }); -}); diff --git a/packages/kbn-securitysolution-list-utils/src/helpers/index.ts b/packages/kbn-securitysolution-list-utils/src/helpers/index.ts deleted file mode 100644 index 8031cfba14f2..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/helpers/index.ts +++ /dev/null @@ -1,1089 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { v4 as uuidv4 } from 'uuid'; -import { - addIdToItem, - removeIdFromItem, - validateHasWildcardWithWrongOperator, -} from '@kbn/securitysolution-utils'; -import { validate } from '@kbn/securitysolution-io-ts-utils'; -import { - CreateExceptionListItemSchema, - EntriesArray, - Entry, - EntryNested, - ExceptionListType, - ListSchema, - NamespaceType, - ListOperatorEnum as OperatorEnum, - ListOperatorTypeEnum as OperatorTypeEnum, - createExceptionListItemSchema, - entriesList, - entriesNested, - entry, - exceptionListItemSchema, - nestedEntryItem, - CreateRuleExceptionListItemSchema, - createRuleExceptionListItemSchema, -} from '@kbn/securitysolution-io-ts-list-types'; -import { - DataViewBase, - DataViewFieldBase, - getDataViewFieldSubtypeNested, - isDataViewFieldSubtypeNested, -} from '@kbn/es-query'; -import { castEsToKbnFieldTypeName, KBN_FIELD_TYPES } from '@kbn/field-types'; - -import { - ALL_OPERATORS, - EXCEPTION_OPERATORS_SANS_LISTS, - doesNotExistOperator, - existsOperator, - isNotOperator, - isOneOfOperator, - isOperator, - DETECTION_ENGINE_EXCEPTION_OPERATORS, - isNotOneOfOperator, - isInListOperator, - isNotInListOperator, - matchesOperator, - doesNotMatchOperator, -} from '../autocomplete_operators'; - -import { - BuilderEntry, - CreateExceptionListItemBuilderSchema, - DataViewField, - EmptyEntry, - EmptyNestedEntry, - ExceptionsBuilderExceptionItem, - ExceptionsBuilderReturnExceptionItem, - FormattedBuilderEntry, - OperatorOption, - SavedObjectType, -} from '../types'; - -export const isEntryNested = (item: BuilderEntry): item is EntryNested => { - return (item as EntryNested).entries != null; -}; - -export const filterExceptionItems = ( - exceptions: ExceptionsBuilderExceptionItem[] -): ExceptionsBuilderReturnExceptionItem[] => { - return exceptions.reduce((acc, exception) => { - const entries = exception.entries.reduce((nestedAcc, singleEntry) => { - const strippedSingleEntry = removeIdFromItem(singleEntry); - if (entriesNested.is(strippedSingleEntry)) { - const nestedEntriesArray = strippedSingleEntry.entries.filter((singleNestedEntry) => { - const noIdSingleNestedEntry = removeIdFromItem(singleNestedEntry); - const [validatedNestedEntry] = validate(noIdSingleNestedEntry, nestedEntryItem); - return validatedNestedEntry != null; - }); - const noIdNestedEntries = nestedEntriesArray.map((singleNestedEntry) => - removeIdFromItem(singleNestedEntry) - ); - - const [validatedNestedEntry] = validate( - { ...strippedSingleEntry, entries: noIdNestedEntries }, - entriesNested - ); - - if (validatedNestedEntry != null) { - return [...nestedAcc, { ...singleEntry, entries: nestedEntriesArray }]; - } - return nestedAcc; - } else { - const [validatedEntry] = validate(strippedSingleEntry, entry); - if (validatedEntry != null) { - return [...nestedAcc, singleEntry]; - } - return nestedAcc; - } - }, []); - - if (entries.length === 0) { - return acc; - } - - const item = { ...exception, entries }; - - if (exceptionListItemSchema.is(item)) { - return [...acc, item]; - } else if ( - createExceptionListItemSchema.is(item) || - createRuleExceptionListItemSchema.is(item) - ) { - const { meta, ...rest } = item; - const itemSansMetaId: CreateExceptionListItemSchema | CreateRuleExceptionListItemSchema = { - ...rest, - meta: undefined, - }; - return [...acc, itemSansMetaId]; - } else { - return acc; - } - }, []); -}; - -export const addIdToEntries = (entries: EntriesArray): EntriesArray => { - return entries.map((singleEntry) => { - if (singleEntry.type === 'nested') { - return addIdToItem({ - ...singleEntry, - entries: singleEntry.entries.map((nestedEntry) => addIdToItem(nestedEntry)), - }); - } else { - return addIdToItem(singleEntry); - } - }); -}; - -export const getNewExceptionItem = ({ - listId, - namespaceType, - name, -}: { - listId: string | undefined; - namespaceType: NamespaceType | undefined; - name: string; -}): CreateExceptionListItemBuilderSchema => { - return { - comments: [], - description: `Exception list item`, - entries: addIdToEntries([ - { - field: '', - operator: 'included', - type: 'match', - value: '', - }, - ]), - item_id: undefined, - list_id: listId, - meta: { - temporaryUuid: uuidv4(), - }, - name, - namespace_type: namespaceType, - tags: [], - type: 'simple', - }; -}; - -/** - * Returns the operator type, may not need this if using io-ts types - * - * @param item a single ExceptionItem entry - */ -export const getOperatorType = (item: BuilderEntry): OperatorTypeEnum => { - switch (item.type) { - case 'match': - return OperatorTypeEnum.MATCH; - case 'match_any': - return OperatorTypeEnum.MATCH_ANY; - case 'wildcard': - return OperatorTypeEnum.WILDCARD; - case 'list': - return OperatorTypeEnum.LIST; - default: - return OperatorTypeEnum.EXISTS; - } -}; - -/** - * Determines operator selection (is/is not/is one of, etc.) - * Default operator is "is" - * - * @param item a single ExceptionItem entry - */ -export const getExceptionOperatorSelect = (item: BuilderEntry): OperatorOption => { - if (item.type === 'nested') { - return isOperator; - } else { - const operatorType = getOperatorType(item); - const foundOperator = ALL_OPERATORS.find((operatorOption) => { - return item.operator === operatorOption.operator && operatorType === operatorOption.type; - }); - - return foundOperator != null ? foundOperator : isOperator; - } -}; - -/** - * Returns the fields corresponding value for an entry - * - * @param item a single ExceptionItem entry - */ -export const getEntryValue = (item: BuilderEntry): string | string[] | undefined => { - switch (item.type) { - case OperatorTypeEnum.MATCH: - case OperatorTypeEnum.MATCH_ANY: - case OperatorTypeEnum.WILDCARD: - return item.value; - case OperatorTypeEnum.EXISTS: - return undefined; - case OperatorTypeEnum.LIST: - return item.list.id; - default: - return undefined; - } -}; - -/** - * Determines whether an entire entry, exception item, or entry within a nested - * entry needs to be removed - * - * @param exceptionItem - * @param entryIndex index of given entry, for nested entries, this will correspond - * to their parent index - * @param nestedEntryIndex index of nested entry - * - */ -export const getUpdatedEntriesOnDelete = ( - exceptionItem: ExceptionsBuilderExceptionItem, - entryIndex: number, - nestedParentIndex: number | null -): ExceptionsBuilderExceptionItem => { - const itemOfInterest: BuilderEntry = - exceptionItem.entries[nestedParentIndex != null ? nestedParentIndex : entryIndex]; - - if (nestedParentIndex != null && itemOfInterest.type === OperatorTypeEnum.NESTED) { - const updatedEntryEntries = [ - ...itemOfInterest.entries.slice(0, entryIndex), - ...itemOfInterest.entries.slice(entryIndex + 1), - ]; - - if (updatedEntryEntries.length === 0) { - return { - ...exceptionItem, - entries: [ - ...exceptionItem.entries.slice(0, nestedParentIndex), - ...exceptionItem.entries.slice(nestedParentIndex + 1), - ], - }; - } else { - const { field } = itemOfInterest; - const updatedItemOfInterest: EntryNested | EmptyNestedEntry = { - entries: updatedEntryEntries, - field, - id: itemOfInterest.id != null ? itemOfInterest.id : `${entryIndex}`, - type: OperatorTypeEnum.NESTED, - }; - - return { - ...exceptionItem, - entries: [ - ...exceptionItem.entries.slice(0, nestedParentIndex), - updatedItemOfInterest, - ...exceptionItem.entries.slice(nestedParentIndex + 1), - ], - }; - } - } else { - return { - ...exceptionItem, - entries: [ - ...exceptionItem.entries.slice(0, entryIndex), - ...exceptionItem.entries.slice(entryIndex + 1), - ], - }; - } -}; - -/** - * Returns filtered index patterns based on the field - if a user selects to - * add nested entry, should only show nested fields, if item is the parent - * field of a nested entry, we only display the parent field - * - * @param patterns DataViewBase containing available fields on rule index - * @param item exception item entry - * set to add a nested field - */ -export const getFilteredIndexPatterns = ( - patterns: DataViewBase, - item: FormattedBuilderEntry -): DataViewBase => { - if (item.nested === 'child' && item.parent != null) { - // when user has selected a nested entry, only fields with the common parent are shown - return { - ...patterns, - fields: patterns.fields - .filter((indexField) => { - const subTypeNested = getDataViewFieldSubtypeNested(indexField); - const fieldHasCommonParentPath = - subTypeNested && - item.parent != null && - subTypeNested.nested.path === item.parent.parent.field; - - return fieldHasCommonParentPath; - }) - .map((f) => { - const [fieldNameWithoutParentPath] = f.name.split('.').slice(-1); - return { ...f, name: fieldNameWithoutParentPath }; - }), - }; - } else if (item.nested === 'parent' && item.field != null) { - // when user has selected a nested entry, right above it we show the common parent - return { ...patterns, fields: [item.field] }; - } else if (item.nested === 'parent' && item.field == null) { - // when user selects to add a nested entry, only nested fields are shown as options - return { - ...patterns, - fields: patterns.fields.filter((field) => isDataViewFieldSubtypeNested(field)), - }; - } else { - return patterns; - } -}; - -/** - * Determines proper entry update when user selects new field - * - * @param item - current exception item entry values - * @param newField - newly selected field - * - */ -export const getEntryOnFieldChange = ( - item: FormattedBuilderEntry, - newField: DataViewFieldBase -): { index: number; updatedEntry: BuilderEntry } => { - const { parent, entryIndex, nested } = item; - const newChildFieldValue = newField != null ? newField.name.split('.').slice(-1)[0] : ''; - - if (nested === 'parent') { - // For nested entries, when user first selects to add a nested - // entry, they first see a row similar to what is shown for when - // a user selects "exists", as soon as they make a selection - // we can now identify the 'parent' and 'child' this is where - // we first convert the entry into type "nested" - const subTypeNested = getDataViewFieldSubtypeNested(newField); - const newParentFieldValue = subTypeNested?.nested.path || ''; - - return { - index: entryIndex, - updatedEntry: { - entries: [ - addIdToItem({ - field: newChildFieldValue != null ? newChildFieldValue : '', - operator: isOperator.operator, - type: OperatorTypeEnum.MATCH, - value: '', - }), - ], - field: newParentFieldValue, - id: item.id, - type: OperatorTypeEnum.NESTED, - }, - }; - } else if (nested === 'child' && parent != null) { - return { - index: parent.parentIndex, - updatedEntry: { - ...parent.parent, - entries: [ - ...parent.parent.entries.slice(0, entryIndex), - { - field: newChildFieldValue != null ? newChildFieldValue : '', - id: item.id, - operator: isOperator.operator, - type: OperatorTypeEnum.MATCH, - value: '', - }, - ...parent.parent.entries.slice(entryIndex + 1), - ], - }, - }; - } else { - return { - index: entryIndex, - updatedEntry: { - field: newField != null ? newField.name : '', - id: item.id, - operator: isOperator.operator, - type: OperatorTypeEnum.MATCH, - value: '', - }, - }; - } -}; - -/** - * Determines proper entry update when user updates value - * when operator is of type "list" - * - * @param item - current exception item entry values - * @param newField - newly selected list - * - */ -export const getEntryOnListChange = ( - item: FormattedBuilderEntry, - newField: ListSchema -): { index: number; updatedEntry: BuilderEntry } => { - const { entryIndex, field, operator } = item; - const { id, type } = newField; - - return { - index: entryIndex, - updatedEntry: { - field: field != null ? field.name : '', - id: item.id, - list: { id, type }, - operator: operator.operator, - type: OperatorTypeEnum.LIST, - }, - }; -}; - -/** - * Determines proper entry update when user updates value - * when operator is of type "match_any" - * - * @param item - current exception item entry values - * @param newField - newly entered value - * - */ -export const getEntryOnMatchAnyChange = ( - item: FormattedBuilderEntry, - newField: string[] -): { index: number; updatedEntry: BuilderEntry } => { - const { nested, parent, entryIndex, field, operator } = item; - - if (nested != null && parent != null) { - const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; - - return { - index: parent.parentIndex, - updatedEntry: { - ...parent.parent, - entries: [ - ...parent.parent.entries.slice(0, entryIndex), - { - field: fieldName, - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.MATCH_ANY, - value: newField, - }, - ...parent.parent.entries.slice(entryIndex + 1), - ], - }, - }; - } else { - return { - index: entryIndex, - updatedEntry: { - field: field != null ? field.name : '', - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.MATCH_ANY, - value: newField, - }, - }; - } -}; - -/** - * Determines proper entry update when user updates value - * when operator is of type "match" - * - * @param item - current exception item entry values - * @param newField - newly entered value - * - */ -export const getEntryOnMatchChange = ( - item: FormattedBuilderEntry, - newField: string -): { index: number; updatedEntry: BuilderEntry } => { - const { nested, parent, entryIndex, field, operator } = item; - - if (nested != null && parent != null) { - const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; - - return { - index: parent.parentIndex, - updatedEntry: { - ...parent.parent, - entries: [ - ...parent.parent.entries.slice(0, entryIndex), - { - field: fieldName, - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.MATCH, - value: newField, - }, - ...parent.parent.entries.slice(entryIndex + 1), - ], - }, - }; - } else { - return { - index: entryIndex, - updatedEntry: { - field: field != null ? field.name : '', - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.MATCH, - value: newField, - }, - }; - } -}; - -/** - * Determines proper entry update when user updates value - * when operator is of type "wildcard" - * - * @param item - current exception item entry values - * @param newField - newly entered value - * - */ -export const getEntryOnWildcardChange = ( - item: FormattedBuilderEntry, - newField: string -): { index: number; updatedEntry: BuilderEntry } => { - const { nested, parent, entryIndex, field, operator } = item; - - if (nested != null && parent != null) { - const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; - - return { - index: parent.parentIndex, - updatedEntry: { - ...parent.parent, - entries: [ - ...parent.parent.entries.slice(0, entryIndex), - { - field: fieldName, - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.WILDCARD, - value: newField, - }, - ...parent.parent.entries.slice(entryIndex + 1), - ], - }, - }; - } else { - return { - index: entryIndex, - updatedEntry: { - field: field != null ? field.name : '', - id: item.id, - operator: operator.operator, - type: OperatorTypeEnum.WILDCARD, - value: newField, - }, - }; - } -}; - -/** - * On operator change, determines whether value needs to be cleared or not - * - * @param field - * @param selectedOperator - * @param currentEntry - * - */ -export const getEntryFromOperator = ( - selectedOperator: OperatorOption, - currentEntry: FormattedBuilderEntry -): Entry & { id?: string } => { - const isSameOperatorType = currentEntry.operator.type === selectedOperator.type; - const fieldValue = currentEntry.field != null ? currentEntry.field.name : ''; - switch (selectedOperator.type) { - case 'match': - return { - field: fieldValue, - id: currentEntry.id, - operator: selectedOperator.operator, - type: OperatorTypeEnum.MATCH, - value: - isSameOperatorType && typeof currentEntry.value === 'string' ? currentEntry.value : '', - }; - case 'match_any': - return { - field: fieldValue, - id: currentEntry.id, - operator: selectedOperator.operator, - type: OperatorTypeEnum.MATCH_ANY, - value: isSameOperatorType && Array.isArray(currentEntry.value) ? currentEntry.value : [], - }; - case 'list': - return { - field: fieldValue, - id: currentEntry.id, - list: { id: '', type: 'ip' }, - operator: selectedOperator.operator, - type: OperatorTypeEnum.LIST, - }; - case 'wildcard': - return { - field: fieldValue, - id: currentEntry.id, - operator: selectedOperator.operator, - type: OperatorTypeEnum.WILDCARD, - value: - isSameOperatorType && typeof currentEntry.value === 'string' ? currentEntry.value : '', - }; - default: - return { - field: fieldValue, - id: currentEntry.id, - operator: selectedOperator.operator, - type: OperatorTypeEnum.EXISTS, - }; - } -}; - -/** - * Determines proper entry update when user selects new operator - * - * @param item - current exception item entry values - * @param newOperator - newly selected operator - * - */ -export const getEntryOnOperatorChange = ( - item: FormattedBuilderEntry, - newOperator: OperatorOption -): { updatedEntry: BuilderEntry; index: number } => { - const { parent, entryIndex, field, nested } = item; - const newEntry = getEntryFromOperator(newOperator, item); - - if (!entriesList.is(newEntry) && nested != null && parent != null) { - return { - index: parent.parentIndex, - updatedEntry: { - ...parent.parent, - entries: [ - ...parent.parent.entries.slice(0, entryIndex), - { - ...newEntry, - field: field != null ? field.name.split('.').slice(-1)[0] : '', - }, - ...parent.parent.entries.slice(entryIndex + 1), - ], - }, - }; - } else { - return { index: entryIndex, updatedEntry: newEntry }; - } -}; - -export const isKibanaStringType = (type: string) => { - const kbnFieldType = castEsToKbnFieldTypeName(type); - return kbnFieldType === KBN_FIELD_TYPES.STRING; -}; - -export const fieldSupportsMatches = (field: DataViewFieldBase) => { - return field.esTypes?.some(isKibanaStringType); -}; - -/** - * Determines which operators to make available - * - * @param item - * @param listType - * @param isBoolean - * @param includeValueListOperators whether or not to include the 'is in list' and 'is not in list' operators - */ -export const getOperatorOptions = ( - item: FormattedBuilderEntry, - listType: ExceptionListType, - isBoolean: boolean, - includeValueListOperators = true -): OperatorOption[] => { - if (item.nested === 'parent' || item.field == null) { - return [isOperator]; - } else if (listType === 'endpoint') { - if (isBoolean) { - return [isOperator]; - } else { - return fieldSupportsMatches(item.field) - ? [isOperator, isOneOfOperator, matchesOperator, doesNotMatchOperator] - : [isOperator, isOneOfOperator]; - } - } else if (item.nested != null && listType === 'detection') { - return isBoolean ? [isOperator, existsOperator] : [isOperator, isOneOfOperator, existsOperator]; - } else if (isBoolean) { - return [isOperator, isNotOperator, existsOperator, doesNotExistOperator]; - } else if (!includeValueListOperators) { - return fieldSupportsMatches(item.field) - ? EXCEPTION_OPERATORS_SANS_LISTS - : [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - existsOperator, - doesNotExistOperator, - ]; - } else { - return listType === 'detection' - ? fieldSupportsMatches(item.field) - ? DETECTION_ENGINE_EXCEPTION_OPERATORS - : [ - isOperator, - isNotOperator, - isOneOfOperator, - isNotOneOfOperator, - existsOperator, - doesNotExistOperator, - isInListOperator, - isNotInListOperator, - ] - : ALL_OPERATORS; - } -}; - -/** - * Fields of type 'text' do not generate autocomplete values, we want - * to find it's corresponding keyword type (if available) which does - * generate autocomplete values - * - * @param fields DataViewFieldBase fields - * @param selectedField the field name that was selected - * @param isTextType we only want a corresponding keyword field if - * the selected field is of type 'text' - * - */ -export const getCorrespondingKeywordField = ({ - fields, - selectedField, -}: { - fields: DataViewFieldBase[]; - selectedField: string | undefined; -}): DataViewFieldBase | undefined => { - const selectedFieldBits = - selectedField != null && selectedField !== '' ? selectedField.split('.') : []; - const selectedFieldIsTextType = selectedFieldBits.slice(-1)[0] === 'text'; - - if (selectedFieldIsTextType && selectedFieldBits.length > 0) { - const keywordField = selectedFieldBits.slice(0, selectedFieldBits.length - 1).join('.'); - const [foundKeywordField] = fields.filter( - ({ name }) => keywordField !== '' && keywordField === name - ); - return foundKeywordField; - } - - return undefined; -}; - -/** - * Formats the entry into one that is easily usable for the UI, most of the - * complexity was introduced with nested fields - * - * @param patterns DataViewBase containing available fields on rule index - * @param item exception item entry - * @param itemIndex entry index - * @param parent nested entries hold copy of their parent for use in various logic - * @param parentIndex corresponds to the entry index, this might seem obvious, but - * was added to ensure that nested items could be identified with their parent entry - * @param allowCustomFieldOptions determines if field must be found to match in indexPattern or not - */ -export const getFormattedBuilderEntry = ( - indexPattern: DataViewBase, - item: BuilderEntry, - itemIndex: number, - parent: EntryNested | undefined, - parentIndex: number | undefined, - allowCustomFieldOptions: boolean -): FormattedBuilderEntry => { - const { fields } = indexPattern; - const field = parent != null ? `${parent.field}.${item.field}` : item.field; - const [foundField] = fields.filter(({ name }) => field != null && field === name); - const correspondingKeywordField = getCorrespondingKeywordField({ - fields, - selectedField: field, - }); - - if (parent != null && parentIndex != null) { - return { - correspondingKeywordField, - entryIndex: itemIndex, - field: - foundField != null - ? { ...foundField, name: foundField.name.split('.').slice(-1)[0] } - : foundField, - id: item.id != null ? item.id : `${itemIndex}`, - nested: 'child', - operator: getExceptionOperatorSelect(item), - parent: { parent, parentIndex }, - value: getEntryValue(item), - }; - } else { - const fieldToUse = allowCustomFieldOptions - ? foundField ?? { name: item.field, type: 'keyword' } - : foundField; - - return { - correspondingKeywordField, - entryIndex: itemIndex, - field: fieldToUse, - id: item.id != null ? item.id : `${itemIndex}`, - nested: undefined, - operator: getExceptionOperatorSelect(item), - parent: undefined, - value: getEntryValue(item), - }; - } -}; - -/** - * Formats the entries to be easily usable for the UI, most of the - * complexity was introduced with nested fields - * - * @param patterns DataViewBase containing available fields on rule index - * @param entries exception item entries - * @param allowCustomFieldOptions determines if field must be found to match in indexPattern or not - * @param parent nested entries hold copy of their parent for use in various logic - * @param parentIndex corresponds to the entry index, this might seem obvious, but - * was added to ensure that nested items could be identified with their parent entry - */ -export const getFormattedBuilderEntries = ( - indexPattern: DataViewBase, - entries: BuilderEntry[], - allowCustomFieldOptions: boolean, - parent?: EntryNested, - parentIndex?: number -): FormattedBuilderEntry[] => { - return entries.reduce((acc, item, index) => { - const isNewNestedEntry = item.type === 'nested' && item.entries.length === 0; - if (item.type !== 'nested' && !isNewNestedEntry) { - const newItemEntry: FormattedBuilderEntry = getFormattedBuilderEntry( - indexPattern, - item, - index, - parent, - parentIndex, - allowCustomFieldOptions - ); - return [...acc, newItemEntry]; - } else { - const parentEntry: FormattedBuilderEntry = { - correspondingKeywordField: undefined, - entryIndex: index, - field: isNewNestedEntry - ? undefined - : // This type below is really a FieldSpec type from "src/plugins/data/common/index_patterns/fields/types.ts", we cast it here to keep using the DataViewFieldBase interface - ({ - aggregatable: false, - esTypes: ['nested'], - name: item.field != null ? item.field : '', - searchable: false, - type: 'string', - } as DataViewFieldBase), - id: item.id != null ? item.id : `${index}`, - nested: 'parent', - operator: isOperator, - parent: undefined, - value: undefined, - }; - - // User has selected to add a nested field, but not yet selected the field - if (isNewNestedEntry) { - return [...acc, parentEntry]; - } - - if (isEntryNested(item)) { - const nestedItems = getFormattedBuilderEntries( - indexPattern, - item.entries, - allowCustomFieldOptions, - item, - index - ); - - return [...acc, parentEntry, ...nestedItems]; - } - - return [...acc]; - } - }, []); -}; - -export const getDefaultEmptyEntry = (): EmptyEntry => ({ - field: '', - id: uuidv4(), - operator: OperatorEnum.INCLUDED, - type: OperatorTypeEnum.MATCH, - value: '', -}); - -export const getDefaultNestedEmptyEntry = (): EmptyNestedEntry => ({ - entries: [], - field: '', - id: uuidv4(), - type: OperatorTypeEnum.NESTED, -}); - -export const containsValueListEntry = (items: ExceptionsBuilderExceptionItem[]): boolean => - items.some((item) => item.entries.some(({ type }) => type === OperatorTypeEnum.LIST)); - -export const buildShowActiveExceptionsFilter = (savedObjectPrefix: SavedObjectType[]): string => { - const now = new Date().toISOString(); - const filters = savedObjectPrefix.map( - (prefix) => - `${prefix}.attributes.expire_time > "${now}" OR NOT ${prefix}.attributes.expire_time: *` - ); - return filters.join(','); -}; - -export const buildShowExpiredExceptionsFilter = (savedObjectPrefix: SavedObjectType[]): string => { - const now = new Date().toISOString(); - const filters = savedObjectPrefix.map((prefix) => `${prefix}.attributes.expire_time <= "${now}"`); - return filters.join(','); -}; - -const getIndexGroupName = (indexName: string): string => { - // Check whether it is a Data Stream index - const dataStreamExp = /.ds-(.*?)-[0-9]{4}\.[0-9]{2}\.[0-9]{2}-[0-9]{6}/; - let result = indexName.match(dataStreamExp); - if (result && result.length === 2) { - return result[1]; - } - - // Check whether it is an old '.siem' index group - const siemSignalsExp = /.siem-(.*?)-[0-9]{6}/; - result = indexName.match(siemSignalsExp); - if (result && result.length === 2) { - return `.siem-${result[1]}`; - } - - // Otherwise return index name - return indexName; -}; - -export interface FieldConflictsInfo { - /** - * Kibana field type - */ - type: string; - /** - * Total count of the indices of this type - */ - totalIndexCount: number; - /** - * Grouped indices info - */ - groupedIndices: Array<{ - /** - * Index group name (like '.ds-...' or '.siem-signals-...') - */ - name: string; - /** - * Count of indices in the group - */ - count: number; - }>; -} - -export const getMappingConflictsInfo = (field: DataViewField): FieldConflictsInfo[] | null => { - if (!field.conflictDescriptions) { - return null; - } - const conflicts: FieldConflictsInfo[] = []; - for (const [key, value] of Object.entries(field.conflictDescriptions)) { - const groupedIndices: Array<{ - name: string; - count: number; - }> = []; - - // Group indices and calculate count of indices in each group - const groupedInfo: { [key: string]: number } = {}; - value.forEach((index) => { - const groupName = getIndexGroupName(index); - if (!groupedInfo[groupName]) { - groupedInfo[groupName] = 0; - } - groupedInfo[groupName]++; - }); - for (const [name, count] of Object.entries(groupedInfo)) { - groupedIndices.push({ - name, - count, - }); - } - - // Sort groups by the indices count - groupedIndices.sort((group1, group2) => { - return group2.count - group1.count; - }); - - conflicts.push({ - type: key, - totalIndexCount: value.length, - groupedIndices, - }); - } - return conflicts; -}; - -/** - * Given an exceptions list, determine if any entries have an "IS" operator with a wildcard value - */ -export const hasWrongOperatorWithWildcard = ( - items: ExceptionsBuilderReturnExceptionItem[] -): boolean => { - // flattens array of multiple entries added with OR - const multipleEntries = items.flatMap((item) => item.entries); - // flattens nested entries - const allEntries = multipleEntries.flatMap((item) => { - if (item.type === 'nested') { - return item.entries; - } - return item; - }); - - return allEntries.some((e) => { - if (e.type !== 'list' && 'value' in e) { - return validateHasWildcardWithWrongOperator({ - operator: e.type, - value: e.value, - }); - } - }); -}; - -/** - * Event filters helper where given an exceptions list, - * determine if both 'subject_name' and 'trusted' are - * included in an entry with 'code_signature' - */ -export const hasPartialCodeSignatureEntry = ( - items: ExceptionsBuilderReturnExceptionItem[] -): boolean => { - const { os_types: os = ['windows'], entries = [] } = items[0] || {}; - let name = false; - let trusted = false; - - for (const e of entries) { - if (e.type === 'nested' && e.field === 'process.Ext.code_signature') { - const includesNestedName = e.entries.some( - (nestedEntry) => nestedEntry.field === 'subject_name' - ); - const includesNestedTrusted = e.entries.some( - (nestedEntry) => nestedEntry.field === 'trusted' - ); - if (includesNestedName !== includesNestedTrusted) { - return true; - } - } else if ( - e.field === 'process.code_signature.subject_name' || - (os.includes('macos') && e.field === 'process.code_signature.team_id') - ) { - name = true; - } else if (e.field === 'process.code_signature.trusted') { - trusted = true; - } - } - return name !== trusted; -}; diff --git a/packages/kbn-securitysolution-list-utils/src/types/index.ts b/packages/kbn-securitysolution-list-utils/src/types/index.ts deleted file mode 100644 index 97098af88caf..000000000000 --- a/packages/kbn-securitysolution-list-utils/src/types/index.ts +++ /dev/null @@ -1,124 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataViewFieldBase } from '@kbn/es-query'; -import type { - CreateExceptionListItemSchema, - CreateRuleExceptionListItemSchema, - Entry, - EntryExists, - EntryMatch, - EntryMatchAny, - EntryMatchWildcard, - EntryNested, - ExceptionListItemSchema, - ListOperatorEnum as OperatorEnum, - ListOperatorTypeEnum as OperatorTypeEnum, - NamespaceType, -} from '@kbn/securitysolution-io-ts-list-types'; -import { - EXCEPTION_LIST_NAMESPACE, - EXCEPTION_LIST_NAMESPACE_AGNOSTIC, -} from '@kbn/securitysolution-list-constants'; - -export interface DataViewField extends DataViewFieldBase { - conflictDescriptions?: Record; -} - -export interface OperatorOption { - message: string; - value: string; - operator: OperatorEnum; - type: OperatorTypeEnum; -} - -export interface FormattedBuilderEntry { - id: string; - field: DataViewField | undefined; - operator: OperatorOption; - value: string | string[] | undefined; - nested: 'parent' | 'child' | undefined; - entryIndex: number; - parent: { parent: BuilderEntryNested; parentIndex: number } | undefined; - correspondingKeywordField: DataViewFieldBase | undefined; -} - -export interface EmptyEntry { - id: string; - field: string | undefined; - operator: OperatorEnum; - type: OperatorTypeEnum.MATCH | OperatorTypeEnum.MATCH_ANY | OperatorTypeEnum.WILDCARD; - value: string | string[] | undefined; -} - -export interface EmptyListEntry { - id: string; - field: string | undefined; - operator: OperatorEnum; - type: OperatorTypeEnum.LIST; - list: { id: string | undefined; type: string | undefined }; -} - -export interface EmptyNestedEntry { - id: string; - field: string | undefined; - type: OperatorTypeEnum.NESTED; - entries: Array< - | (EntryMatch & { id?: string }) - | (EntryMatchAny & { id?: string }) - | (EntryMatchWildcard & { id?: string }) - | (EntryExists & { id?: string }) - >; -} - -export type BuilderEntry = - | (Entry & { id?: string }) - | EmptyListEntry - | EmptyEntry - | BuilderEntryNested - | EmptyNestedEntry; - -export type BuilderEntryNested = Omit & { - id?: string; - entries: Array< - | (EntryMatch & { id?: string }) - | (EntryMatchAny & { id?: string }) - | (EntryMatchWildcard & { id?: string }) - | (EntryExists & { id?: string }) - >; -}; - -export type ExceptionListItemBuilderSchema = Omit & { - entries: BuilderEntry[]; -}; - -export type CreateExceptionListItemBuilderSchema = Omit< - CreateExceptionListItemSchema, - 'meta' | 'entries' | 'list_id' | 'namespace_type' -> & { - meta: { temporaryUuid: string }; - entries: BuilderEntry[]; - list_id: string | undefined; - namespace_type: NamespaceType | undefined; -}; - -export type ExceptionsBuilderExceptionItem = - | ExceptionListItemBuilderSchema - | CreateExceptionListItemBuilderSchema; - -export type ExceptionsBuilderReturnExceptionItem = - | ExceptionListItemSchema - | CreateExceptionListItemSchema - | CreateRuleExceptionListItemSchema; - -export const exceptionListSavedObjectType = EXCEPTION_LIST_NAMESPACE; -export const exceptionListAgnosticSavedObjectType = EXCEPTION_LIST_NAMESPACE_AGNOSTIC; -export type SavedObjectType = - | typeof EXCEPTION_LIST_NAMESPACE - | typeof EXCEPTION_LIST_NAMESPACE_AGNOSTIC; diff --git a/packages/kbn-securitysolution-list-utils/tsconfig.json b/packages/kbn-securitysolution-list-utils/tsconfig.json deleted file mode 100644 index d75eb1f98314..000000000000 --- a/packages/kbn-securitysolution-list-utils/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/es-query", - "@kbn/i18n", - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-io-ts-utils", - "@kbn/securitysolution-list-constants", - "@kbn/securitysolution-utils", - "@kbn/field-types" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts b/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts deleted file mode 100644 index ce05117c3308..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Create list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { - ListId, - ListName, - ListDescription, - ListType, - ListMetadata, -} from '../model/list_common.gen'; -import { List } from '../model/list_schemas.gen'; - -export type CreateListRequestBody = z.infer; -export const CreateListRequestBody = z.object({ - id: ListId.optional(), - name: ListName, - description: ListDescription, - type: ListType, - serializer: z.string().optional(), - deserializer: z.string().optional(), - meta: ListMetadata.optional(), - version: z.number().int().min(1).optional().default(1), -}); -export type CreateListRequestBodyInput = z.input; - -export type CreateListResponse = z.infer; -export const CreateListResponse = List; diff --git a/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml b/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml deleted file mode 100644 index 191e973beba6..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml +++ /dev/null @@ -1,81 +0,0 @@ -openapi: 3.0.0 -info: - title: Create list API endpoint - version: '2023-10-31' -paths: - /api/lists: - post: - x-labels: [serverless, ess] - operationId: CreateList - x-codegen-enabled: true - summary: Create a list - description: Create a new list. - requestBody: - description: List's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - name: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' - description: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' - type: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListType' - serializer: - type: string - deserializer: - type: string - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' - version: - type: integer - minimum: 1 - default: 1 - required: - - name - - description - - type - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 409: - description: List already exists response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.ts b/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.ts deleted file mode 100644 index 13b5248b9270..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Create list DS API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -export type CreateListIndexResponse = z.infer; -export const CreateListIndexResponse = z.object({ - acknowledged: z.boolean(), -}); diff --git a/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml b/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml deleted file mode 100644 index c775a9c7d873..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml +++ /dev/null @@ -1,55 +0,0 @@ -openapi: 3.0.0 -info: - title: Create list DS API endpoint - version: '2023-10-31' -paths: - /api/lists/index: - post: - x-labels: [serverless, ess] - operationId: CreateListIndex - x-codegen-enabled: true - summary: Create list data streams - description: Create `.lists` and `.items` data streams in the relevant space. - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - acknowledged: - type: boolean - required: [acknowledged] - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 409: - description: List data stream exists response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.ts b/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.ts deleted file mode 100644 index 4ebafd656857..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Create list item API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListItemId, ListId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; -import { ListItem } from '../model/list_schemas.gen'; - -export type CreateListItemRequestBody = z.infer; -export const CreateListItemRequestBody = z.object({ - id: ListItemId.optional(), - list_id: ListId, - value: ListItemValue, - meta: ListItemMetadata.optional(), - /** - * Determines when changes made by the request are made visible to search - */ - refresh: z.enum(['true', 'false', 'wait_for']).optional(), -}); -export type CreateListItemRequestBodyInput = z.input; - -export type CreateListItemResponse = z.infer; -export const CreateListItemResponse = ListItem; diff --git a/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml b/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml deleted file mode 100644 index 01121d014392..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml +++ /dev/null @@ -1,82 +0,0 @@ -openapi: 3.0.0 -info: - title: Create list item API endpoint - version: '2023-10-31' -paths: - /api/lists/items: - post: - x-labels: [serverless, ess] - operationId: CreateListItem - x-codegen-enabled: true - summary: Create a list item - description: | - Create a list item and associate it with the specified list. - - All list items in the same list must be the same type. For example, each list item in an `ip` list must define a specific IP address. - > info - > Before creating a list item, you must create a list. - requestBody: - description: List item's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' - list_id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - value: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' - refresh: - type: string - enum: - - 'true' - - 'false' - - wait_for - description: Determines when changes made by the request are made visible to search - required: - - list_id - - value - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 409: - description: List item already exists response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts b/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts deleted file mode 100644 index 109e6c58a116..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Delete list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; -import { BooleanFromString } from '@kbn/zod-helpers'; - -import { ListId } from '../model/list_common.gen'; -import { List } from '../model/list_schemas.gen'; - -export type DeleteListRequestQuery = z.infer; -export const DeleteListRequestQuery = z.object({ - /** - * List's `id` value - */ - id: ListId, - deleteReferences: BooleanFromString.optional().default(false), - ignoreReferences: BooleanFromString.optional().default(false), -}); -export type DeleteListRequestQueryInput = z.input; - -export type DeleteListResponse = z.infer; -export const DeleteListResponse = List; diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml b/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml deleted file mode 100644 index 709875363637..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml +++ /dev/null @@ -1,73 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete list API endpoint - version: '2023-10-31' -paths: - /api/lists: - delete: - x-labels: [serverless, ess] - operationId: DeleteList - x-codegen-enabled: true - summary: Delete a list - description: | - Delete a list using the list ID. - > info - > When you delete a list, all of its list items are also deleted. - parameters: - - name: id - in: query - required: true - description: List's `id` value - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: deleteReferences - in: query - required: false - schema: - type: boolean - default: false - - name: ignoreReferences - in: query - required: false - schema: - type: boolean - default: false - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.ts b/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.ts deleted file mode 100644 index 314c1e81bc6a..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Delete list DS API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -export type DeleteListIndexResponse = z.infer; -export const DeleteListIndexResponse = z.object({ - acknowledged: z.boolean(), -}); diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml b/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml deleted file mode 100644 index 4f4b0f00e881..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml +++ /dev/null @@ -1,55 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete list DS API endpoint - version: '2023-10-31' -paths: - /api/lists/index: - delete: - x-labels: [serverless, ess] - operationId: DeleteListIndex - x-codegen-enabled: true - summary: Delete list data streams - description: Delete the `.lists` and `.items` data streams. - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - acknowledged: - type: boolean - required: [acknowledged] - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List data stream not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml b/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml deleted file mode 100644 index 28913259387d..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml +++ /dev/null @@ -1,82 +0,0 @@ -openapi: 3.0.0 -info: - title: Delete list item API endpoint - version: '2023-10-31' -paths: - /api/lists/items: - delete: - x-labels: [serverless, ess] - operationId: DeleteListItem - x-codegen-enabled: true - summary: Delete a list item - description: Delete a list item using its `id`, or its `list_id` and `value` fields. - parameters: - - name: id - in: query - required: false - description: Required if `list_id` and `value` are not specified - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: list_id - in: query - required: false - description: Required if `id` is not specified - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: value - in: query - required: false - description: Required if `id` is not specified - schema: - type: string - - name: refresh - in: query - required: false - description: Determines when changes made by the request are made visible to search - schema: - type: string - enum: ['true', 'false', 'wait_for'] - default: 'false' - responses: - 200: - description: Successful response - content: - application/json: - schema: - oneOf: - - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - - type: array - items: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.ts b/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.ts deleted file mode 100644 index 4e514abefccc..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Export list items API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListId } from '../model/list_common.gen'; - -export type ExportListItemsRequestQuery = z.infer; -export const ExportListItemsRequestQuery = z.object({ - /** - * List's id to export - */ - list_id: ListId, -}); -export type ExportListItemsRequestQueryInput = z.input; diff --git a/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml b/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml deleted file mode 100644 index 8d185a23b64c..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml +++ /dev/null @@ -1,60 +0,0 @@ -openapi: 3.0.0 -info: - title: Export list items API endpoint - version: '2023-10-31' -paths: - /api/lists/items/_export: - post: - x-labels: [serverless, ess] - operationId: ExportListItems - x-codegen-enabled: true - summary: Export list items - description: Export list item values from the specified list. - parameters: - - name: list_id - in: query - required: true - description: List's id to export - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - responses: - 200: - description: Successful response - content: - application/ndjson: - schema: - type: string - format: binary - description: A `.txt` file containing list items from the specified list - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml b/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml deleted file mode 100644 index 3bb55decacff..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml +++ /dev/null @@ -1,118 +0,0 @@ -openapi: 3.0.0 -info: - title: Find lists API endpoint - version: '2023-10-31' -paths: - /api/lists/_find: - get: - x-labels: [serverless, ess] - operationId: FindLists - x-codegen-enabled: true - summary: Get lists - description: Get a paginated subset of lists. By default, the first page is returned, with 20 results per page. - parameters: - - name: page - in: query - required: false - description: The page number to return - schema: - type: integer - - name: per_page - in: query - required: false - description: The number of lists to return per page - schema: - type: integer - - name: sort_field - in: query - required: false - description: Determines which field is used to sort the results - schema: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - name: sort_order - in: query - required: false - description: Determines the sort order, which can be `desc` or `asc` - schema: - type: string - enum: [desc, asc] - - name: cursor - in: query - required: false - description: | - Returns the list that come after the last list returned in the previous call - (use the cursor value returned in the previous call). This parameter uses - the `tie_breaker_id` field to ensure all lists are sorted and returned correctly. - schema: - $ref: '#/components/schemas/FindListsCursor' - - name: filter - in: query - required: false - description: | - Filters the returned results according to the value of the specified field, - using the : syntax. - schema: - $ref: '#/components/schemas/FindListsFilter' - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - data: - type: array - items: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - page: - type: integer - minimum: 0 - per_page: - type: integer - minimum: 0 - total: - type: integer - minimum: 0 - cursor: - $ref: '#/components/schemas/FindListsCursor' - required: - - data - - page - - per_page - - total - - cursor - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - -components: - schemas: - FindListsCursor: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - FindListsFilter: - type: string diff --git a/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml b/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml deleted file mode 100644 index 520213e949c1..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml +++ /dev/null @@ -1,101 +0,0 @@ -openapi: 3.0.0 -info: - title: Import list items API endpoint - version: '2023-10-31' -paths: - /api/lists/items/_import: - post: - x-labels: [serverless, ess] - operationId: ImportListItems - x-codegen-enabled: true - summary: Import list items - description: | - Import list items from a TXT or CSV file. The maximum file size is 9 million bytes. - - You can import items to a new or existing list. - requestBody: - required: true - content: - multipart/form-data: - schema: - type: object - properties: - file: - type: string - format: binary - description: A `.txt` or `.csv` file containing newline separated list items - parameters: - - name: list_id - in: query - required: false - description: | - List's id. - - Required when importing to an existing list. - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: type - in: query - required: false - description: | - Type of the importing list. - - Required when importing a new list that is `list_id` is not specified. - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListType' - - name: serializer - in: query - required: false - schema: - type: string - - name: deserializer - in: query - required: false - schema: - type: string - - name: refresh - in: query - required: false - description: Determines when changes made by the request are made visible to search - schema: - type: string - enum: ['true', 'false', 'wait_for'] - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 409: - description: List with specified list_id does not exist response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/index.ts b/packages/kbn-securitysolution-lists-common/api/index.ts deleted file mode 100644 index 27c70d162810..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './model/list_common.gen'; -export * from './model/list_schemas.gen'; -export * from './create_list_index/create_list_index.gen'; -export * from './create_list_item/create_list_item.gen'; -export * from './create_list/create_list.gen'; -export * from './delete_list_index/delete_list_index.gen'; -export * from './delete_list_item/delete_list_item.gen'; -export * from './delete_list/delete_list.gen'; -export * from './find_list_items/find_list_items.gen'; -export * from './find_lists/find_lists.gen'; -export * from './export_list_items/export_list_items.gen'; -export * from './import_list_items/import_list_items.gen'; -export * from './patch_list_item/patch_list_item.gen'; -export * from './patch_list/patch_list.gen'; -export * from './read_list_index/read_list_index.gen'; -export * from './read_list_item/read_list_item.gen'; -export * from './read_list/read_list.gen'; -export * from './update_list_item/update_list_item.gen'; -export * from './update_list/update_list.gen'; diff --git a/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml b/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml deleted file mode 100644 index 6fb160105bb5..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml +++ /dev/null @@ -1,59 +0,0 @@ -openapi: 3.0.0 -info: - title: Common List Attributes - version: 'not applicable' -paths: {} -components: - schemas: - ListId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListType: - type: string - enum: - - binary - - boolean - - byte - - date - - date_nanos - - date_range - - double - - double_range - - float - - float_range - - geo_point - - geo_shape - - half_float - - integer - - integer_range - - ip - - ip_range - - keyword - - long - - long_range - - shape - - short - - text - - ListName: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListDescription: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListMetadata: - type: object - additionalProperties: true - - ListItemId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListItemValue: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListItemDescription: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - - ListItemMetadata: - type: object - additionalProperties: true diff --git a/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.ts b/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.ts deleted file mode 100644 index d7c955e6daac..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Patch list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListId, ListName, ListDescription, ListMetadata } from '../model/list_common.gen'; -import { List } from '../model/list_schemas.gen'; - -export type PatchListRequestBody = z.infer; -export const PatchListRequestBody = z.object({ - id: ListId, - name: ListName.optional(), - description: ListDescription.optional(), - meta: ListMetadata.optional(), - version: z.number().int().min(1).optional(), - _version: z.string().optional(), -}); -export type PatchListRequestBodyInput = z.input; - -export type PatchListResponse = z.infer; -export const PatchListResponse = List; diff --git a/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml b/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml deleted file mode 100644 index b98b34e6347e..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml +++ /dev/null @@ -1,74 +0,0 @@ -openapi: 3.0.0 -info: - title: Patch list API endpoint - version: '2023-10-31' -paths: - /api/lists: - patch: - x-labels: [serverless, ess] - operationId: PatchList - x-codegen-enabled: true - summary: Patch a list - description: Update specific fields of an existing list using the list ID. - requestBody: - description: List's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - name: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' - description: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' - version: - type: integer - minimum: 1 - _version: - type: string - required: - - id - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.ts b/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.ts deleted file mode 100644 index 9943a9999a89..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Patch list item API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListItemId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; -import { ListItem } from '../model/list_schemas.gen'; - -export type PatchListItemRequestBody = z.infer; -export const PatchListItemRequestBody = z.object({ - id: ListItemId, - value: ListItemValue.optional(), - meta: ListItemMetadata.optional(), - _version: z.string().optional(), - /** - * Determines when changes made by the request are made visible to search - */ - refresh: z.enum(['true', 'false', 'wait_for']).optional(), -}); -export type PatchListItemRequestBodyInput = z.input; - -export type PatchListItemResponse = z.infer; -export const PatchListItemResponse = ListItem; diff --git a/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml b/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml deleted file mode 100644 index f79efc4691dd..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml +++ /dev/null @@ -1,76 +0,0 @@ -openapi: 3.0.0 -info: - title: Patch list item API endpoint - version: '2023-10-31' -paths: - /api/lists/items: - patch: - x-labels: [serverless, ess] - operationId: PatchListItem - x-codegen-enabled: true - summary: Patch a list item - description: Update specific fields of an existing list item using the list item ID. - requestBody: - description: List item's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' - value: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' - _version: - type: string - refresh: - type: string - enum: - - 'true' - - 'false' - - wait_for - description: Determines when changes made by the request are made visible to search - required: - - id - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts b/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts deleted file mode 100644 index 7bf343d935f2..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts +++ /dev/null @@ -1,430 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Lists API client for quickstart - * version: Bundle (no version) - */ - -import type { KbnClient } from '@kbn/test'; -import { ToolingLog } from '@kbn/tooling-log'; -import { ELASTIC_HTTP_VERSION_HEADER } from '@kbn/core-http-common'; -import { catchAxiosErrorFormatAndThrow } from '@kbn/securitysolution-utils'; - -import type { CreateListIndexResponse } from './create_list_index/create_list_index.gen'; -import type { - CreateListItemRequestBodyInput, - CreateListItemResponse, -} from './create_list_item/create_list_item.gen'; -import type { CreateListRequestBodyInput, CreateListResponse } from './create_list/create_list.gen'; -import type { DeleteListIndexResponse } from './delete_list_index/delete_list_index.gen'; -import type { - DeleteListItemRequestQueryInput, - DeleteListItemResponse, -} from './delete_list_item/delete_list_item.gen'; -import type { - DeleteListRequestQueryInput, - DeleteListResponse, -} from './delete_list/delete_list.gen'; -import type { ExportListItemsRequestQueryInput } from './export_list_items/export_list_items.gen'; -import type { - FindListItemsRequestQueryInput, - FindListItemsResponse, -} from './find_list_items/find_list_items.gen'; -import type { FindListsRequestQueryInput, FindListsResponse } from './find_lists/find_lists.gen'; -import type { - ImportListItemsRequestQueryInput, - ImportListItemsResponse, -} from './import_list_items/import_list_items.gen'; -import type { - PatchListItemRequestBodyInput, - PatchListItemResponse, -} from './patch_list_item/patch_list_item.gen'; -import type { PatchListRequestBodyInput, PatchListResponse } from './patch_list/patch_list.gen'; -import type { ReadListIndexResponse } from './read_list_index/read_list_index.gen'; -import type { - ReadListItemRequestQueryInput, - ReadListItemResponse, -} from './read_list_item/read_list_item.gen'; -import type { ReadListPrivilegesResponse } from './read_list_privileges/read_list_privileges.gen'; -import type { ReadListRequestQueryInput, ReadListResponse } from './read_list/read_list.gen'; -import type { - UpdateListItemRequestBodyInput, - UpdateListItemResponse, -} from './update_list_item/update_list_item.gen'; -import type { UpdateListRequestBodyInput, UpdateListResponse } from './update_list/update_list.gen'; - -export interface ClientOptions { - kbnClient: KbnClient; - log: ToolingLog; -} - -export class Client { - readonly kbnClient: KbnClient; - readonly log: ToolingLog; - - constructor(options: ClientOptions) { - this.kbnClient = options.kbnClient; - this.log = options.log; - } - /** - * Create a new list. - */ - async createList(props: CreateListProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateList`); - return this.kbnClient - .request({ - path: '/api/lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Create `.lists` and `.items` data streams in the relevant space. - */ - async createListIndex() { - this.log.info(`${new Date().toISOString()} Calling API CreateListIndex`); - return this.kbnClient - .request({ - path: '/api/lists/index', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Create a list item and associate it with the specified list. - -All list items in the same list must be the same type. For example, each list item in an `ip` list must define a specific IP address. -> info -> Before creating a list item, you must create a list. - - */ - async createListItem(props: CreateListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API CreateListItem`); - return this.kbnClient - .request({ - path: '/api/lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Delete a list using the list ID. -> info -> When you delete a list, all of its list items are also deleted. - - */ - async deleteList(props: DeleteListProps) { - this.log.info(`${new Date().toISOString()} Calling API DeleteList`); - return this.kbnClient - .request({ - path: '/api/lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'DELETE', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Delete the `.lists` and `.items` data streams. - */ - async deleteListIndex() { - this.log.info(`${new Date().toISOString()} Calling API DeleteListIndex`); - return this.kbnClient - .request({ - path: '/api/lists/index', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'DELETE', - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Delete a list item using its `id`, or its `list_id` and `value` fields. - */ - async deleteListItem(props: DeleteListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API DeleteListItem`); - return this.kbnClient - .request({ - path: '/api/lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'DELETE', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Export list item values from the specified list. - */ - async exportListItems(props: ExportListItemsProps) { - this.log.info(`${new Date().toISOString()} Calling API ExportListItems`); - return this.kbnClient - .request({ - path: '/api/lists/items/_export', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get all list items in the specified list. - */ - async findListItems(props: FindListItemsProps) { - this.log.info(`${new Date().toISOString()} Calling API FindListItems`); - return this.kbnClient - .request({ - path: '/api/lists/items/_find', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get a paginated subset of lists. By default, the first page is returned, with 20 results per page. - */ - async findLists(props: FindListsProps) { - this.log.info(`${new Date().toISOString()} Calling API FindLists`); - return this.kbnClient - .request({ - path: '/api/lists/_find', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Import list items from a TXT or CSV file. The maximum file size is 9 million bytes. - -You can import items to a new or existing list. - - */ - async importListItems(props: ImportListItemsProps) { - this.log.info(`${new Date().toISOString()} Calling API ImportListItems`); - return this.kbnClient - .request({ - path: '/api/lists/items/_import', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'POST', - body: props.attachment, - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update specific fields of an existing list using the list ID. - */ - async patchList(props: PatchListProps) { - this.log.info(`${new Date().toISOString()} Calling API PatchList`); - return this.kbnClient - .request({ - path: '/api/lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PATCH', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update specific fields of an existing list item using the list item ID. - */ - async patchListItem(props: PatchListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API PatchListItem`); - return this.kbnClient - .request({ - path: '/api/lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PATCH', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get the details of a list using the list ID. - */ - async readList(props: ReadListProps) { - this.log.info(`${new Date().toISOString()} Calling API ReadList`); - return this.kbnClient - .request({ - path: '/api/lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Verify that `.lists` and `.items` data streams exist. - */ - async readListIndex() { - this.log.info(`${new Date().toISOString()} Calling API ReadListIndex`); - return this.kbnClient - .request({ - path: '/api/lists/index', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Get the details of a list item. - */ - async readListItem(props: ReadListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API ReadListItem`); - return this.kbnClient - .request({ - path: '/api/lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - - query: props.query, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - async readListPrivileges() { - this.log.info(`${new Date().toISOString()} Calling API ReadListPrivileges`); - return this.kbnClient - .request({ - path: '/api/lists/privileges', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'GET', - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update a list using the list ID. The original list is replaced, and all unspecified fields are deleted. -> info -> You cannot modify the `id` value. - - */ - async updateList(props: UpdateListProps) { - this.log.info(`${new Date().toISOString()} Calling API UpdateList`); - return this.kbnClient - .request({ - path: '/api/lists', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PUT', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } - /** - * Update a list item using the list item ID. The original list item is replaced, and all unspecified fields are deleted. -> info -> You cannot modify the `id` value. - - */ - async updateListItem(props: UpdateListItemProps) { - this.log.info(`${new Date().toISOString()} Calling API UpdateListItem`); - return this.kbnClient - .request({ - path: '/api/lists/items', - headers: { - [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', - }, - method: 'PUT', - body: props.body, - }) - .catch(catchAxiosErrorFormatAndThrow); - } -} - -export interface CreateListProps { - body: CreateListRequestBodyInput; -} -export interface CreateListItemProps { - body: CreateListItemRequestBodyInput; -} -export interface DeleteListProps { - query: DeleteListRequestQueryInput; -} -export interface DeleteListItemProps { - query: DeleteListItemRequestQueryInput; -} -export interface ExportListItemsProps { - query: ExportListItemsRequestQueryInput; -} -export interface FindListItemsProps { - query: FindListItemsRequestQueryInput; -} -export interface FindListsProps { - query: FindListsRequestQueryInput; -} -export interface ImportListItemsProps { - query: ImportListItemsRequestQueryInput; - attachment: FormData; -} -export interface PatchListProps { - body: PatchListRequestBodyInput; -} -export interface PatchListItemProps { - body: PatchListItemRequestBodyInput; -} -export interface ReadListProps { - query: ReadListRequestQueryInput; -} -export interface ReadListItemProps { - query: ReadListItemRequestQueryInput; -} -export interface UpdateListProps { - body: UpdateListRequestBodyInput; -} -export interface UpdateListItemProps { - body: UpdateListItemRequestBodyInput; -} diff --git a/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.ts b/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.ts deleted file mode 100644 index d744eb15c9b5..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Read list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListId } from '../model/list_common.gen'; -import { List } from '../model/list_schemas.gen'; - -export type ReadListRequestQuery = z.infer; -export const ReadListRequestQuery = z.object({ - /** - * List's `id` value - */ - id: ListId, -}); -export type ReadListRequestQueryInput = z.input; - -export type ReadListResponse = z.infer; -export const ReadListResponse = List; diff --git a/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml b/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml deleted file mode 100644 index d932e16f528a..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml +++ /dev/null @@ -1,58 +0,0 @@ -openapi: 3.0.0 -info: - title: Read list API endpoint - version: '2023-10-31' -paths: - /api/lists: - get: - x-labels: [serverless, ess] - operationId: ReadList - x-codegen-enabled: true - summary: Get list details - description: Get the details of a list using the list ID. - parameters: - - name: id - in: query - required: true - description: List's `id` value - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.ts b/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.ts deleted file mode 100644 index 8a5068f72f23..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Read list DS existence status API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -export type ReadListIndexResponse = z.infer; -export const ReadListIndexResponse = z.object({ - list_index: z.boolean(), - list_item_index: z.boolean(), -}); diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml b/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml deleted file mode 100644 index b67526460015..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml +++ /dev/null @@ -1,57 +0,0 @@ -openapi: 3.0.0 -info: - title: Read list DS existence status API endpoint - version: '2023-10-31' -paths: - /api/lists/index: - get: - x-labels: [serverless, ess] - operationId: ReadListIndex - x-codegen-enabled: true - summary: Get status of list data streams - description: Verify that `.lists` and `.items` data streams exist. - responses: - 200: - description: Successful response - content: - application/json: - schema: - type: object - properties: - list_index: - type: boolean - list_item_index: - type: boolean - required: [list_index, list_item_index] - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List data stream(s) not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.ts b/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.ts deleted file mode 100644 index cd0c1d8fca26..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Read list item API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListId } from '../model/list_common.gen'; -import { ListItem } from '../model/list_schemas.gen'; - -export type ReadListItemRequestQuery = z.infer; -export const ReadListItemRequestQuery = z.object({ - /** - * Required if `list_id` and `value` are not specified - */ - id: ListId.optional(), - /** - * Required if `id` is not specified - */ - list_id: ListId.optional(), - /** - * Required if `id` is not specified - */ - value: z.string().optional(), -}); -export type ReadListItemRequestQueryInput = z.input; - -export type ReadListItemResponse = z.infer; -export const ReadListItemResponse = z.union([ListItem, z.array(ListItem)]); diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml b/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml deleted file mode 100644 index 4d686f5452e0..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml +++ /dev/null @@ -1,74 +0,0 @@ -openapi: 3.0.0 -info: - title: Read list item API endpoint - version: '2023-10-31' -paths: - /api/lists/items: - get: - x-labels: [serverless, ess] - operationId: ReadListItem - x-codegen-enabled: true - summary: Get a list item - description: Get the details of a list item. - parameters: - - name: id - in: query - required: false - description: Required if `list_id` and `value` are not specified - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: list_id - in: query - required: false - description: Required if `id` is not specified - schema: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - - name: value - in: query - required: false - description: Required if `id` is not specified - schema: - type: string - responses: - 200: - description: Successful response - content: - application/json: - schema: - oneOf: - - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - - type: array - items: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.ts b/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.ts deleted file mode 100644 index f5eb085fe4aa..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Update list API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListId, ListName, ListDescription, ListMetadata } from '../model/list_common.gen'; -import { List } from '../model/list_schemas.gen'; - -export type UpdateListRequestBody = z.infer; -export const UpdateListRequestBody = z.object({ - id: ListId, - name: ListName, - description: ListDescription, - meta: ListMetadata.optional(), - version: z.number().int().min(1).optional(), - _version: z.string().optional(), -}); -export type UpdateListRequestBodyInput = z.input; - -export type UpdateListResponse = z.infer; -export const UpdateListResponse = List; diff --git a/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml b/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml deleted file mode 100644 index c41b52427b63..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml +++ /dev/null @@ -1,79 +0,0 @@ -openapi: 3.0.0 -info: - title: Update list API endpoint - version: '2023-10-31' -paths: - /api/lists: - put: - x-labels: [serverless, ess] - operationId: UpdateList - x-codegen-enabled: true - summary: Update a list - description: | - Update a list using the list ID. The original list is replaced, and all unspecified fields are deleted. - > info - > You cannot modify the `id` value. - requestBody: - description: List's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' - name: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' - description: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' - version: - type: integer - minimum: 1 - _version: - type: string - required: - - id - - name - - description - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.ts b/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.ts deleted file mode 100644 index 052c4c979e84..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/* - * NOTICE: Do not edit this file manually. - * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. - * - * info: - * title: Update list item API endpoint - * version: 2023-10-31 - */ - -import { z } from '@kbn/zod'; - -import { ListItemId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; -import { ListItem } from '../model/list_schemas.gen'; - -export type UpdateListItemRequestBody = z.infer; -export const UpdateListItemRequestBody = z.object({ - id: ListItemId, - value: ListItemValue, - meta: ListItemMetadata.optional(), - _version: z.string().optional(), -}); -export type UpdateListItemRequestBodyInput = z.input; - -export type UpdateListItemResponse = z.infer; -export const UpdateListItemResponse = ListItem; diff --git a/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml b/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml deleted file mode 100644 index 6b05e01f35aa..000000000000 --- a/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml +++ /dev/null @@ -1,73 +0,0 @@ -openapi: 3.0.0 -info: - title: Update list item API endpoint - version: '2023-10-31' -paths: - /api/lists/items: - put: - x-labels: [serverless, ess] - operationId: UpdateListItem - x-codegen-enabled: true - summary: Update a list item - description: | - Update a list item using the list item ID. The original list item is replaced, and all unspecified fields are deleted. - > info - > You cannot modify the `id` value. - requestBody: - description: List item's properties - required: true - content: - application/json: - schema: - type: object - properties: - id: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' - value: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' - meta: - $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' - _version: - type: string - required: - - id - - value - responses: - 200: - description: Successful response - content: - application/json: - schema: - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' - 400: - description: Invalid input data response - content: - application/json: - schema: - oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 401: - description: Unsuccessful authentication response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 403: - description: Not enough privileges response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - 404: - description: List item not found response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' - 500: - description: Internal server error response - content: - application/json: - schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/package.json b/packages/kbn-securitysolution-lists-common/package.json deleted file mode 100644 index 624c2709ea73..000000000000 --- a/packages/kbn-securitysolution-lists-common/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "description": "Security Solution Lists common package", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "name": "@kbn/securitysolution-lists-common", - "private": true, - "version": "1.0.0", - "scripts": { - "openapi:generate": "node scripts/openapi_generate", - "openapi:bundle": "node scripts/openapi_bundle" - } -} diff --git a/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js b/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js deleted file mode 100644 index 7a6172475917..000000000000 --- a/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { bundle } = require('@kbn/openapi-bundler'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/serverless/security_solution_lists_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['serverless'], - prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/lists_serverless.info.yaml'), - }, - }); - - await bundle({ - sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), - outputFilePath: join( - ROOT, - 'docs/openapi/ess/security_solution_lists_api_{version}.bundled.schema.yaml' - ), - options: { - includeLabels: ['ess'], - prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/lists_ess.info.yaml'), - }, - }); -})(); diff --git a/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js b/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js deleted file mode 100644 index 7adc36ed32ca..000000000000 --- a/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -require('../../../src/setup_node_env'); -const { join, resolve } = require('path'); -const { generate } = require('@kbn/openapi-generator'); -const { REPO_ROOT } = require('@kbn/repo-info'); - -const ROOT = resolve(__dirname, '..'); - -(async () => { - await generate({ - title: 'OpenAPI Lists API Schemas', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'zod_operation_schema', - }); - - await generate({ - title: 'Lists API client for tests', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'api_client_supertest', - skipLinting: true, - bundle: { - outFile: join( - REPO_ROOT, - 'x-pack/test/api_integration/services/security_solution_lists_api.gen.ts' - ), - }, - }); - - await generate({ - title: 'Lists API client for quickstart', - rootDir: ROOT, - sourceGlob: './api/**/*.schema.yaml', - templateName: 'api_client_quickstart', - skipLinting: true, - bundle: { - outFile: join( - REPO_ROOT, - 'packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts' - ), - }, - }); -})(); diff --git a/packages/kbn-securitysolution-lists-common/tsconfig.json b/packages/kbn-securitysolution-lists-common/tsconfig.json deleted file mode 100644 index e8149be08355..000000000000 --- a/packages/kbn-securitysolution-lists-common/tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "exclude": ["target/**/*"], - "extends": "../../tsconfig.base.json", - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/zod-helpers", - "@kbn/openapi-common", - "@kbn/test", - "@kbn/tooling-log", - "@kbn/core-http-common", - "@kbn/securitysolution-utils", - "@kbn/zod", - ] -} diff --git a/packages/kbn-securitysolution-rules/tsconfig.json b/packages/kbn-securitysolution-rules/tsconfig.json deleted file mode 100644 index 9bd4f35cf62a..000000000000 --- a/packages/kbn-securitysolution-rules/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-t-grid/index.ts b/packages/kbn-securitysolution-t-grid/index.ts deleted file mode 100644 index fb5ebc443ccd..000000000000 --- a/packages/kbn-securitysolution-t-grid/index.ts +++ /dev/null @@ -1,13 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/constants'; -export * from './src/utils'; -// eslint-disable-next-line @kbn/imports/no_boundary_crossing -export * from './src/mock'; diff --git a/packages/kbn-securitysolution-t-grid/package.json b/packages/kbn-securitysolution-t-grid/package.json deleted file mode 100644 index b262a21e7dc6..000000000000 --- a/packages/kbn-securitysolution-t-grid/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@kbn/securitysolution-t-grid", - "version": "1.0.0", - "description": "security solution t-grid packages will allow sharing components between timelines and security_solution plugin until we transfer all functionality to timelines plugin", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-t-grid/src/constants/index.ts b/packages/kbn-securitysolution-t-grid/src/constants/index.ts deleted file mode 100644 index 3ff541240a8c..000000000000 --- a/packages/kbn-securitysolution-t-grid/src/constants/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const HIGHLIGHTED_DROP_TARGET_CLASS_NAME = 'highlighted-drop-target'; -export const EMPTY_PROVIDERS_GROUP_CLASS_NAME = 'empty-providers-group'; - -/** The draggable will move this many pixels via the keyboard when the arrow key is pressed */ -export const KEYBOARD_DRAG_OFFSET = 20; - -export const DRAGGABLE_KEYBOARD_WRAPPER_CLASS_NAME = 'draggable-keyboard-wrapper'; - -export const ROW_RENDERER_CLASS_NAME = 'row-renderer'; - -export const NOTES_CONTAINER_CLASS_NAME = 'notes-container'; - -export const NOTE_CONTENT_CLASS_NAME = 'note-content'; - -/** This class is added to the document body while dragging */ -export const IS_DRAGGING_CLASS_NAME = 'is-dragging'; - -export const HOVER_ACTIONS_ALWAYS_SHOW_CLASS_NAME = 'hover-actions-always-show'; diff --git a/packages/kbn-securitysolution-t-grid/src/mock/index.ts b/packages/kbn-securitysolution-t-grid/src/mock/index.ts deleted file mode 100644 index 51a5726d914f..000000000000 --- a/packages/kbn-securitysolution-t-grid/src/mock/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './mock_event_details'; diff --git a/packages/kbn-securitysolution-t-grid/src/utils/api/index.ts b/packages/kbn-securitysolution-t-grid/src/utils/api/index.ts deleted file mode 100644 index 8f7588fdeafd..000000000000 --- a/packages/kbn-securitysolution-t-grid/src/utils/api/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { has } from 'lodash/fp'; - -export interface AppError extends Error { - body: { - message: string; - }; -} - -export interface KibanaError extends AppError { - body: { - message: string; - statusCode: number; - }; -} - -export interface SecurityAppError extends AppError { - body: { - message: string; - status_code: number; - }; -} - -export const isKibanaError = (error: unknown): error is KibanaError => - has('message', error) && has('body.message', error) && has('body.statusCode', error); - -export const isSecurityAppError = (error: unknown): error is SecurityAppError => - has('message', error) && has('body.message', error) && has('body.status_code', error); - -export const isAppError = (error: unknown): error is AppError => - isKibanaError(error) || isSecurityAppError(error); - -export const isNotFoundError = (error: unknown) => - (isKibanaError(error) && error.body.statusCode === 404) || - (isSecurityAppError(error) && error.body.status_code === 404); diff --git a/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.ts b/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.ts deleted file mode 100644 index 9b7f4bf6ed7d..000000000000 --- a/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import type { DropResult } from '@hello-pangea/dnd'; - -export const draggableIdPrefix = 'draggableId'; - -export const droppableIdPrefix = 'droppableId'; - -export const draggableContentPrefix = `${draggableIdPrefix}.content.`; - -export const draggableTimelineProvidersPrefix = `${draggableIdPrefix}.timelineProviders.`; - -export const draggableFieldPrefix = `${draggableIdPrefix}.field.`; - -export const droppableContentPrefix = `${droppableIdPrefix}.content.`; - -export const droppableFieldPrefix = `${droppableIdPrefix}.field.`; - -export const droppableTimelineProvidersPrefix = `${droppableIdPrefix}.timelineProviders.`; - -export const droppableTimelineColumnsPrefix = `${droppableIdPrefix}.timelineColumns.`; - -export const droppableTimelineFlyoutBottomBarPrefix = `${droppableIdPrefix}.flyoutButton.`; - -export const getDraggableId = (dataProviderId: string): string => - `${draggableContentPrefix}${dataProviderId}`; - -export const getDraggableFieldId = ({ - contextId, - fieldId, -}: { - contextId: string; - fieldId: string; -}): string => `${draggableFieldPrefix}${escapeContextId(contextId)}.${escapeFieldId(fieldId)}`; - -export const getTimelineProviderDroppableId = ({ - groupIndex, - timelineId, -}: { - groupIndex: number; - timelineId: string; -}): string => `${droppableTimelineProvidersPrefix}${timelineId}.group.${groupIndex}`; - -export const getTimelineProviderDraggableId = ({ - dataProviderId, - groupIndex, - timelineId, -}: { - dataProviderId: string; - groupIndex: number; - timelineId: string; -}): string => - `${draggableTimelineProvidersPrefix}${timelineId}.group.${groupIndex}.${dataProviderId}`; - -export const getDroppableId = (visualizationPlaceholderId: string): string => - `${droppableContentPrefix}${visualizationPlaceholderId}`; - -export const sourceIsContent = (result: DropResult): boolean => - result.source.droppableId.startsWith(droppableContentPrefix); - -export const sourceAndDestinationAreSameTimelineProviders = (result: DropResult): boolean => { - const regex = /^droppableId\.timelineProviders\.(\S+)\./; - const sourceMatches = result.source.droppableId.match(regex) || []; - const destinationMatches = - (result.destination && result.destination.droppableId.match(regex)) || []; - - return ( - sourceMatches.length >= 2 && - destinationMatches.length >= 2 && - sourceMatches[1] === destinationMatches[1] - ); -}; - -export const draggableIsContent = (result: DropResult | { draggableId: string }): boolean => - result.draggableId.startsWith(draggableContentPrefix); - -export const draggableIsField = (result: DropResult | { draggableId: string }): boolean => - result.draggableId.startsWith(draggableFieldPrefix); - -export const reasonIsDrop = (result: DropResult): boolean => result.reason === 'DROP'; - -export const destinationIsTimelineProviders = (result: DropResult): boolean => - result.destination != null && - result.destination.droppableId.startsWith(droppableTimelineProvidersPrefix); - -export const destinationIsTimelineColumns = (result: DropResult): boolean => - result.destination != null && - result.destination.droppableId.startsWith(droppableTimelineColumnsPrefix); - -export const destinationIsTimelineButton = (result: DropResult): boolean => - result.destination != null && - result.destination.droppableId.startsWith(droppableTimelineFlyoutBottomBarPrefix); - -export const getProviderIdFromDraggable = (result: DropResult): string => - result.draggableId.substring(result.draggableId.lastIndexOf('.') + 1); - -export const getFieldIdFromDraggable = (result: DropResult): string => - unEscapeFieldId(result.draggableId.substring(result.draggableId.lastIndexOf('.') + 1)); - -export const escapeDataProviderId = (path: string) => path.replace(/\./g, '_'); - -export const escapeContextId = (path: string) => path.replace(/\./g, '_'); - -export const escapeFieldId = (path: string) => path.replace(/\./g, '!!!DOT!!!'); - -export const unEscapeFieldId = (path: string) => path.replace(/!!!DOT!!!/g, '.'); - -export const providerWasDroppedOnTimeline = (result: DropResult): boolean => - reasonIsDrop(result) && - draggableIsContent(result) && - sourceIsContent(result) && - destinationIsTimelineProviders(result); - -export const userIsReArrangingProviders = (result: DropResult): boolean => - reasonIsDrop(result) && sourceAndDestinationAreSameTimelineProviders(result); - -export const fieldWasDroppedOnTimelineColumns = (result: DropResult): boolean => - reasonIsDrop(result) && draggableIsField(result) && destinationIsTimelineColumns(result); - -/** - * Prevents fields from being dragged or dropped to any area other than column - * header drop zone in the timeline - */ -export const DRAG_TYPE_FIELD = 'drag-type-field'; - -/** This class is added to the document body while timeline field dragging */ -export const IS_TIMELINE_FIELD_DRAGGING_CLASS_NAME = 'is-timeline-field-dragging'; diff --git a/packages/kbn-securitysolution-t-grid/src/utils/index.ts b/packages/kbn-securitysolution-t-grid/src/utils/index.ts deleted file mode 100644 index c921565845e9..000000000000 --- a/packages/kbn-securitysolution-t-grid/src/utils/index.ts +++ /dev/null @@ -1,11 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './api'; -export * from './drag_and_drop'; diff --git a/packages/kbn-securitysolution-t-grid/tsconfig.json b/packages/kbn-securitysolution-t-grid/tsconfig.json deleted file mode 100644 index 9bd4f35cf62a..000000000000 --- a/packages/kbn-securitysolution-t-grid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-securitysolution-utils/index.ts b/packages/kbn-securitysolution-utils/index.ts deleted file mode 100644 index 8769a281e220..000000000000 --- a/packages/kbn-securitysolution-utils/index.ts +++ /dev/null @@ -1,15 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './src/add_remove_id_to_item'; -export * from './src/axios'; -export * from './src/transform_data_to_ndjson'; -export * from './src/path_validations'; -export * from './src/esql'; -export * from './src/debounce_async/debounce_async'; diff --git a/packages/kbn-securitysolution-utils/jest.config.js b/packages/kbn-securitysolution-utils/jest.config.js deleted file mode 100644 index 43e3bc62c156..000000000000 --- a/packages/kbn-securitysolution-utils/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-securitysolution-utils'], -}; diff --git a/packages/kbn-securitysolution-utils/package.json b/packages/kbn-securitysolution-utils/package.json deleted file mode 100644 index 2e18ecbc7642..000000000000 --- a/packages/kbn-securitysolution-utils/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@kbn/securitysolution-utils", - "version": "1.0.0", - "description": "security solution utilities to use across plugins such lists, security_solution, cases, etc...", - "license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0", - "private": true, - "sideEffects": false -} \ No newline at end of file diff --git a/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts b/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts deleted file mode 100644 index 462f1245500e..000000000000 --- a/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts +++ /dev/null @@ -1,79 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { addIdToItem, removeIdFromItem } from '.'; - -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/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts b/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts deleted file mode 100644 index b01a0f7db1ec..000000000000 --- a/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { v4 as uuidv4 } 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 = item as typeof item & { id?: string }; - if (maybeId.id != null) { - return item; - } else { - return { ...item, id: uuidv4() }; - } -}; - -/** - * 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 = item as typeof item & { id?: string }; - if (maybeId.id != null) { - const { id, ...noId } = maybeId; - return noId; - } else { - return item; - } -}; diff --git a/packages/kbn-securitysolution-utils/src/axios/index.ts b/packages/kbn-securitysolution-utils/src/axios/index.ts deleted file mode 100644 index c5c0bbe9d1fd..000000000000 --- a/packages/kbn-securitysolution-utils/src/axios/index.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { AxiosError } from 'axios'; - -export class FormattedAxiosError extends Error { - public readonly request: { - method: string; - url: string; - data: unknown; - }; - public readonly response: { - status: number; - statusText: string; - data: any; - }; - - constructor(axiosError: AxiosError) { - const method = axiosError.config?.method ?? ''; - const url = axiosError.config?.url ?? ''; - - super( - `${axiosError.message}${ - axiosError?.response?.data ? `: ${JSON.stringify(axiosError?.response?.data)}` : '' - }${url ? `\n(Request: ${method} ${url})` : ''}` - ); - - this.request = { - method, - url, - data: axiosError.config?.data ?? '', - }; - - this.response = { - status: axiosError?.response?.status ?? 0, - statusText: axiosError?.response?.statusText ?? '', - data: axiosError?.response?.data, - }; - - this.name = this.constructor.name; - } - - toJSON() { - return { - message: this.message, - request: this.request, - response: this.response, - }; - } - - toString() { - return JSON.stringify(this.toJSON(), null, 2); - } -} - -/** - * Used with `promise.catch()`, it will format the Axios error to a new error and will re-throw - * @param error - */ -export const catchAxiosErrorFormatAndThrow = (error: Error): never => { - if (error instanceof AxiosError) { - throw new FormattedAxiosError(error); - } - - throw error; -}; diff --git a/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts b/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts deleted file mode 100644 index d3a479b44102..000000000000 --- a/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import limit from 'p-limit'; - -/** - * This type is just an async function's type - */ -type RequestFactory = () => Promise; - -/** - * Helper function to call a large number of async functions with limited concurrency. - * Example pattern of how to create functions to pass in: - * - * const ruleCopies = duplicateRuleParams(basicRule, 200); - * const functions = ruleCopies.map((rule) => () => detectionsClient.createRule({ body: rule })); - * - * Note that the `map` call in the example returns a *function* that calls detectionsClient.createRule, it doesn't call createRule immediately. - * - * @param functions Async functions to call with limited concurrency - * @param concurrency Maximum number of concurrent function calls - * @returns Results from all functions passed in - */ -export const concurrentlyExec = async ( - requestFactories: Array>, - concurrency: number = 10 -) => { - const limiter = limit(concurrency); - const promises = requestFactories.map((f) => limiter(f)); - return Promise.all(promises); -}; diff --git a/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.ts b/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.ts deleted file mode 100644 index 99fe653b0e21..000000000000 --- a/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -/** - * Unlike lodash's debounce, which resolves intermediate calls with the most - * recent value, this implementation waits to resolve intermediate calls until - * the next invocation resolves. - * - * @param fn an async function - * - * @returns A debounced async function that resolves on the next invocation - */ -export function debounceAsync( - fn: (...args: Args) => Result, - intervalMs: number -): (...args: Args) => Promise> { - let timeoutId: ReturnType | undefined; - let resolve: (value: Awaited) => void; - let promise = new Promise>((_resolve) => { - resolve = _resolve; - }); - - return (...args) => { - if (timeoutId) { - clearTimeout(timeoutId); - } - - timeoutId = setTimeout(async () => { - resolve(await fn(...args)); - promise = new Promise((_resolve) => { - resolve = _resolve; - }); - }, intervalMs); - - return promise; - }; -} diff --git a/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.ts b/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.ts deleted file mode 100644 index c9b8474b5596..000000000000 --- a/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { type ESQLAstQueryExpression, parse } from '@kbn/esql-ast'; - -export const isAggregatingQuery = (astExpression: ESQLAstQueryExpression): boolean => - astExpression.commands.some((command) => command.name === 'stats'); - -/** - * compute if esqlQuery is aggregating/grouping, i.e. using STATS...BY command - * @param esqlQuery - * @returns boolean - */ -export const computeIsESQLQueryAggregating = (esqlQuery: string): boolean => { - const { root } = parse(esqlQuery); - return isAggregatingQuery(root); -}; diff --git a/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.ts b/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.ts deleted file mode 100644 index 7cf69b409d5d..000000000000 --- a/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils'; - -/** - * parses ES|QL query and returns array of indices - */ -export const getIndexListFromEsqlQuery = (query: string | undefined): string[] => { - try { - const indexString = getIndexPatternFromESQLQuery(query); - - return getIndexListFromIndexString(indexString); - } catch (e) { - return []; - } -}; - -/** - * transforms sting of indices, separated by commas to array - * index*, index2* => [index*, index2*] - */ -export const getIndexListFromIndexString = (indexString: string | undefined): string[] => { - if (!indexString) { - return []; - } - return indexString.split(',').map((index) => index.trim()); -}; diff --git a/packages/kbn-securitysolution-utils/src/esql/index.ts b/packages/kbn-securitysolution-utils/src/esql/index.ts deleted file mode 100644 index 930ff246988e..000000000000 --- a/packages/kbn-securitysolution-utils/src/esql/index.ts +++ /dev/null @@ -1,12 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export * from './compute_if_esql_query_aggregating'; -export * from './get_index_list_from_esql_query'; -export * from './parse_esql_query'; diff --git a/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts b/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts deleted file mode 100644 index e6dfded20007..000000000000 --- a/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts +++ /dev/null @@ -1,760 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { - isPathValid, - hasSimpleExecutableName, - OperatingSystem, - ConditionEntryField, - validateWildcardInput, - validateHasWildcardWithWrongOperator, - validatePotentialWildcardInput, - validateFilePathInput, - WILDCARD_WARNING, - FILEPATH_WARNING, -} from '.'; - -describe('validatePotentialWildcardInput', () => { - it('warns on wildcard when field is file.path.text', () => { - expect( - validatePotentialWildcardInput({ - field: 'file.path.text', - os: OperatingSystem.WINDOWS, - value: 'c:\\path*.exe', - }) - ).toEqual(WILDCARD_WARNING); - }); - it('warns on wildcard when field is not file.path.text', () => { - expect( - validatePotentialWildcardInput({ - field: 'event.category', - os: OperatingSystem.WINDOWS, - value: 'some*value', - }) - ).toEqual(WILDCARD_WARNING); - }); -}); - -describe('validateWildcardInput', () => { - it('warns on wildcard for fields that are not file paths', () => { - expect(validateWildcardInput('*')).toEqual(WILDCARD_WARNING); - }); - it('does not warn if no wildcard', () => { - expect(validateWildcardInput('non-wildcard')).toEqual(undefined); - }); -}); - -describe('validateFilePathInput', () => { - describe('windows', () => { - const os = OperatingSystem.WINDOWS; - - it('does not warn on valid filenames', () => { - expect( - validateFilePathInput({ - os, - value: 'C:\\Windows\\*\\FILENAME.EXE-1231205124.gz', - }) - ).not.toBeDefined(); - expect( - validateFilePathInput({ - os, - value: "C:\\Windows\\*\\test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", - }) - ).toEqual(undefined); - }); - - it('warns on wildcard in file name at the end of the path', () => { - expect(validateFilePathInput({ os, value: 'c:\\path*.exe' })).toEqual(WILDCARD_WARNING); - expect( - validateFilePathInput({ - os, - value: 'C:\\Windows\\*\\FILENAME.EXE-*.gz', - }) - ).toEqual(WILDCARD_WARNING); - }); - - it('warns on unix paths or non-windows paths', () => { - expect(validateFilePathInput({ os, value: '/opt/bin' })).toEqual(FILEPATH_WARNING); - }); - - it('warns on malformed paths', () => { - expect(validateFilePathInput({ os, value: 'c:\\path/opt' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: '1242' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: 'w12efdfa' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: 'c:\\folder\\' })).toEqual(FILEPATH_WARNING); - }); - }); - describe('unix paths', () => { - const os = - parseInt((Math.random() * 2).toString(), 10) === 1 - ? OperatingSystem.MAC - : OperatingSystem.LINUX; - - it('does not warn on valid filenames', () => { - expect( - validateFilePathInput({ - os, - value: '/opt/*/FILENAME.EXE-1231205124.gz', - }) - ).not.toEqual(WILDCARD_WARNING); - expect( - validateFilePathInput({ - os, - value: "/opt/*/test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", - }) - ).not.toEqual(WILDCARD_WARNING); - }); - it('warns on wildcard in file name at the end of the path', () => { - expect(validateFilePathInput({ os, value: '/opt/bin*' })).toEqual(WILDCARD_WARNING); - expect(validateFilePathInput({ os, value: '/opt/FILENAME.EXE-*.gz' })).toEqual( - WILDCARD_WARNING - ); - }); - - it('warns on windows paths', () => { - expect(validateFilePathInput({ os, value: 'd:\\path\\file.exe' })).toEqual(FILEPATH_WARNING); - }); - - it('warns on malformed paths', () => { - expect(validateFilePathInput({ os, value: 'opt/bin\\file.exe' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: '1242' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: 'w12efdfa' })).toEqual(FILEPATH_WARNING); - expect(validateFilePathInput({ os, value: '/folder/' })).toEqual(FILEPATH_WARNING); - }); - }); -}); - -describe('Wildcard and invalid operator', () => { - it('should return TRUE when operator is not "WILDCARD" and value contains a wildcard', () => { - expect(validateHasWildcardWithWrongOperator({ operator: 'match', value: 'asdf*' })).toEqual( - true - ); - }); - it('should return FALSE when operator is not "WILDCARD" and value does not contain a wildcard', () => { - expect(validateHasWildcardWithWrongOperator({ operator: 'match', value: 'asdf' })).toEqual( - false - ); - }); - it('should return FALSE when operator is "WILDCARD" and value contains a wildcard', () => { - expect(validateHasWildcardWithWrongOperator({ operator: 'wildcard', value: 'asdf*' })).toEqual( - false - ); - }); - it('should return FALSE when operator is "WILDCARD" and value does not contain a wildcard', () => { - expect(validateHasWildcardWithWrongOperator({ operator: 'wildcard', value: 'asdf' })).toEqual( - false - ); - }); -}); - -describe('No Warnings', () => { - it('should not show warnings on non path entries ', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.HASH, - type: 'match', - value: '5d5b09f6dcb2d53a5fffc60c4ac0d55fabdf556069d6631545f42aa6e3500f2e', - }) - ).toEqual(true); - - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.SIGNER, - type: 'match', - value: '', - }) - ).toEqual(true); - }); -}); - -describe('Unacceptable Windows wildcard paths', () => { - it('should not accept paths that do not have a folder name with a wildcard ', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:\\folder', - }) - ).toEqual(false); - }); - - it('should not accept paths that do not have a file name with a wildcard ', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:\\path.exe', - }) - ).toEqual(false); - }); - - it('should not accept nested paths that do not have a wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:\\folder\\path.exe', - }) - ).toEqual(false); - }); - - it('should not accept paths with * wildcard and /', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:/**/path.exe', - }) - ).toEqual(false); - }); - - it('should not accept paths with ? wildcard and /', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:/?indows/pat?', - }) - ).toEqual(false); - }); -}); - -describe('Acceptable Windows wildcard paths', () => { - it('should accept wildcards for folders', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:\\**\\path.exe', - }) - ).toEqual(true); - }); - - it('should accept wildcards for folders and files', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'e:\\**\\*.exe', - }) - ).toEqual(true); - }); - - it('should accept paths with single wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'f:\\*', - }) - ).toEqual(true); - - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'f:\\?', - }) - ).toEqual(true); - }); - - it('should accept paths that have wildcard in filenames', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'a:\\*.*', - }) - ).toEqual(true); - }); - - it('should accept paths with ? as wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:\\?indows\\pat?', - }) - ).toEqual(true); - }); - - it('should accept paths with both ? and * as wildcards', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:\\*?', - }) - ).toEqual(true); - }); - - it('should accept paths with multiple wildcards', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:\\**', - }) - ).toEqual(true); - - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:\\??', - }) - ).toEqual(true); - }); -}); - -describe('Acceptable Windows exact paths', () => { - it('should accept paths when it ends with a folder name', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\folder', - }) - ).toEqual(true); - }); - - it('should accept paths when it ends with a file name', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\path.exe', - }) - ).toEqual(true); - }); - - it('should accept paths when it ends with a filename in a folder', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\folder\\path.exe', - }) - ).toEqual(true); - }); -}); - -describe('Acceptable Windows exact paths with hyphens', () => { - it('should accept paths when paths have folder names with hyphens', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\hype-folder-name', - }) - ).toEqual(true); - }); - - it('should accept paths when file names have hyphens', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\file-name.exe', - }) - ).toEqual(true); - }); -}); - -describe('Unacceptable Windows exact paths', () => { - it('should not accept paths with /', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:/folder/path.exe', - }) - ).toEqual(false); - }); - - it('should not accept paths not having a in the suffix', () => { - expect( - isPathValid({ - os: OperatingSystem.WINDOWS, - field: ConditionEntryField.PATH, - type: 'match', - value: '\\folder\\path.exe', - }) - ).toEqual(false); - }); -}); - -/// -describe('Unacceptable Mac/Linux wildcard paths', () => { - it('should not accept paths that do not have a folder name with a wildcard ', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/folder', - }) - ).toEqual(false); - }); - - it('should not accept paths that do not have a file name with a wildcard ', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/zip.zip', - }) - ).toEqual(false); - }); - - it('should not accept nested paths that do not have a wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/opt/pack.tar', - }) - ).toEqual(false); - }); - - it('should not accept paths with * wildcard and \\', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'c:\\**\\path.exe', - }) - ).toEqual(false); - }); - - it('should not accept paths with ? wildcard and \\', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: 'C:\\?indows\\pat?', - }) - ).toEqual(false); - }); -}); - -describe('Acceptable Mac/Linux wildcard paths', () => { - it('should accept wildcards for folders', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/**/file.', - }) - ).toEqual(true); - }); - - it('should accept wildcards for folders and files', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/usr/bi?/*.js', - }) - ).toEqual(true); - }); - - it('should accept paths with single wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/op*', - }) - ).toEqual(true); - - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/op?', - }) - ).toEqual(true); - }); - - it('should accept paths that have wildcard in filenames', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/*.*', - }) - ).toEqual(true); - }); - - it('should accept paths with ? as wildcard', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/usr/?inux/pat?', - }) - ).toEqual(true); - }); - - it('should accept paths with both ? and * as wildcards', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/usr/*?', - }) - ).toEqual(true); - }); - - it('should accept paths with multiple wildcards', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/usr/**', - }) - ).toEqual(true); - - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'wildcard', - value: '/opt/??', - }) - ).toEqual(true); - }); -}); - -describe('Acceptable Mac/Linux exact paths', () => { - it('should accept paths when it is the root path', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'match', - value: '/', - }) - ).toEqual(true); - }); - - it('should accept paths when it ends with a file name', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'match', - value: '/usr/file.ts', - }) - ).toEqual(true); - }); - - it('should accept paths when it ends with a filename in a folder', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'match', - value: '/opt/z.dmg', - }) - ).toEqual(true); - }); -}); - -describe('Acceptable Mac/Linux exact paths with hyphens', () => { - it('should accept paths when paths have folder names with hyphens', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'match', - value: '/hype-folder-name', - }) - ).toEqual(true); - }); - - it('should accept paths when file names have hyphens', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'match', - value: '/file-name.dmg', - }) - ).toEqual(true); - }); -}); - -describe('Unacceptable Mac/Linux exact paths', () => { - it('should not accept paths with \\', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'match', - value: 'c:\\folder\\path.exe', - }) - ).toEqual(false); - }); - - it('should not accept paths not starting with /', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'match', - value: 'opt/bin', - }) - ).toEqual(false); - }); - - it('should not accept paths ending with /', () => { - expect( - isPathValid({ - os: OperatingSystem.MAC, - field: ConditionEntryField.PATH, - type: 'match', - value: '/opt/bin/', - }) - ).toEqual(false); - }); - - it('should not accept file extensions with hyphens', () => { - expect( - isPathValid({ - os: OperatingSystem.LINUX, - field: ConditionEntryField.PATH, - type: 'match', - value: '/opt/bin/file.d-mg', - }) - ).toEqual(false); - }); -}); - -describe('hasSimpleExecutableName', () => { - it('should return TRUE when MAC/LINUX wildcard paths have an executable name', () => { - const os = - parseInt((Math.random() * 2).toString(), 10) === 1 - ? OperatingSystem.MAC - : OperatingSystem.LINUX; - - expect( - hasSimpleExecutableName({ - os, - type: 'wildcard', - value: '/opt/*/app', - }) - ).toEqual(true); - expect( - hasSimpleExecutableName({ - os, - type: 'wildcard', - value: '/op*/**/app.dmg', - }) - ).toEqual(true); - expect( - hasSimpleExecutableName({ - os, - type: 'wildcard', - value: "/sy*/test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", - }) - ).toEqual(true); - }); - - it('should return FALSE when MAC/LINUX wildcard paths have a wildcard in executable name', () => { - const os = - parseInt((Math.random() * 2).toString(), 10) === 1 - ? OperatingSystem.MAC - : OperatingSystem.LINUX; - - expect( - hasSimpleExecutableName({ - os, - type: 'wildcard', - value: '/op/*/*pp', - }) - ).toEqual(false); - expect( - hasSimpleExecutableName({ - os, - type: 'wildcard', - value: '/op*/b**/ap.m**', - }) - ).toEqual(false); - }); - - it('should return TRUE when WINDOWS wildcards paths have a executable name', () => { - expect( - hasSimpleExecutableName({ - os: OperatingSystem.WINDOWS, - type: 'wildcard', - value: 'c:\\**\\path.exe', - }) - ).toEqual(true); - expect( - hasSimpleExecutableName({ - os: OperatingSystem.WINDOWS, - type: 'wildcard', - value: 'C:\\*\\file-name.path华语 1234.txt', - }) - ).toEqual(true); - expect( - hasSimpleExecutableName({ - os: OperatingSystem.WINDOWS, - type: 'wildcard', - value: "C:\\*\\test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", - }) - ).toEqual(true); - }); - - it('should return FALSE when WINDOWS wildcards paths have a wildcard in executable name', () => { - expect( - hasSimpleExecutableName({ - os: OperatingSystem.WINDOWS, - type: 'wildcard', - value: 'c:\\**\\pa*h.exe', - }) - ).toEqual(false); - }); -}); diff --git a/packages/kbn-securitysolution-utils/src/path_validations/index.ts b/packages/kbn-securitysolution-utils/src/path_validations/index.ts deleted file mode 100644 index 1f1eaf0b0142..000000000000 --- a/packages/kbn-securitysolution-utils/src/path_validations/index.ts +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { i18n } from '@kbn/i18n'; - -export const WILDCARD_WARNING = i18n.translate('utils.wildcardWarning', { - defaultMessage: `Using wildcards can impact Endpoint performance`, -}); - -export const FILEPATH_WARNING = i18n.translate('utils.filename.pathWarning', { - defaultMessage: `Path may be formed incorrectly; verify value`, -}); - -export enum ConditionEntryField { - HASH = 'process.hash.*', - PATH = 'process.executable.caseless', - SIGNER = 'process.Ext.code_signature', - SIGNER_MAC = 'process.code_signature', -} - -export enum EntryFieldType { - HASH = '.hash.', - EXECUTABLE = '.executable.caseless', - PATH = '.path', - SIGNER = '.code_signature', -} - -export type TrustedAppConditionEntryField = - | 'process.hash.*' - | 'process.executable.caseless' - | 'process.Ext.code_signature' - | 'process.code_signature'; - -export type BlocklistConditionEntryField = - | 'file.hash.*' - | 'file.path' - | 'file.Ext.code_signature' - | 'file.path.caseless'; -export type AllConditionEntryFields = - | TrustedAppConditionEntryField - | BlocklistConditionEntryField - | 'file.path.text'; - -export enum OperatingSystem { - LINUX = 'linux', - MAC = 'macos', - WINDOWS = 'windows', -} - -export type EntryTypes = 'match' | 'wildcard' | 'match_any'; -export type TrustedAppEntryTypes = Extract; -export type EventFiltersTypes = EntryTypes | 'exists' | 'nested'; - -export const validatePotentialWildcardInput = ({ - field = '', - os, - value = '', -}: { - field?: string; - os: OperatingSystem; - value?: string; -}): string | undefined => { - const textInput = value.trim(); - if (field === 'file.path.text') { - return validateFilePathInput({ os, value: textInput }); - } - return validateWildcardInput(textInput); -}; - -export const validateFilePathInput = ({ - os, - value, -}: { - os: OperatingSystem; - value: string; -}): string | undefined => { - const isValidFilePath = isPathValid({ - os, - field: 'file.path.text', - type: 'wildcard', - value, - }); - const hasSimpleFileName = hasSimpleExecutableName({ - os, - type: 'wildcard', - value, - }); - - if (!value.length) { - return FILEPATH_WARNING; - } - - if (isValidFilePath) { - if (hasSimpleFileName !== undefined && !hasSimpleFileName) { - return WILDCARD_WARNING; - } - } else { - return FILEPATH_WARNING; - } -}; - -export const validateWildcardInput = (value: string | string[]): string | undefined => { - const wildcardRegex = /[*?]/; - if (Array.isArray(value)) { - const doesAnyValueContainWildcardInput = value.some((v) => wildcardRegex.test(v)); - if (doesAnyValueContainWildcardInput) { - return WILDCARD_WARNING; - } - } else { - if (wildcardRegex.test(value)) { - return WILDCARD_WARNING; - } - } -}; - -export const validateHasWildcardWithWrongOperator = ({ - operator, - value, -}: { - operator: TrustedAppEntryTypes | EventFiltersTypes; - value: string | string[]; -}): boolean => { - if (operator !== 'wildcard' && validateWildcardInput(value)) { - return true; - } else { - return false; - } -}; - -export const hasSimpleExecutableName = ({ - os, - type, - value, -}: { - os: OperatingSystem; - type: EntryTypes; - value: string; -}): boolean | undefined => { - const separator = os === OperatingSystem.WINDOWS ? '\\' : '/'; - const lastString = value.split(separator).pop(); - if (!lastString) { - return; - } - if (type === 'wildcard') { - return (lastString.split('*').length || lastString.split('?').length) === 1; - } - return true; -}; - -export const isPathValid = ({ - os, - field, - type, - value, -}: { - os: OperatingSystem; - field: AllConditionEntryFields; - type: EntryTypes; - value: string; -}): boolean => { - const pathFields: AllConditionEntryFields[] = [ - 'process.executable.caseless', - 'file.path', - 'file.path.text', - ]; - if (pathFields.includes(field)) { - if (type === 'wildcard') { - return os === OperatingSystem.WINDOWS - ? isWindowsWildcardPathValid(value) - : isLinuxMacWildcardPathValid(value); - } - return doesPathMatchRegex({ value, os }); - } - return true; -}; - -const doesPathMatchRegex = ({ os, value }: { os: OperatingSystem; value: string }): boolean => { - if (os === OperatingSystem.WINDOWS) { - const filePathRegex = - /^[a-z]:(?:|\\\\[^<>:"'/\\|?*]+\\[^<>:"'/\\|?*]+|%\w+%|)[\\](?:[^<>:"'/\\|?*]+[\\/])*([^<>:"'/\\|?*])+$/i; - return filePathRegex.test(value); - } - return /^(\/|(\/[\w\-]+)+|\/[\w\-]+\.[\w]+|(\/[\w-]+)+\/[\w\-]+\.[\w]+)$/i.test(value); -}; - -const isWindowsWildcardPathValid = (path: string): boolean => { - const firstCharacter = path[0]; - const lastCharacter = path.slice(-1); - const trimmedValue = path.trim(); - const hasSlash = /\//.test(trimmedValue); - if (path.length === 0) { - return false; - } else if ( - hasSlash || - trimmedValue.length !== path.length || - firstCharacter === '^' || - lastCharacter === '\\' || - !hasWildcard({ path, isWindowsPath: true }) - ) { - return false; - } else { - return true; - } -}; - -const isLinuxMacWildcardPathValid = (path: string): boolean => { - const firstCharacter = path[0]; - const lastCharacter = path.slice(-1); - const trimmedValue = path.trim(); - if (path.length === 0) { - return false; - } else if ( - trimmedValue.length !== path.length || - firstCharacter !== '/' || - lastCharacter === '/' || - path.length > 1024 === true || - path.includes('//') === true || - !hasWildcard({ path, isWindowsPath: false }) - ) { - return false; - } else { - return true; - } -}; - -const hasWildcard = ({ - path, - isWindowsPath, -}: { - path: string; - isWindowsPath: boolean; -}): boolean => { - for (const pathComponent of path.split(isWindowsPath ? '\\' : '/')) { - if (/[\*|\?]+/.test(pathComponent) === true) { - return true; - } - } - return false; -}; diff --git a/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts b/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts deleted file mode 100644 index 8c4e8289b1dd..000000000000 --- a/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts +++ /dev/null @@ -1,85 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { transformDataToNdjson } from '.'; - -export const ANCHOR_DATE = '2020-02-20T03:57:54.037Z'; - -const getRulesSchemaMock = (anchorDate: string = ANCHOR_DATE) => ({ - author: [], - id: '7a7065d7-6e8b-4aae-8d20-c93613dec9f9', - created_at: new Date(anchorDate).toISOString(), - updated_at: new Date(anchorDate).toISOString(), - created_by: 'elastic', - description: 'some description', - enabled: true, - false_positives: ['false positive 1', 'false positive 2'], - from: 'now-6m', - immutable: false, - name: 'Query with a rule id', - query: 'user.name: root or user.name: admin', - references: ['test 1', 'test 2'], - severity: 'high', - severity_mapping: [], - updated_by: 'elastic_kibana', - tags: ['some fake tag 1', 'some fake tag 2'], - to: 'now', - type: 'query', - threat: [], - version: 1, - output_index: '.siem-signals-default', - max_signals: 100, - risk_score: 55, - risk_score_mapping: [], - language: 'kuery', - rule_id: 'query-rule-id', - interval: '5m', - exceptions_list: [], -}); - -describe('transformDataToNdjson', () => { - test('if rules are empty it returns an empty string', () => { - const ruleNdjson = transformDataToNdjson([]); - expect(ruleNdjson).toEqual(''); - }); - - test('single rule will transform with new line ending character for ndjson', () => { - const rule = getRulesSchemaMock(); - const ruleNdjson = transformDataToNdjson([rule]); - expect(ruleNdjson.endsWith('\n')).toBe(true); - }); - - test('multiple rules will transform with two new line ending characters for ndjson', () => { - const result1 = getRulesSchemaMock(); - const result2 = getRulesSchemaMock(); - result2.id = 'some other id'; - result2.rule_id = 'some other id'; - result2.name = 'Some other rule'; - - const ruleNdjson = transformDataToNdjson([result1, result2]); - // this is how we count characters in JavaScript :-) - const count = ruleNdjson.split('\n').length - 1; - expect(count).toBe(2); - }); - - test('you can parse two rules back out without errors', () => { - const result1 = getRulesSchemaMock(); - const result2 = getRulesSchemaMock(); - result2.id = 'some other id'; - result2.rule_id = 'some other id'; - result2.name = 'Some other rule'; - - const ruleNdjson = transformDataToNdjson([result1, result2]); - const ruleStrings = ruleNdjson.split('\n'); - const reParsed1 = JSON.parse(ruleStrings[0]); - const reParsed2 = JSON.parse(ruleStrings[1]); - expect(reParsed1).toEqual(result1); - expect(reParsed2).toEqual(result2); - }); -}); diff --git a/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts b/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts deleted file mode 100644 index b20606c356ef..000000000000 --- a/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -export const transformDataToNdjson = (data: unknown[]): string => { - if (data.length !== 0) { - const dataString = data.map((item) => JSON.stringify(item)).join('\n'); - return `${dataString}\n`; - } else { - return ''; - } -}; diff --git a/packages/kbn-securitysolution-utils/tsconfig.json b/packages/kbn-securitysolution-utils/tsconfig.json deleted file mode 100644 index d45b0c973af8..000000000000 --- a/packages/kbn-securitysolution-utils/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node" - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/i18n", - "@kbn/esql-utils", - "@kbn/esql-ast", - "@kbn/esql-validation-autocomplete" - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/run_check_ftr_configs_cli.ts b/packages/kbn-test/src/functional_test_runner/lib/config/run_check_ftr_configs_cli.ts index 5808c88901b1..265bdbe9e008 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/run_check_ftr_configs_cli.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/run_check_ftr_configs_cli.ts @@ -25,6 +25,10 @@ const THIS_REL = Path.relative(REPO_ROOT, THIS_PATH); const IGNORED_PATHS = [ THIS_PATH, Path.resolve(REPO_ROOT, 'packages/kbn-test/src/jest/run_check_jest_configs_cli.ts'), + Path.resolve( + REPO_ROOT, + 'x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/playwright.config.ts' + ), ]; export async function runCheckFtrConfigsCli() { diff --git a/packages/kbn-unified-data-table/src/components/data_table.tsx b/packages/kbn-unified-data-table/src/components/data_table.tsx index abaec0f6a98e..e7680ccc9175 100644 --- a/packages/kbn-unified-data-table/src/components/data_table.tsx +++ b/packages/kbn-unified-data-table/src/components/data_table.tsx @@ -1198,13 +1198,13 @@ export const UnifiedDataTable = ({ {searchDescription ? ( ) : ( )} diff --git a/packages/kbn-zod-helpers/jest.config.js b/packages/kbn-zod-helpers/jest.config.js deleted file mode 100644 index 4f66c7eed2ee..000000000000 --- a/packages/kbn-zod-helpers/jest.config.js +++ /dev/null @@ -1,14 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../..', - roots: ['/packages/kbn-zod-helpers'], -}; diff --git a/packages/kbn-zod-helpers/tsconfig.json b/packages/kbn-zod-helpers/tsconfig.json deleted file mode 100644 index 9eab856c8c4d..000000000000 --- a/packages/kbn-zod-helpers/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "outDir": "target/types", - "types": ["jest", "node"] - }, - "exclude": ["target/**/*"], - "extends": "../../tsconfig.base.json", - "include": ["**/*.ts"], - "kbn_references": [ - "@kbn/datemath", - "@kbn/core", - "@kbn/zod", - ] -} diff --git a/packages/react/kibana_context/render/render_provider.tsx b/packages/react/kibana_context/render/render_provider.tsx index 233abb42834b..345a0993bb9e 100644 --- a/packages/react/kibana_context/render/render_provider.tsx +++ b/packages/react/kibana_context/render/render_provider.tsx @@ -25,11 +25,11 @@ export type KibanaRenderContextProviderProps = Omit > = ({ children, ...props }) => { - const { analytics, i18n, theme, userProfile, colorMode, modify } = props; + const { analytics, executionContext, i18n, theme, userProfile, colorMode, modify } = props; return ( {children} diff --git a/packages/react/kibana_context/root/BUILD.bazel b/packages/react/kibana_context/root/BUILD.bazel index 1c47c25bc20a..fc073da074a6 100644 --- a/packages/react/kibana_context/root/BUILD.bazel +++ b/packages/react/kibana_context/root/BUILD.bazel @@ -26,6 +26,7 @@ DEPS = [ "@npm//tslib", "@npm//@elastic/eui", "//packages/core/base/core-base-common", + "//packages/shared-ux/router/impl:shared-ux-router", ] js_library( diff --git a/packages/react/kibana_context/root/root_provider.test.tsx b/packages/react/kibana_context/root/root_provider.test.tsx index 405823a9b823..52af9d565421 100644 --- a/packages/react/kibana_context/root/root_provider.test.tsx +++ b/packages/react/kibana_context/root/root_provider.test.tsx @@ -15,6 +15,8 @@ import { useEuiTheme } from '@elastic/eui'; import type { UseEuiTheme } from '@elastic/eui'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import type { KibanaTheme } from '@kbn/react-kibana-context-common'; +import type { ExecutionContextStart } from '@kbn/core-execution-context-browser'; +import { executionContextServiceMock } from '@kbn/core-execution-context-browser-mocks'; import { i18nServiceMock } from '@kbn/core-i18n-browser-mocks'; import { I18nStart } from '@kbn/core-i18n-browser'; import type { UserProfileService } from '@kbn/core-user-profile-browser'; @@ -25,11 +27,13 @@ describe('KibanaRootContextProvider', () => { let euiTheme: UseEuiTheme | undefined; let i18nMock: I18nStart; let userProfile: UserProfileService; + let executionContext: ExecutionContextStart; beforeEach(() => { euiTheme = undefined; i18nMock = i18nServiceMock.createStartContract(); userProfile = userProfileServiceMock.createStart(); + executionContext = executionContextServiceMock.createStartContract(); }); const flushPromises = async () => { @@ -64,6 +68,7 @@ describe('KibanaRootContextProvider', () => { @@ -82,6 +87,7 @@ describe('KibanaRootContextProvider', () => { diff --git a/packages/react/kibana_context/root/root_provider.tsx b/packages/react/kibana_context/root/root_provider.tsx index 386a67fb005e..be8ddfa3f95a 100644 --- a/packages/react/kibana_context/root/root_provider.tsx +++ b/packages/react/kibana_context/root/root_provider.tsx @@ -11,6 +11,8 @@ import React, { FC, PropsWithChildren } from 'react'; import type { AnalyticsServiceStart } from '@kbn/core-analytics-browser'; import type { I18nStart } from '@kbn/core-i18n-browser'; +import type { ExecutionContextStart } from '@kbn/core-execution-context-browser'; +import { SharedUXRouterContext } from '@kbn/shared-ux-router'; // @ts-expect-error EUI exports this component internally, but Kibana isn't picking it up its types import { useIsNestedEuiProvider } from '@elastic/eui/lib/components/provider/nested'; @@ -25,6 +27,8 @@ export interface KibanaRootContextProviderProps extends KibanaEuiProviderProps { i18n: I18nStart; /** The `AnalyticsServiceStart` API from `CoreStart`. */ analytics?: Pick; + /** The `ExecutionContextStart` API from `CoreStart`. */ + executionContext?: ExecutionContextStart; } /** @@ -44,20 +48,26 @@ export interface KibanaRootContextProviderProps extends KibanaEuiProviderProps { export const KibanaRootContextProvider: FC> = ({ children, i18n, + executionContext, ...props }) => { const hasEuiProvider = useIsNestedEuiProvider(); + const rootContextProvider = ( + + {children} + + ); if (hasEuiProvider) { emitEuiProviderWarning( 'KibanaRootContextProvider has likely been nested in this React tree, either by direct reference or by KibanaRenderContextProvider. The result of this nesting is a nesting of EuiProvider, which has negative effects. Check your React tree for nested Kibana context providers.' ); - return {children}; + return rootContextProvider; } else { const { theme, userProfile, globalStyles, colorMode, modify } = props; return ( - {children} + {rootContextProvider} ); } diff --git a/packages/react/kibana_context/root/tsconfig.json b/packages/react/kibana_context/root/tsconfig.json index a7606025552b..8035f8379e39 100644 --- a/packages/react/kibana_context/root/tsconfig.json +++ b/packages/react/kibana_context/root/tsconfig.json @@ -24,5 +24,8 @@ "@kbn/core-analytics-browser", "@kbn/core-user-profile-browser", "@kbn/core-user-profile-browser-mocks", + "@kbn/core-execution-context-browser", + "@kbn/core-execution-context-browser-mocks", + "@kbn/shared-ux-router" ] } diff --git a/packages/shared-ux/router/impl/BUILD.bazel b/packages/shared-ux/router/impl/BUILD.bazel new file mode 100644 index 000000000000..224bebcf72e4 --- /dev/null +++ b/packages/shared-ux/router/impl/BUILD.bazel @@ -0,0 +1,34 @@ +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") + +SRCS = glob( + [ + "**/*.ts", + "**/*.tsx", + ], + exclude = [ + "**/test_helpers.ts", + "**/*.config.js", + "**/*.mock.*", + "**/*.test.*", + "**/*.stories.*", + "**/__snapshots__/**", + "**/integration_tests/**", + "**/mocks/**", + "**/scripts/**", + "**/storybook/**", + "**/test_fixtures/**", + "**/test_helpers/**", + ], +) + +DEPS = [ + +] + +js_library( + name = "shared-ux-router", + package_name = "@kbn/shared-ux-router", + srcs = ["package.json"] + SRCS, + deps = DEPS, + visibility = ["//visibility:public"], +) diff --git a/packages/shared-ux/router/impl/__snapshots__/route.test.tsx.snap b/packages/shared-ux/router/impl/__snapshots__/route.test.tsx.snap index 418aa60b7c1f..b7ef59528923 100644 --- a/packages/shared-ux/router/impl/__snapshots__/route.test.tsx.snap +++ b/packages/shared-ux/router/impl/__snapshots__/route.test.tsx.snap @@ -33,3 +33,5 @@ exports[`Route renders 1`] = ` `; + +exports[`Route renders with enableExecutionContextTracking as false 1`] = ``; diff --git a/packages/shared-ux/router/impl/index.ts b/packages/shared-ux/router/impl/index.ts index a8bef1b8499d..253d42beaa50 100644 --- a/packages/shared-ux/router/impl/index.ts +++ b/packages/shared-ux/router/impl/index.ts @@ -10,3 +10,5 @@ export { Route } from './route'; export { HashRouter, BrowserRouter, MemoryRouter, Router } from './router'; export { Routes } from './routes'; + +export { SharedUXRouterContext } from './services'; diff --git a/packages/shared-ux/router/impl/route.test.tsx b/packages/shared-ux/router/impl/route.test.tsx index 96bb6130387a..9d21690cdcf4 100644 --- a/packages/shared-ux/router/impl/route.test.tsx +++ b/packages/shared-ux/router/impl/route.test.tsx @@ -9,15 +9,34 @@ import React, { Component, FC } from 'react'; import { shallow } from 'enzyme'; +import { useSharedUXRoutesContext } from './routes_context'; import { Route } from './route'; import { createMemoryHistory } from 'history'; +jest.mock('./routes_context', () => ({ + useSharedUXRoutesContext: jest.fn().mockImplementation(() => ({ + enableExecutionContextTracking: true, + })), +})); + describe('Route', () => { + beforeEach(() => { + jest.restoreAllMocks(); + }); + test('renders', () => { const example = shallow(); expect(example).toMatchSnapshot(); }); + test('renders with enableExecutionContextTracking as false', () => { + (useSharedUXRoutesContext as jest.Mock).mockImplementationOnce(() => ({ + enableExecutionContextTracking: false, + })); + const example = shallow(); + expect(example).toMatchSnapshot(); + }); + test('location renders as expected', () => { // create a history const historyLocation = createMemoryHistory(); diff --git a/packages/shared-ux/router/impl/route.tsx b/packages/shared-ux/router/impl/route.tsx index 3535ff7aecec..5041f872b71b 100644 --- a/packages/shared-ux/router/impl/route.tsx +++ b/packages/shared-ux/router/impl/route.tsx @@ -15,6 +15,7 @@ import { RouteProps, useRouteMatch, } from 'react-router-dom'; +import { useSharedUXRoutesContext } from './routes_context'; import { useKibanaSharedUX } from './services'; import { useSharedUXExecutionContext } from './use_execution_context'; @@ -30,17 +31,18 @@ export const Route = ({ render, ...rest }: RouteProps) => { + const { enableExecutionContextTracking } = useSharedUXRoutesContext(); const component = useMemo(() => { if (!Component) { return undefined; } return (props: RouteComponentProps) => ( <> - + {enableExecutionContextTracking && } ); - }, [Component]); + }, [Component, enableExecutionContextTracking]); if (component) { return ; @@ -52,7 +54,7 @@ export const Route = ({ {...rest} render={(props) => ( <> - + {enableExecutionContextTracking && } {/* @ts-ignore else condition exists if renderFunction is undefined*/} {renderFunction(props)} @@ -62,7 +64,7 @@ export const Route = ({ } return ( - + {enableExecutionContextTracking && } {children} ); @@ -75,6 +77,12 @@ export const MatchPropagator = () => { const { executionContext } = useKibanaSharedUX().services; const match = useRouteMatch(); + if (!executionContext && process.env.NODE_ENV !== 'production') { + throw new Error( + 'Default execution context tracking is enabled but the executionContext service is not available' + ); + } + useSharedUXExecutionContext(executionContext, { type: 'application', page: match.path, diff --git a/packages/shared-ux/router/impl/routes.tsx b/packages/shared-ux/router/impl/routes.tsx index 9c1a97de6583..937756224627 100644 --- a/packages/shared-ux/router/impl/routes.tsx +++ b/packages/shared-ux/router/impl/routes.tsx @@ -13,6 +13,7 @@ import React, { Children } from 'react'; import { Switch, useRouteMatch } from 'react-router-dom'; import { Routes as ReactRouterRoutes, Route } from 'react-router-dom-v5-compat'; import { Route as LegacyRoute, MatchPropagator } from './route'; +import { SharedUXRoutesContext } from './routes_context'; type RouterElementChildren = Array< React.ReactElement< @@ -28,42 +29,47 @@ type RouterElementChildren = Array< export const Routes = ({ legacySwitch = true, + enableExecutionContextTracking = false, children, }: { legacySwitch?: boolean; + enableExecutionContextTracking?: boolean; children: React.ReactNode; }) => { const match = useRouteMatch(); return legacySwitch ? ( - {children} + + {children} + ) : ( - - {Children.map(children as RouterElementChildren, (child) => { - if (React.isValidElement(child) && child.type === LegacyRoute) { - const path = replace(child?.props.path, match.url + '/', ''); - const renderFunction = - typeof child?.props.children === 'function' - ? child?.props.children - : child?.props.render; - - return ( - - - {(child?.props?.component && ) || - (renderFunction && renderFunction()) || - children} - - } - /> - ); - } else { - return child; - } - })} - + + + {Children.map(children as RouterElementChildren, (child) => { + if (React.isValidElement(child) && child.type === LegacyRoute) { + const path = replace(child?.props.path, match.url + '/', ''); + const renderFunction = + typeof child?.props.children === 'function' + ? child?.props.children + : child?.props.render; + return ( + + {enableExecutionContextTracking && } + {(child?.props?.component && ) || + (renderFunction && renderFunction()) || + children} + + } + /> + ); + } else { + return child; + } + })} + + ); }; diff --git a/packages/shared-ux/router/impl/routes_context.ts b/packages/shared-ux/router/impl/routes_context.ts new file mode 100644 index 000000000000..115a5df7780d --- /dev/null +++ b/packages/shared-ux/router/impl/routes_context.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +import { createContext, useContext } from 'react'; +import { SharedUXRoutesContextType } from './types'; + +const defaultContextValue = {}; + +export const SharedUXRoutesContext = createContext(defaultContextValue); + +export const useSharedUXRoutesContext = (): SharedUXRoutesContextType => + useContext(SharedUXRoutesContext as unknown as React.Context); diff --git a/packages/shared-ux/router/impl/services.ts b/packages/shared-ux/router/impl/services.ts index c3ad2ab06e06..7cea72f03bd8 100644 --- a/packages/shared-ux/router/impl/services.ts +++ b/packages/shared-ux/router/impl/services.ts @@ -50,7 +50,7 @@ export interface SharedUXExecutionContextSetup { */ export interface SharedUXExecutionContextSetup { /** {@link SharedUXExecutionContextSetup} */ - executionContext: SharedUXExecutionContextStart; + executionContext?: SharedUXExecutionContextStart; } export type KibanaServices = Partial; @@ -63,12 +63,14 @@ const defaultContextValue = { services: {}, }; -export const sharedUXContext = +export const SharedUXRouterContext = createContext>(defaultContextValue); export const useKibanaSharedUX = (): SharedUXRouterContextValue< KibanaServices & Extra > => useContext( - sharedUXContext as unknown as React.Context> + SharedUXRouterContext as unknown as React.Context< + SharedUXRouterContextValue + > ); diff --git a/packages/shared-ux/router/impl/types.ts b/packages/shared-ux/router/impl/types.ts index 833c5bdd0c81..067677d152ca 100644 --- a/packages/shared-ux/router/impl/types.ts +++ b/packages/shared-ux/router/impl/types.ts @@ -33,3 +33,11 @@ export declare interface SharedUXExecutionContext { /** an inner context spawned from the current context. */ child?: SharedUXExecutionContext; } + +export declare interface SharedUXRoutesContextType { + /** + * This flag is used to enable the default execution context tracking for a specific router. + * Enable this flag in case you don't have a custom implementation for execution context tracking. + * */ + readonly enableExecutionContextTracking?: boolean; +} diff --git a/packages/shared-ux/router/impl/use_execution_context.ts b/packages/shared-ux/router/impl/use_execution_context.ts index d460d4df3080..5e088fc3eac7 100644 --- a/packages/shared-ux/router/impl/use_execution_context.ts +++ b/packages/shared-ux/router/impl/use_execution_context.ts @@ -8,7 +8,7 @@ */ import useDeepCompareEffect from 'react-use/lib/useDeepCompareEffect'; -import { SharedUXExecutionContextSetup } from './services'; +import type { SharedUXExecutionContextSetup } from './services'; import { SharedUXExecutionContext } from './types'; /** diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts index 41a194f5f1e5..c6995c6e2d4c 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts @@ -772,7 +772,9 @@ export const runActionTestSuite = ({ // Reindex doesn't return any errors on its own, so we have to test // together with waitForReindexTask - describe('reindex & waitForReindexTask', () => { + // Flaky: https://github.com/elastic/kibana/issues/166190 + // Reported here: https://github.com/elastic/kibana/issues/167273 + describe.skip('reindex & waitForReindexTask', () => { it('resolves right when reindex succeeds without reindex script', async () => { const res = (await reindex({ client, diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/base/Dockerfile b/src/dev/build/tasks/os_packages/docker_generator/templates/base/Dockerfile index e868cb73cb8d..7d9eaac88696 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/templates/base/Dockerfile +++ b/src/dev/build/tasks/os_packages/docker_generator/templates/base/Dockerfile @@ -114,7 +114,7 @@ EXPOSE 5601 RUN for iter in {1..10}; do \ microdnf update --setopt=tsflags=nodocs -y && \ microdnf install --setopt=tsflags=nodocs -y \ - fontconfig freetype shadow-utils nss findutils && \ + fontconfig liberation-fonts-common freetype shadow-utils nss findutils && \ microdnf clean all && exit_code=0 && break || exit_code=$? && echo "microdnf error: retry $iter in 10s" && \ sleep 10; \ done; \ @@ -126,7 +126,7 @@ RUN for iter in {1..10}; do \ apt-get update && \ apt-get upgrade -y && \ apt-get install -y --no-install-recommends \ - fontconfig libnss3 curl ca-certificates && \ + fontconfig fonts-liberation libnss3 curl ca-certificates && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* && exit_code=0 && break || exit_code=$? && echo "apt-get error: retry $iter in 10s" && \ sleep 10; \ @@ -134,7 +134,7 @@ RUN for iter in {1..10}; do \ (exit $exit_code) {{/ubuntu}} {{#wolfi}} -RUN apk --no-cache add bash curl fontconfig libstdc++ libnss findutils shadow ca-certificates +RUN apk --no-cache add bash curl fontconfig font-liberation libstdc++ libnss findutils shadow ca-certificates {{/wolfi}} # Bring in Kibana from the initial stage. diff --git a/src/dev/code_coverage/ingest_coverage/__tests__/enumerate_patterns.test.js b/src/dev/code_coverage/ingest_coverage/__tests__/enumerate_patterns.test.js index 5faeab1acb53..540b51a29498 100644 --- a/src/dev/code_coverage/ingest_coverage/__tests__/enumerate_patterns.test.js +++ b/src/dev/code_coverage/ingest_coverage/__tests__/enumerate_patterns.test.js @@ -17,13 +17,13 @@ const log = new ToolingLog({ }); describe(`enumeratePatterns`, () => { - it(`should resolve x-pack/plugins/screenshotting/server/browsers/extract/unzip.ts to kibana-screenshotting`, () => { + it(`should resolve x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.ts to kibana-screenshotting`, () => { const actual = enumeratePatterns(REPO_ROOT)(log)( - new Map([['x-pack/plugins/screenshotting', ['kibana-screenshotting']]]) + new Map([['x-pack/platform/plugins/shared/screenshotting', ['kibana-screenshotting']]]) ); expect(actual.flat()).toContain( - 'x-pack/plugins/screenshotting/server/browsers/extract/unzip.ts kibana-screenshotting' + 'x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.ts kibana-screenshotting' ); }); it(`should resolve src/plugins/charts/common/static/color_maps/color_maps.ts to kibana-app`, () => { diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index b437c15688b9..30383559e7fe 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -182,10 +182,10 @@ export const TEMPORARILY_IGNORED_PATHS = [ 'x-pack/plugins/monitoring/public/icons/health-green.svg', 'x-pack/plugins/monitoring/public/icons/health-red.svg', 'x-pack/plugins/monitoring/public/icons/health-yellow.svg', - 'x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf', - 'x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf', - 'x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf', - 'x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf', - 'x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf', - 'x-pack/plugins/screenshotting/server/assets/img/logo-grey.png', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf', + 'x-pack/platform/plugins/shared/screenshotting/server/assets/img/logo-grey.png', ]; diff --git a/src/dev/storybook/aliases.ts b/src/dev/storybook/aliases.ts index 4991ac0dfe44..2bf3888ce6cb 100644 --- a/src/dev/storybook/aliases.ts +++ b/src/dev/storybook/aliases.ts @@ -17,7 +17,8 @@ export const storybookAliases = { canvas: 'x-pack/plugins/canvas/storybook', cases: 'packages/kbn-cases-components/.storybook', cell_actions: 'src/platform/packages/shared/kbn-cell-actions/.storybook', - cloud_security_posture_packages: 'x-pack/packages/kbn-cloud-security-posture/storybook/config', + cloud_security_posture_packages: + 'x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook', cloud: 'packages/cloud/.storybook', coloring: 'packages/kbn-coloring/.storybook', language_documentation_popover: @@ -49,7 +50,7 @@ export const storybookAliases = { inventory: 'x-pack/plugins/observability_solution/inventory/.storybook', investigate: 'x-pack/solutions/observability/plugins/investigate_app/.storybook', kibana_react: 'src/plugins/kibana_react/.storybook', - lists: 'x-pack/plugins/lists/.storybook', + lists: 'x-pack/solutions/security/plugins/lists/.storybook', logs_explorer: 'x-pack/plugins/observability_solution/logs_explorer/.storybook', management: 'packages/kbn-management/storybook/config', observability: 'x-pack/solutions/observability/plugins/observability/.storybook', diff --git a/packages/kbn-openapi-common/README.md b/src/platform/packages/shared/kbn-openapi-common/README.md similarity index 100% rename from packages/kbn-openapi-common/README.md rename to src/platform/packages/shared/kbn-openapi-common/README.md diff --git a/src/platform/packages/shared/kbn-openapi-common/jest.config.js b/src/platform/packages/shared/kbn-openapi-common/jest.config.js new file mode 100644 index 000000000000..12c38e415465 --- /dev/null +++ b/src/platform/packages/shared/kbn-openapi-common/jest.config.js @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +module.exports = { + preset: '@kbn/test/jest_node', + rootDir: '../../../../..', + roots: ['/src/platform/packages/shared/kbn-openapi-common'], +}; diff --git a/packages/kbn-openapi-common/kibana.jsonc b/src/platform/packages/shared/kbn-openapi-common/kibana.jsonc similarity index 100% rename from packages/kbn-openapi-common/kibana.jsonc rename to src/platform/packages/shared/kbn-openapi-common/kibana.jsonc diff --git a/packages/kbn-openapi-common/package.json b/src/platform/packages/shared/kbn-openapi-common/package.json similarity index 100% rename from packages/kbn-openapi-common/package.json rename to src/platform/packages/shared/kbn-openapi-common/package.json diff --git a/packages/kbn-openapi-common/schemas/error_responses.gen.ts b/src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.gen.ts similarity index 100% rename from packages/kbn-openapi-common/schemas/error_responses.gen.ts rename to src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.gen.ts diff --git a/packages/kbn-openapi-common/schemas/error_responses.schema.yaml b/src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml similarity index 100% rename from packages/kbn-openapi-common/schemas/error_responses.schema.yaml rename to src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml diff --git a/packages/kbn-openapi-common/schemas/primitives.gen.ts b/src/platform/packages/shared/kbn-openapi-common/schemas/primitives.gen.ts similarity index 100% rename from packages/kbn-openapi-common/schemas/primitives.gen.ts rename to src/platform/packages/shared/kbn-openapi-common/schemas/primitives.gen.ts diff --git a/packages/kbn-openapi-common/schemas/primitives.schema.yaml b/src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml similarity index 100% rename from packages/kbn-openapi-common/schemas/primitives.schema.yaml rename to src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml diff --git a/packages/kbn-openapi-common/schemas/primitives.test.ts b/src/platform/packages/shared/kbn-openapi-common/schemas/primitives.test.ts similarity index 100% rename from packages/kbn-openapi-common/schemas/primitives.test.ts rename to src/platform/packages/shared/kbn-openapi-common/schemas/primitives.test.ts diff --git a/src/platform/packages/shared/kbn-openapi-common/scripts/openapi_generate.js b/src/platform/packages/shared/kbn-openapi-common/scripts/openapi_generate.js new file mode 100644 index 000000000000..54fa109cfb2c --- /dev/null +++ b/src/platform/packages/shared/kbn-openapi-common/scripts/openapi_generate.js @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +require('../../../../../setup_node_env'); +const { resolve } = require('path'); +const { generate } = require('@kbn/openapi-generator'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await generate({ + title: 'OpenAPI Common Schemas (kbn-openapi-common)', + rootDir: ROOT, + sourceGlob: './schemas/**/*.schema.yaml', + templateName: 'zod_operation_schema', + }); +})(); diff --git a/packages/kbn-openapi-common/shared/index.ts b/src/platform/packages/shared/kbn-openapi-common/shared/index.ts similarity index 100% rename from packages/kbn-openapi-common/shared/index.ts rename to src/platform/packages/shared/kbn-openapi-common/shared/index.ts diff --git a/packages/kbn-openapi-common/shared/path_params_replacer.ts b/src/platform/packages/shared/kbn-openapi-common/shared/path_params_replacer.ts similarity index 100% rename from packages/kbn-openapi-common/shared/path_params_replacer.ts rename to src/platform/packages/shared/kbn-openapi-common/shared/path_params_replacer.ts diff --git a/src/platform/packages/shared/kbn-openapi-common/tsconfig.json b/src/platform/packages/shared/kbn-openapi-common/tsconfig.json new file mode 100644 index 000000000000..cf3d0ba7804a --- /dev/null +++ b/src/platform/packages/shared/kbn-openapi-common/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "exclude": ["target/**/*"], + "extends": "../../../../../tsconfig.base.json", + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/zod", + "@kbn/zod-helpers", + ] +} diff --git a/packages/kbn-securitysolution-es-utils/README.md b/src/platform/packages/shared/kbn-securitysolution-es-utils/README.md similarity index 100% rename from packages/kbn-securitysolution-es-utils/README.md rename to src/platform/packages/shared/kbn-securitysolution-es-utils/README.md diff --git a/packages/kbn-securitysolution-es-utils/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/jest.config.js b/src/platform/packages/shared/kbn-securitysolution-es-utils/jest.config.js new file mode 100644 index 000000000000..3a654a3a269e --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/jest.config.js @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/src/platform/packages/shared/kbn-securitysolution-es-utils'], +}; diff --git a/packages/kbn-securitysolution-es-utils/kibana.jsonc b/src/platform/packages/shared/kbn-securitysolution-es-utils/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-es-utils/kibana.jsonc rename to src/platform/packages/shared/kbn-securitysolution-es-utils/kibana.jsonc diff --git a/packages/kbn-securitysolution-es-utils/package.json b/src/platform/packages/shared/kbn-securitysolution-es-utils/package.json similarity index 100% rename from packages/kbn-securitysolution-es-utils/package.json rename to src/platform/packages/shared/kbn-securitysolution-es-utils/package.json diff --git a/packages/kbn-securitysolution-es-utils/src/bad_request_error/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/bad_request_error/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/bad_request_error/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/bad_request_error/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/create_data_stream/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_data_stream/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/create_data_stream/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_data_stream/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/decode_version/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/decode_version/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/decode_version/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/decode_version/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_all_index/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_all_index/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/delete_data_stream/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_data_stream/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/delete_data_stream/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_data_stream/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/delete_index_template/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_index_template/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/delete_index_template/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_index_template/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_policy/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_policy/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/delete_template/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_template/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/delete_template/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/delete_template/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_data_stream_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_data_stream_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_data_stream_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_data_stream_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_count/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_count/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_template_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_template_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_index_template_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_template_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_template_exists/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_template_exists/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/migrate_to_data_stream/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/migrate_to_data_stream/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/migrate_to_data_stream/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/migrate_to_data_stream/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/put_mappings/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/put_mappings/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/put_mappings/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/put_mappings/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/read_index/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_index/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/read_index/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_index/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/remove_policy_from_index/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_policy_from_index/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/remove_policy_from_index/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_policy_from_index/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/set_index_template/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_index_template/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/set_index_template/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_index_template/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/set_policy/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_policy/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/set_policy/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_policy/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/set_template/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_template/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/set_template/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/set_template/index.ts diff --git a/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/transform_error/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/transform_error/index.test.ts diff --git a/packages/kbn-securitysolution-es-utils/src/transform_error/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/transform_error/index.ts similarity index 100% rename from packages/kbn-securitysolution-es-utils/src/transform_error/index.ts rename to src/platform/packages/shared/kbn-securitysolution-es-utils/src/transform_error/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/tsconfig.json b/src/platform/packages/shared/kbn-securitysolution-es-utils/tsconfig.json new file mode 100644 index 000000000000..5a16f6bdaff6 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "target/**/*", + ], + "kbn_references": [ + "@kbn/zod-helpers", + "@kbn/zod", + ] +} diff --git a/packages/kbn-securitysolution-io-ts-types/README.md b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/README.md similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/README.md rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/README.md diff --git a/packages/kbn-securitysolution-io-ts-types/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-io-ts-types/jest.config.js b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/jest.config.js new file mode 100644 index 000000000000..309c3085d744 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/jest.config.js @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/src/platform/packages/shared/kbn-securitysolution-io-ts-types'], +}; diff --git a/packages/kbn-securitysolution-io-ts-types/kibana.jsonc b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/kibana.jsonc rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/kibana.jsonc diff --git a/packages/kbn-securitysolution-io-ts-types/package.json b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/package.json similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/package.json rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/package.json diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_false/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_boolean_true/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_csv_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_csv_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_csv_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_csv_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_csv_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_csv_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_csv_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_csv_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_empty_string/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_empty_string/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_empty_string/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_empty_string/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_empty_string/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_empty_string/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_empty_string/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_empty_string/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_string_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_string_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_string_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_string_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_string_boolean_false/index.ts diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_uuid/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_uuid/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_uuid/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_uuid/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_uuid/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_uuid/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_value/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_value/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_value/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_value/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_value/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_value/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_value/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_value/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/empty_string_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/empty_string_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/empty_string_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/empty_string_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/empty_string_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/empty_string_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/empty_string_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/empty_string_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/enumeration/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/enumeration/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/enumeration/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/enumeration/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/enumeration/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/enumeration/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/enumeration/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/enumeration/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/import_query_schema/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/import_query_schema/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/import_query_schema/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/import_query_schema/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/import_query_schema/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/import_query_schema/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/import_query_schema/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/import_query_schema/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/iso_date_string/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/iso_date_string/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/iso_date_string/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/iso_date_string/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/iso_date_string/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/iso_date_string/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/iso_date_string/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/iso_date_string/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/limited_size_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/limited_size_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/limited_size_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/limited_size_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/limited_size_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/limited_size_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/limited_size_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/limited_size_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_or_nullable_string_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_string/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_string/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_string/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_string/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/non_empty_string_array/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/number_between_zero_and_one_inclusive/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/only_false_allowed/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/operator/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/operator/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/operator/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/operator/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/positive_integer/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/positive_integer/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/positive_integer/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/positive_integer/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/positive_integer_greater_than_zero/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/string_to_positive_number/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/string_to_positive_number/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/string_to_positive_number/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/string_to_positive_number/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/time_duration/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/time_duration/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/time_duration/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/time_duration/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/uuid/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/uuid/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/uuid/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/uuid/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/uuid/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/uuid/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/uuid/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/uuid/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/version/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/version/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-types/src/version/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-types/src/version/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-io-ts-types/tsconfig.json b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/tsconfig.json new file mode 100644 index 000000000000..6bc8a84da337 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-io-ts-types/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/securitysolution-io-ts-utils" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-io-ts-utils/README.md b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/README.md similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/README.md rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/README.md diff --git a/packages/kbn-securitysolution-io-ts-utils/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/jest.config.js b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/jest.config.js new file mode 100644 index 000000000000..cfa70556f4b8 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/jest.config.js @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/src/platform/packages/shared/kbn-securitysolution-io-ts-utils'], +}; diff --git a/packages/kbn-securitysolution-io-ts-utils/kibana.jsonc b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/kibana.jsonc rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/kibana.jsonc diff --git a/packages/kbn-securitysolution-io-ts-utils/package.json b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/package.json similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/package.json rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/package.json diff --git a/packages/kbn-securitysolution-io-ts-utils/src/exact_check/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/exact_check/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/exact_check/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/exact_check/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/exact_check/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/exact_check/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/exact_check/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/exact_check/index.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/parse_schedule_dates/index.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/validate/index.test.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/validate/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/validate/index.test.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/validate/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-utils/src/validate/index.ts b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/validate/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-utils/src/validate/index.ts rename to src/platform/packages/shared/kbn-securitysolution-io-ts-utils/src/validate/index.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/tsconfig.json b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/tsconfig.json new file mode 100644 index 000000000000..ca5354ad56e4 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-io-ts-utils/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/datemath" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-rules/README.md b/src/platform/packages/shared/kbn-securitysolution-rules/README.md similarity index 100% rename from packages/kbn-securitysolution-rules/README.md rename to src/platform/packages/shared/kbn-securitysolution-rules/README.md diff --git a/packages/kbn-securitysolution-rules/index.ts b/src/platform/packages/shared/kbn-securitysolution-rules/index.ts similarity index 100% rename from packages/kbn-securitysolution-rules/index.ts rename to src/platform/packages/shared/kbn-securitysolution-rules/index.ts diff --git a/packages/kbn-securitysolution-rules/kibana.jsonc b/src/platform/packages/shared/kbn-securitysolution-rules/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-rules/kibana.jsonc rename to src/platform/packages/shared/kbn-securitysolution-rules/kibana.jsonc diff --git a/packages/kbn-securitysolution-rules/package.json b/src/platform/packages/shared/kbn-securitysolution-rules/package.json similarity index 100% rename from packages/kbn-securitysolution-rules/package.json rename to src/platform/packages/shared/kbn-securitysolution-rules/package.json diff --git a/packages/kbn-securitysolution-rules/src/configuration_constants.ts b/src/platform/packages/shared/kbn-securitysolution-rules/src/configuration_constants.ts similarity index 100% rename from packages/kbn-securitysolution-rules/src/configuration_constants.ts rename to src/platform/packages/shared/kbn-securitysolution-rules/src/configuration_constants.ts diff --git a/packages/kbn-securitysolution-rules/src/rule_type_constants.ts b/src/platform/packages/shared/kbn-securitysolution-rules/src/rule_type_constants.ts similarity index 100% rename from packages/kbn-securitysolution-rules/src/rule_type_constants.ts rename to src/platform/packages/shared/kbn-securitysolution-rules/src/rule_type_constants.ts diff --git a/packages/kbn-securitysolution-rules/src/rule_type_mappings.ts b/src/platform/packages/shared/kbn-securitysolution-rules/src/rule_type_mappings.ts similarity index 100% rename from packages/kbn-securitysolution-rules/src/rule_type_mappings.ts rename to src/platform/packages/shared/kbn-securitysolution-rules/src/rule_type_mappings.ts diff --git a/packages/kbn-securitysolution-rules/src/utils.ts b/src/platform/packages/shared/kbn-securitysolution-rules/src/utils.ts similarity index 100% rename from packages/kbn-securitysolution-rules/src/utils.ts rename to src/platform/packages/shared/kbn-securitysolution-rules/src/utils.ts diff --git a/src/platform/packages/shared/kbn-securitysolution-rules/tsconfig.json b/src/platform/packages/shared/kbn-securitysolution-rules/tsconfig.json new file mode 100644 index 000000000000..131ff3e6bb43 --- /dev/null +++ b/src/platform/packages/shared/kbn-securitysolution-rules/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-zod-helpers/README.md b/src/platform/packages/shared/kbn-zod-helpers/README.md similarity index 100% rename from packages/kbn-zod-helpers/README.md rename to src/platform/packages/shared/kbn-zod-helpers/README.md diff --git a/packages/kbn-zod-helpers/index.ts b/src/platform/packages/shared/kbn-zod-helpers/index.ts similarity index 100% rename from packages/kbn-zod-helpers/index.ts rename to src/platform/packages/shared/kbn-zod-helpers/index.ts diff --git a/src/platform/packages/shared/kbn-zod-helpers/jest.config.js b/src/platform/packages/shared/kbn-zod-helpers/jest.config.js new file mode 100644 index 000000000000..a24e94098381 --- /dev/null +++ b/src/platform/packages/shared/kbn-zod-helpers/jest.config.js @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/src/platform/packages/shared/kbn-zod-helpers'], +}; diff --git a/packages/kbn-zod-helpers/kibana.jsonc b/src/platform/packages/shared/kbn-zod-helpers/kibana.jsonc similarity index 100% rename from packages/kbn-zod-helpers/kibana.jsonc rename to src/platform/packages/shared/kbn-zod-helpers/kibana.jsonc diff --git a/packages/kbn-zod-helpers/package.json b/src/platform/packages/shared/kbn-zod-helpers/package.json similarity index 100% rename from packages/kbn-zod-helpers/package.json rename to src/platform/packages/shared/kbn-zod-helpers/package.json diff --git a/packages/kbn-zod-helpers/src/array_from_string.test.ts b/src/platform/packages/shared/kbn-zod-helpers/src/array_from_string.test.ts similarity index 100% rename from packages/kbn-zod-helpers/src/array_from_string.test.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/array_from_string.test.ts diff --git a/packages/kbn-zod-helpers/src/array_from_string.ts b/src/platform/packages/shared/kbn-zod-helpers/src/array_from_string.ts similarity index 100% rename from packages/kbn-zod-helpers/src/array_from_string.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/array_from_string.ts diff --git a/packages/kbn-zod-helpers/src/boolean_from_string.test.ts b/src/platform/packages/shared/kbn-zod-helpers/src/boolean_from_string.test.ts similarity index 100% rename from packages/kbn-zod-helpers/src/boolean_from_string.test.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/boolean_from_string.test.ts diff --git a/packages/kbn-zod-helpers/src/boolean_from_string.ts b/src/platform/packages/shared/kbn-zod-helpers/src/boolean_from_string.ts similarity index 100% rename from packages/kbn-zod-helpers/src/boolean_from_string.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/boolean_from_string.ts diff --git a/packages/kbn-zod-helpers/src/build_route_validation_with_zod.ts b/src/platform/packages/shared/kbn-zod-helpers/src/build_route_validation_with_zod.ts similarity index 100% rename from packages/kbn-zod-helpers/src/build_route_validation_with_zod.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/build_route_validation_with_zod.ts diff --git a/packages/kbn-zod-helpers/src/expect_parse_error.ts b/src/platform/packages/shared/kbn-zod-helpers/src/expect_parse_error.ts similarity index 100% rename from packages/kbn-zod-helpers/src/expect_parse_error.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/expect_parse_error.ts diff --git a/packages/kbn-zod-helpers/src/expect_parse_success.ts b/src/platform/packages/shared/kbn-zod-helpers/src/expect_parse_success.ts similarity index 100% rename from packages/kbn-zod-helpers/src/expect_parse_success.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/expect_parse_success.ts diff --git a/packages/kbn-zod-helpers/src/is_valid_date_math.ts b/src/platform/packages/shared/kbn-zod-helpers/src/is_valid_date_math.ts similarity index 100% rename from packages/kbn-zod-helpers/src/is_valid_date_math.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/is_valid_date_math.ts diff --git a/packages/kbn-zod-helpers/src/non_empty_string.ts b/src/platform/packages/shared/kbn-zod-helpers/src/non_empty_string.ts similarity index 100% rename from packages/kbn-zod-helpers/src/non_empty_string.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/non_empty_string.ts diff --git a/packages/kbn-zod-helpers/src/required_optional.ts b/src/platform/packages/shared/kbn-zod-helpers/src/required_optional.ts similarity index 100% rename from packages/kbn-zod-helpers/src/required_optional.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/required_optional.ts diff --git a/packages/kbn-zod-helpers/src/safe_parse_result.ts b/src/platform/packages/shared/kbn-zod-helpers/src/safe_parse_result.ts similarity index 100% rename from packages/kbn-zod-helpers/src/safe_parse_result.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/safe_parse_result.ts diff --git a/packages/kbn-zod-helpers/src/stringify_zod_error.ts b/src/platform/packages/shared/kbn-zod-helpers/src/stringify_zod_error.ts similarity index 100% rename from packages/kbn-zod-helpers/src/stringify_zod_error.ts rename to src/platform/packages/shared/kbn-zod-helpers/src/stringify_zod_error.ts diff --git a/src/platform/packages/shared/kbn-zod-helpers/tsconfig.json b/src/platform/packages/shared/kbn-zod-helpers/tsconfig.json new file mode 100644 index 000000000000..d3b33b22966b --- /dev/null +++ b/src/platform/packages/shared/kbn-zod-helpers/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "exclude": ["target/**/*"], + "extends": "../../../../../tsconfig.base.json", + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/datemath", + "@kbn/core", + "@kbn/zod", + ] +} diff --git a/src/platform/plugins/shared/dev_tools/public/application.tsx b/src/platform/plugins/shared/dev_tools/public/application.tsx index 0b66621fb2e9..3acbaa21ed5a 100644 --- a/src/platform/plugins/shared/dev_tools/public/application.tsx +++ b/src/platform/plugins/shared/dev_tools/public/application.tsx @@ -11,9 +11,8 @@ import React, { useEffect, useRef } from 'react'; import ReactDOM from 'react-dom'; import { Redirect, RouteComponentProps } from 'react-router-dom'; import { HashRouter as Router, Routes, Route } from '@kbn/shared-ux-router'; -import { EuiTab, EuiTabs, EuiToolTip, EuiBetaBadge } from '@elastic/eui'; +import { EuiTab, EuiTabs, EuiToolTip, EuiBetaBadge, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiThemeVars } from '@kbn/ui-theme'; import type { ApplicationStart, @@ -56,6 +55,7 @@ function DevToolsWrapper({ location, startServices, }: DevToolsWrapperProps) { + const { euiTheme } = useEuiTheme(); const { docTitleService, breadcrumbService } = appServices; const mountedTool = useRef(null); @@ -75,7 +75,7 @@ function DevToolsWrapper({ return (
- + {devTools.map((currentDevTool) => ( Record = () => ({ value: true, description: i18n.translate('esql.advancedSettings.enableESQLDescription', { defaultMessage: - 'This setting enables ES|QL in Kibana. By switching it off you will hide the ES|QL user interface from various applications. However, users will be able to access existing ES|QL saved searches, visualizations, etc.', + 'This setting enables ES|QL in Kibana. By switching it off you will hide the ES|QL user interface from various applications. However, users will be able to access existing ES|QL based Discover sessions, visualizations, etc.', }), requiresPageReload: true, schema: schema.boolean(), diff --git a/src/plugins/dashboard/common/dashboard_container/types.ts b/src/plugins/dashboard/common/dashboard_container/types.ts index dd3f7302038c..528eff1f96cb 100644 --- a/src/plugins/dashboard/common/dashboard_container/types.ts +++ b/src/plugins/dashboard/common/dashboard_container/types.ts @@ -8,7 +8,6 @@ */ import { - ViewMode, PanelState, EmbeddableInput, SavedObjectEmbeddableInput, @@ -17,6 +16,7 @@ import { Filter, Query, TimeRange } from '@kbn/es-query'; import type { Reference } from '@kbn/content-management-utils'; import { RefreshInterval } from '@kbn/data-plugin/common'; import { KibanaExecutionContext } from '@kbn/core-execution-context-common'; +import type { ViewMode } from '@kbn/presentation-publishing'; import type { DashboardOptions, GridData } from '../../server/content_management'; @@ -44,7 +44,7 @@ export interface DashboardPanelState< export type DashboardContainerByReferenceInput = SavedObjectEmbeddableInput; -export interface DashboardContainerInput extends EmbeddableInput { +export interface DashboardContainerInput extends Omit { // filter context to be passed to children query: Query; filters: Filter[]; diff --git a/src/plugins/dashboard/public/dashboard_app/dashboard_app.tsx b/src/plugins/dashboard/public/dashboard_app/dashboard_app.tsx index 06f56669630e..39616653eea2 100644 --- a/src/plugins/dashboard/public/dashboard_app/dashboard_app.tsx +++ b/src/plugins/dashboard/public/dashboard_app/dashboard_app.tsx @@ -14,10 +14,10 @@ import { debounceTime } from 'rxjs'; import { v4 as uuidv4 } from 'uuid'; import { DASHBOARD_APP_LOCATOR } from '@kbn/deeplinks-analytics'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { useExecutionContext } from '@kbn/kibana-react-plugin/public'; import { createKbnUrlStateStorage, withNotifyOnErrors } from '@kbn/kibana-utils-plugin/public'; +import { ViewMode } from '@kbn/presentation-publishing'; import { DashboardApi, DashboardCreationOptions, DashboardRenderer } from '..'; import { SharedDashboardState } from '../../common'; import { @@ -154,7 +154,7 @@ export function DashboardApp({ // if print mode is active, force viewMode.PRINT ...(screenshotModeService.isScreenshotMode() && screenshotModeService.getScreenshotContext('layout') === 'print' - ? { viewMode: ViewMode.PRINT } + ? { viewMode: 'print' as ViewMode } : {}), }; }; diff --git a/src/plugins/dashboard/public/dashboard_app/dashboard_router.tsx b/src/plugins/dashboard/public/dashboard_app/dashboard_router.tsx index f994d9aa20c8..6b59bf03a4bc 100644 --- a/src/plugins/dashboard/public/dashboard_app/dashboard_router.tsx +++ b/src/plugins/dashboard/public/dashboard_app/dashboard_router.tsx @@ -10,7 +10,6 @@ import './_dashboard_app.scss'; import { AppMountParameters, CoreStart } from '@kbn/core/public'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { createKbnUrlStateStorage, withNotifyOnErrors } from '@kbn/kibana-utils-plugin/public'; import { KibanaRenderContextProvider } from '@kbn/react-kibana-context-render'; import { Route, Routes } from '@kbn/shared-ux-router'; @@ -72,7 +71,7 @@ export async function mountApp({ if (redirectTo.destination === 'dashboard') { path = redirectTo.id ? createDashboardEditUrl(redirectTo.id) : CREATE_NEW_DASHBOARD_URL; if (redirectTo.editMode) { - state = { viewMode: ViewMode.EDIT }; + state = { viewMode: 'edit' }; } } else { path = createDashboardListingFilterUrl(redirectTo.filter); diff --git a/src/plugins/dashboard/public/dashboard_app/listing_page/dashboard_listing_page.tsx b/src/plugins/dashboard/public/dashboard_app/listing_page/dashboard_listing_page.tsx index 59b3b3926060..55f8bcabdfea 100644 --- a/src/plugins/dashboard/public/dashboard_app/listing_page/dashboard_listing_page.tsx +++ b/src/plugins/dashboard/public/dashboard_app/listing_page/dashboard_listing_page.tsx @@ -10,7 +10,6 @@ import React, { useEffect, useState } from 'react'; import { syncGlobalQueryStateWithUrl } from '@kbn/data-plugin/public'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import type { IKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; import { DashboardRedirect } from '../../dashboard_container/types'; @@ -108,7 +107,7 @@ export const DashboardListingPage = ({ useSessionStorageIntegration={true} initialFilter={initialFilter ?? titleFilter} goToDashboard={(id, viewMode) => { - redirectTo({ destination: 'dashboard', id, editMode: viewMode === ViewMode.EDIT }); + redirectTo({ destination: 'dashboard', id, editMode: viewMode === 'edit' }); }} getDashboardUrl={(id, timeRestore) => { return getDashboardListItemLink(kbnUrlStateStorage, id, timeRestore); diff --git a/src/plugins/dashboard/public/dashboard_app/top_nav/share/show_share_modal.tsx b/src/plugins/dashboard/public/dashboard_app/top_nav/share/show_share_modal.tsx index 41a290844328..d8b4c341cf67 100644 --- a/src/plugins/dashboard/public/dashboard_app/top_nav/share/show_share_modal.tsx +++ b/src/plugins/dashboard/public/dashboard_app/top_nav/share/show_share_modal.tsx @@ -15,7 +15,6 @@ import { EuiCallOut, EuiCheckboxGroup } from '@elastic/eui'; import type { Capabilities } from '@kbn/core/public'; import { QueryState } from '@kbn/data-plugin/common'; import { DASHBOARD_APP_LOCATOR } from '@kbn/deeplinks-analytics'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { i18n } from '@kbn/i18n'; import { getStateFromKbnUrl, setStateToKbnUrl, unhashUrl } from '@kbn/kibana-utils-plugin/public'; @@ -177,7 +176,7 @@ export function ShowShareModal({ dashboardId: savedObjectId, preserveSavedFilters: true, refreshInterval: undefined, // We don't share refresh interval externally - viewMode: ViewMode.VIEW, // For share locators we always load the dashboard in view mode + viewMode: 'view', // For share locators we always load the dashboard in view mode useHash: false, timeRange: dataService.query.timefilter.timefilter.getTime(), ...unsavedStateForLocator, diff --git a/src/plugins/dashboard/public/dashboard_app/top_nav/use_dashboard_menu_items.tsx b/src/plugins/dashboard/public/dashboard_app/top_nav/use_dashboard_menu_items.tsx index 07e29db545e7..6f3d9c1cf565 100644 --- a/src/plugins/dashboard/public/dashboard_app/top_nav/use_dashboard_menu_items.tsx +++ b/src/plugins/dashboard/public/dashboard_app/top_nav/use_dashboard_menu_items.tsx @@ -9,7 +9,6 @@ import { Dispatch, SetStateAction, useCallback, useMemo, useState } from 'react'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import type { TopNavMenuData } from '@kbn/navigation-plugin/public'; import useMountedState from 'react-use/lib/useMountedState'; @@ -97,8 +96,8 @@ export const useDashboardMenuItems = ({ dashboardApi.clearOverlays(); const switchModes = switchToViewMode ? () => { - dashboardApi.setViewMode(ViewMode.VIEW); - getDashboardBackupService().storeViewMode(ViewMode.VIEW); + dashboardApi.setViewMode('view'); + getDashboardBackupService().storeViewMode('view'); } : undefined; if (!hasUnsavedChanges) { @@ -112,7 +111,7 @@ export const useDashboardMenuItems = ({ setIsResetting(false); switchModes?.(); } - }, viewMode as ViewMode); + }, viewMode); }, [dashboardApi, hasUnsavedChanges, viewMode, isMounted] ); @@ -146,8 +145,8 @@ export const useDashboardMenuItems = ({ testId: 'dashboardEditMode', className: 'eui-hideFor--s eui-hideFor--xs', // hide for small screens - editing doesn't work in mobile mode. run: () => { - getDashboardBackupService().storeViewMode(ViewMode.EDIT); - dashboardApi.setViewMode(ViewMode.EDIT); + getDashboardBackupService().storeViewMode('edit'); + dashboardApi.setViewMode('edit'); dashboardApi.clearOverlays(); }, disableButton: disableTopNav, @@ -171,13 +170,13 @@ export const useDashboardMenuItems = ({ testId: 'dashboardInteractiveSaveMenuItem', run: dashboardInteractiveSave, label: - viewMode === ViewMode.VIEW + viewMode === 'view' ? topNavStrings.viewModeInteractiveSave.label : Boolean(lastSavedId) ? topNavStrings.editModeInteractiveSave.label : topNavStrings.quickSave.label, description: - viewMode === ViewMode.VIEW + viewMode === 'view' ? topNavStrings.viewModeInteractiveSave.description : topNavStrings.editModeInteractiveSave.description, } as TopNavMenuData, @@ -232,7 +231,7 @@ export const useDashboardMenuItems = ({ isResetting || !hasUnsavedChanges || hasOverlays || - (viewMode === ViewMode.EDIT && (isSaveInProgress || !lastSavedId)), + (viewMode === 'edit' && (isSaveInProgress || !lastSavedId)), isLoading: isResetting, run: () => resetChanges(), }; diff --git a/src/plugins/dashboard/public/dashboard_app/url/search_sessions_integration.ts b/src/plugins/dashboard/public/dashboard_app/url/search_sessions_integration.ts index 37c9af6944f7..9992ac661614 100644 --- a/src/plugins/dashboard/public/dashboard_app/url/search_sessions_integration.ts +++ b/src/plugins/dashboard/public/dashboard_app/url/search_sessions_integration.ts @@ -18,7 +18,6 @@ import { import { replaceUrlHashQuery } from '@kbn/kibana-utils-plugin/common'; import type { Query } from '@kbn/es-query'; import { SearchSessionInfoProvider } from '@kbn/data-plugin/public'; -import type { ViewMode } from '@kbn/embeddable-plugin/common'; import { DASHBOARD_APP_LOCATOR } from '@kbn/deeplinks-analytics'; import { SEARCH_SESSION_ID } from '../../dashboard_constants'; import { DashboardLocatorParams } from '../../dashboard_container'; @@ -73,7 +72,7 @@ function getLocatorParams({ }): DashboardLocatorParams { const savedObjectId = dashboardApi.savedObjectId.value; return { - viewMode: (dashboardApi.viewMode.value as ViewMode) ?? 'view', + viewMode: dashboardApi.viewMode.value ?? 'view', useHash: false, preserveSavedFilters: false, filters: dataService.query.filterManager.getFilters(), diff --git a/src/plugins/dashboard/public/dashboard_constants.ts b/src/plugins/dashboard/public/dashboard_constants.ts index da8c56bd70ee..190b6653341a 100644 --- a/src/plugins/dashboard/public/dashboard_constants.ts +++ b/src/plugins/dashboard/public/dashboard_constants.ts @@ -7,7 +7,6 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { ViewMode } from '@kbn/embeddable-plugin/common'; import type { DashboardContainerInput } from '../common'; // ------------------------------------------------------------------ @@ -85,7 +84,7 @@ export const DASHBOARD_CACHE_TTL = 1000 * 60 * 5; // time to live = 5 minutes // Default State // ------------------------------------------------------------------ export const DEFAULT_DASHBOARD_INPUT: Omit = { - viewMode: ViewMode.VIEW, + viewMode: 'view', timeRestore: false, query: { query: '', language: 'kuery' }, description: '', diff --git a/src/plugins/dashboard/public/dashboard_container/component/empty_screen/dashboard_empty_screen.tsx b/src/plugins/dashboard/public/dashboard_container/component/empty_screen/dashboard_empty_screen.tsx index b7a4facde1c1..73d225dca3b4 100644 --- a/src/plugins/dashboard/public/dashboard_container/component/empty_screen/dashboard_empty_screen.tsx +++ b/src/plugins/dashboard/public/dashboard_container/component/empty_screen/dashboard_empty_screen.tsx @@ -20,7 +20,6 @@ import { EuiText, } from '@elastic/eui'; import { METRIC_TYPE } from '@kbn/analytics'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { useStateFromPublishingSubject } from '@kbn/presentation-publishing'; import { useDashboardApi } from '../../../dashboard_api/use_dashboard_api'; @@ -131,7 +130,7 @@ export function DashboardEmptyScreen() { } if (showWriteControls) { return ( - dashboardApi.setViewMode(ViewMode.EDIT)}> + dashboardApi.setViewMode('edit')}> {emptyScreenStrings.getEditLinkTitle()} ); diff --git a/src/plugins/dashboard/public/dashboard_container/component/grid/dashboard_grid.tsx b/src/plugins/dashboard/public/dashboard_container/component/grid/dashboard_grid.tsx index 1f5e48dd7a5d..e521a1bbd276 100644 --- a/src/plugins/dashboard/public/dashboard_container/component/grid/dashboard_grid.tsx +++ b/src/plugins/dashboard/public/dashboard_container/component/grid/dashboard_grid.tsx @@ -15,8 +15,6 @@ import classNames from 'classnames'; import React, { useState, useMemo, useCallback, useEffect } from 'react'; import { Layout, Responsive as ResponsiveReactGridLayout } from 'react-grid-layout'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; - import { useBatchedPublishingSubjects } from '@kbn/presentation-publishing'; import { useAppFixedViewport } from '@kbn/core-rendering-browser'; import { DashboardPanelState } from '../../../../common'; @@ -106,7 +104,7 @@ export const DashboardGrid = ({ const onLayoutChange = useCallback( (newLayout: Array) => { - if (viewMode !== ViewMode.EDIT) return; + if (viewMode !== 'edit') return; const updatedPanels: { [key: string]: DashboardPanelState } = newLayout.reduce( (updatedPanelsAcc, panelLayout) => { @@ -127,8 +125,8 @@ export const DashboardGrid = ({ const classes = classNames({ 'dshLayout-withoutMargins': !useMargins, - 'dshLayout--viewing': viewMode === ViewMode.VIEW, - 'dshLayout--editing': viewMode !== ViewMode.VIEW, + 'dshLayout--viewing': viewMode === 'view', + 'dshLayout--editing': viewMode !== 'view', 'dshLayout--noAnimation': !animatePanelTransforms || delayedIsPanelExpanded, 'dshLayout-isMaximizedPanel': expandedPanelId !== undefined, }); @@ -136,7 +134,7 @@ export const DashboardGrid = ({ const { layouts, breakpoints, columns } = useDashboardGridSettings(panelsInOrder, panels); // in print mode, dashboard layout is not controlled by React Grid Layout - if (viewMode === ViewMode.PRINT) { + if (viewMode === 'print') { return <>{panelComponents}; } diff --git a/src/plugins/dashboard/public/dashboard_container/component/grid/use_dashboard_grid_settings.tsx b/src/plugins/dashboard/public/dashboard_container/component/grid/use_dashboard_grid_settings.tsx index 155d7022141d..50481d1a82f7 100644 --- a/src/plugins/dashboard/public/dashboard_container/component/grid/use_dashboard_grid_settings.tsx +++ b/src/plugins/dashboard/public/dashboard_container/component/grid/use_dashboard_grid_settings.tsx @@ -10,7 +10,6 @@ import { useMemo } from 'react'; import { useEuiTheme } from '@elastic/eui'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { useStateFromPublishingSubject } from '@kbn/presentation-publishing'; import { DashboardPanelMap } from '../../../../common'; @@ -30,14 +29,14 @@ export const useDashboardGridSettings = (panelsInOrder: string[], panels: Dashbo }, [panels, panelsInOrder]); const breakpoints = useMemo( - () => ({ lg: euiTheme.breakpoint.m, ...(viewMode === ViewMode.VIEW ? { sm: 0 } : {}) }), + () => ({ lg: euiTheme.breakpoint.m, ...(viewMode === 'view' ? { sm: 0 } : {}) }), [viewMode, euiTheme.breakpoint.m] ); const columns = useMemo( () => ({ lg: DASHBOARD_GRID_COLUMN_COUNT, - ...(viewMode === ViewMode.VIEW ? { sm: 1 } : {}), + ...(viewMode === 'view' ? { sm: 1 } : {}), }), [viewMode] ); diff --git a/src/plugins/dashboard/public/dashboard_container/component/viewport/dashboard_viewport.tsx b/src/plugins/dashboard/public/dashboard_container/component/viewport/dashboard_viewport.tsx index 32f1f830ba93..0252341b5f4b 100644 --- a/src/plugins/dashboard/public/dashboard_container/component/viewport/dashboard_viewport.tsx +++ b/src/plugins/dashboard/public/dashboard_container/component/viewport/dashboard_viewport.tsx @@ -13,7 +13,7 @@ import useResizeObserver from 'use-resize-observer/polyfilled'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { EuiPortal } from '@elastic/eui'; -import { ReactEmbeddableRenderer, ViewMode } from '@kbn/embeddable-plugin/public'; +import { ReactEmbeddableRenderer } from '@kbn/embeddable-plugin/public'; import { ExitFullScreenButton } from '@kbn/shared-ux-button-exit-full-screen'; import { @@ -119,7 +119,7 @@ export const DashboardViewport = ({ dashboardContainer }: { dashboardContainer?: 'dshDashboardViewportWrapper--isFullscreen': fullScreenMode, })} > - {viewMode !== ViewMode.PRINT ? ( + {viewMode !== 'print' ? (
@@ -116,7 +116,7 @@ export const resetConfirmStrings = { defaultMessage: 'Reset dashboard?', }), getResetSubtitle: (viewMode: ViewMode) => - viewMode === ViewMode.EDIT + viewMode === 'edit' ? i18n.translate('dashboard.discardChangesConfirmModal.discardChangesDescription', { defaultMessage: `All unsaved changes will be lost.`, }) diff --git a/src/plugins/dashboard/public/dashboard_listing/confirm_overlays.tsx b/src/plugins/dashboard/public/dashboard_listing/confirm_overlays.tsx index a2adea2470ab..d6e3728df023 100644 --- a/src/plugins/dashboard/public/dashboard_listing/confirm_overlays.tsx +++ b/src/plugins/dashboard/public/dashboard_listing/confirm_overlays.tsx @@ -21,9 +21,9 @@ import { EuiOutsideClickDetector, EuiText, } from '@elastic/eui'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { toMountPoint } from '@kbn/react-kibana-mount'; +import { ViewMode } from '@kbn/presentation-publishing'; import { coreServices } from '../services/kibana_services'; import { createConfirmStrings, resetConfirmStrings } from './_dashboard_listing_strings'; @@ -31,12 +31,12 @@ export type DiscardOrKeepSelection = 'cancel' | 'discard' | 'keep'; export const confirmDiscardUnsavedChanges = ( discardCallback: () => void, - viewMode: ViewMode = ViewMode.EDIT // we want to show the danger modal on the listing page + viewMode: ViewMode = 'edit' // we want to show the danger modal on the listing page ) => { coreServices.overlays .openConfirm(resetConfirmStrings.getResetSubtitle(viewMode), { confirmButtonText: resetConfirmStrings.getResetConfirmButtonText(), - buttonColor: viewMode === ViewMode.EDIT ? 'danger' : 'primary', + buttonColor: viewMode === 'edit' ? 'danger' : 'primary', maxWidth: 500, defaultFocusedButton: EUI_MODAL_CANCEL_BUTTON, title: resetConfirmStrings.getResetTitle(), diff --git a/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.test.tsx b/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.test.tsx index 74b538d87c20..5cadd610ea2a 100644 --- a/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.test.tsx +++ b/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.test.tsx @@ -11,7 +11,6 @@ import { ComponentType, mount } from 'enzyme'; import React from 'react'; import { findTestSubject } from '@elastic/eui/lib/test'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { I18nProvider } from '@kbn/i18n-react'; import { waitFor } from '@testing-library/react'; @@ -72,7 +71,7 @@ describe('Unsaved listing', () => { expect(getEditButton().length).toEqual(1); }); getEditButton().simulate('click'); - expect(props.goToDashboard).toHaveBeenCalledWith('dashboardUnsavedOne', ViewMode.EDIT); + expect(props.goToDashboard).toHaveBeenCalledWith('dashboardUnsavedOne', 'edit'); }); it('Redirects to new dashboard when continue editing clicked', async () => { @@ -85,7 +84,7 @@ describe('Unsaved listing', () => { expect(getEditButton().length).toBe(1); }); getEditButton().simulate('click'); - expect(props.goToDashboard).toHaveBeenCalledWith(undefined, ViewMode.EDIT); + expect(props.goToDashboard).toHaveBeenCalledWith(undefined, 'edit'); }); it('Shows a warning then clears changes when delete unsaved changes is pressed', async () => { diff --git a/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.tsx b/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.tsx index 04f40a199e83..1ab1aecfce91 100644 --- a/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.tsx +++ b/src/plugins/dashboard/public/dashboard_listing/dashboard_unsaved_listing.tsx @@ -18,8 +18,7 @@ import { } from '@elastic/eui'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; - +import { ViewMode } from '@kbn/presentation-publishing'; import type { DashboardAttributes } from '../../server/content_management'; import { DASHBOARD_PANELS_UNSAVED_ID, @@ -124,7 +123,7 @@ export const DashboardUnsavedListing = ({ const onOpen = useCallback( (id?: string) => { - goToDashboard(id, ViewMode.EDIT); + goToDashboard(id, 'edit'); }, [goToDashboard] ); diff --git a/src/plugins/dashboard/public/dashboard_listing/hooks/use_dashboard_listing_table.tsx b/src/plugins/dashboard/public/dashboard_listing/hooks/use_dashboard_listing_table.tsx index e29f93f97c17..23d29898e49c 100644 --- a/src/plugins/dashboard/public/dashboard_listing/hooks/use_dashboard_listing_table.tsx +++ b/src/plugins/dashboard/public/dashboard_listing/hooks/use_dashboard_listing_table.tsx @@ -14,7 +14,7 @@ import { ContentInsightsClient } from '@kbn/content-management-content-insights- import { TableListViewTableProps } from '@kbn/content-management-table-list-view-table'; import type { SavedObjectsFindOptionsReference } from '@kbn/core/public'; import { reportPerformanceMetricEvent } from '@kbn/ebt-tools'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; +import { ViewMode } from '@kbn/presentation-publishing'; import type { DashboardSearchOut } from '../../../server/content_management'; import { @@ -270,7 +270,7 @@ export const useDashboardListingTable = ({ ); const editItem = useCallback( - ({ id }: { id: string | undefined }) => goToDashboard(id, ViewMode.EDIT), + ({ id }: { id: string | undefined }) => goToDashboard(id, 'edit'), [goToDashboard] ); diff --git a/src/plugins/dashboard/public/dashboard_listing/types.ts b/src/plugins/dashboard/public/dashboard_listing/types.ts index 0f5e24536624..84a47012b04c 100644 --- a/src/plugins/dashboard/public/dashboard_listing/types.ts +++ b/src/plugins/dashboard/public/dashboard_listing/types.ts @@ -9,7 +9,7 @@ import type { PropsWithChildren } from 'react'; import type { UserContentCommonSchema } from '@kbn/content-management-table-list-view-common'; -import type { ViewMode } from '@kbn/embeddable-plugin/public'; +import { ViewMode } from '@kbn/presentation-publishing'; export type DashboardListingProps = PropsWithChildren<{ disableCreateDashboardButton?: boolean; diff --git a/src/plugins/dashboard/public/mocks.tsx b/src/plugins/dashboard/public/mocks.tsx index 1a275d805e5e..334bf9ee0520 100644 --- a/src/plugins/dashboard/public/mocks.tsx +++ b/src/plugins/dashboard/public/mocks.tsx @@ -9,7 +9,6 @@ import { ControlGroupApi } from '@kbn/controls-plugin/public'; import { BehaviorSubject } from 'rxjs'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { DashboardStart } from './plugin'; import { DashboardState } from './dashboard_api/types'; import { getDashboardApi } from './dashboard_api/get_dashboard_api'; @@ -97,7 +96,6 @@ export function buildMockDashboardApi({ dashboardInput: { ...initialState, executionContext: { type: 'dashboard' }, - viewMode: initialState.viewMode as ViewMode, id: savedObjectId ?? '123', } as SavedDashboardInput, references: [], diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index a8e7cd96f38d..c8b2244d6865 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -298,7 +298,7 @@ export class DashboardPlugin defaultMessage: 'Analyze data in dashboards.', }), description: i18n.translate('dashboard.featureCatalogue.dashboardDescription', { - defaultMessage: 'Display and share a collection of visualizations and saved searches.', + defaultMessage: 'Display and share a collection of visualizations and search results.', }), icon: 'dashboardApp', path: `/app/${DASHBOARD_APP_ID}#${LANDING_PAGE_PATH}`, diff --git a/src/plugins/dashboard/public/services/dashboard_content_management_service/lib/load_dashboard_state.ts b/src/plugins/dashboard/public/services/dashboard_content_management_service/lib/load_dashboard_state.ts index 9773291b2ca5..f0fe47b54ba9 100644 --- a/src/plugins/dashboard/public/services/dashboard_content_management_service/lib/load_dashboard_state.ts +++ b/src/plugins/dashboard/public/services/dashboard_content_management_service/lib/load_dashboard_state.ts @@ -11,7 +11,6 @@ import { has } from 'lodash'; import { v4 as uuidv4 } from 'uuid'; import { injectSearchSourceReferences } from '@kbn/data-plugin/public'; -import { ViewMode } from '@kbn/embeddable-plugin/public'; import { Filter, Query } from '@kbn/es-query'; import { SavedObjectNotFound } from '@kbn/kibana-utils-plugin/public'; @@ -188,7 +187,7 @@ export const loadDashboardState = async ({ query, title, - viewMode: ViewMode.VIEW, // dashboards loaded from saved object default to view mode. If it was edited recently, the view mode from session storage will override this. + viewMode: 'view', // dashboards loaded from saved object default to view mode. If it was edited recently, the view mode from session storage will override this. tags: savedObjectsTaggingService?.getTaggingApi()?.ui.getTagIdsFromReferences(references) ?? [], diff --git a/src/plugins/data/server/ui_settings.ts b/src/plugins/data/server/ui_settings.ts index 8dc58c3ffd63..857de03d4dbd 100644 --- a/src/plugins/data/server/ui_settings.ts +++ b/src/plugins/data/server/ui_settings.ts @@ -55,7 +55,7 @@ export function getUiSettings( value: true, description: i18n.translate('data.advancedSettings.docTableHighlightText', { defaultMessage: - 'Highlight results in Discover and Saved Searches Dashboard. ' + + 'Highlights search results in Discover and Discover session panels on dashboards. ' + 'Highlighting makes requests slow when working on big documents.', }), category: ['discover'], diff --git a/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/__snapshots__/header.test.tsx.snap b/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/__snapshots__/header.test.tsx.snap index 83a272d88d15..97486302553f 100644 --- a/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/__snapshots__/header.test.tsx.snap +++ b/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/__snapshots__/header.test.tsx.snap @@ -7,7 +7,7 @@ exports[`Header should render normally 1`] = ` >

diff --git a/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/header.tsx b/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/header.tsx index 3530493a7490..86a77e6512af 100644 --- a/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/header.tsx +++ b/src/plugins/data_view_management/public/components/edit_index_pattern/source_filters_table/components/header/header.tsx @@ -19,7 +19,7 @@ export const Header = () => (

diff --git a/src/plugins/discover/README.md b/src/plugins/discover/README.md index 6240cd63f3ea..6f3f17c97e7a 100644 --- a/src/plugins/discover/README.md +++ b/src/plugins/discover/README.md @@ -16,7 +16,7 @@ One folder for every "route", each folder contains files and folders related onl * **[/not_found](./public/application/not_found)** (Rendered when a route can't be found) * **[/view_alert](./public/application/view_alert)** (Forwarding links in alert notifications) * **[/components](./public/components)** (All React components used in more than just one app) -* **[/embeddable](./public/embeddable)** (Code related to the saved search embeddable, rendered on dashboards) +* **[/embeddable](./public/embeddable)** (Code related to the Discover session embeddable, rendered on dashboards) * **[/hooks](./public/hooks)** (Code containing React hooks) * **[/services](./public/services)** (Services either for external or internal use) * **[/utils](./public/utils)** (All utility functions used across more than one application) diff --git a/src/plugins/discover/public/application/index.tsx b/src/plugins/discover/public/application/index.tsx index 426e38881172..99fc03170a9b 100644 --- a/src/plugins/discover/public/application/index.tsx +++ b/src/plugins/discover/public/application/index.tsx @@ -37,7 +37,7 @@ export const renderApp = ({ defaultMessage: 'Read only', }), tooltip: i18n.translate('discover.badge.readOnly.tooltip', { - defaultMessage: 'Unable to save searches', + defaultMessage: 'Unable to save Discover sessions', }), iconType: 'glasses', }); diff --git a/src/plugins/discover/public/application/main/components/top_nav/__snapshots__/open_search_panel.test.tsx.snap b/src/plugins/discover/public/application/main/components/top_nav/__snapshots__/open_search_panel.test.tsx.snap index b1b399d1bd73..934e7068e78d 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/__snapshots__/open_search_panel.test.tsx.snap +++ b/src/plugins/discover/public/application/main/components/top_nav/__snapshots__/open_search_panel.test.tsx.snap @@ -14,7 +14,7 @@ exports[`OpenSearchPanel render 1`] = ` >

@@ -25,7 +25,7 @@ exports[`OpenSearchPanel render 1`] = ` id="discoverOpenSearch" noItemsMessage={ } @@ -34,7 +34,7 @@ exports[`OpenSearchPanel render 1`] = ` Array [ Object { "getIconForSavedObject": [Function], - "name": "Saved search", + "name": "Discover session", "type": "search", }, ] @@ -59,11 +59,11 @@ exports[`OpenSearchPanel render 1`] = ` diff --git a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_new_search.tsx b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_new_search.tsx index b67f14f31c56..a27b1f5753e2 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_new_search.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_new_search.tsx @@ -19,11 +19,8 @@ export const getNewSearchAppMenuItem = ({ id: AppMenuActionId.new, type: AppMenuActionType.primary, controlProps: { - label: i18n.translate('discover.localMenu.localMenu.newSearchTitle', { - defaultMessage: 'New', - }), - description: i18n.translate('discover.localMenu.newSearchDescription', { - defaultMessage: 'New Search', + label: i18n.translate('discover.localMenu.localMenu.newDiscoverSessionTitle', { + defaultMessage: 'New session', }), iconType: 'plus', testId: 'discoverNewButton', diff --git a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_open_search.tsx b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_open_search.tsx index e8f6c5448d60..0a3d75af893c 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_open_search.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_open_search.tsx @@ -21,11 +21,8 @@ export const getOpenSearchAppMenuItem = ({ id: AppMenuActionId.open, type: AppMenuActionType.primary, controlProps: { - label: i18n.translate('discover.localMenu.openTitle', { - defaultMessage: 'Open', - }), - description: i18n.translate('discover.localMenu.openSavedSearchDescription', { - defaultMessage: 'Open Saved Search', + label: i18n.translate('discover.localMenu.openDiscoverSessionTitle', { + defaultMessage: 'Open session', }), iconType: 'folderOpen', testId: 'discoverOpenButton', diff --git a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_share.tsx b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_share.tsx index f1a030a40ea0..87514e81a063 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_share.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/app_menu_actions/get_share.tsx @@ -34,7 +34,7 @@ export const getShareAppMenuItem = ({ defaultMessage: 'Share', }), description: i18n.translate('discover.localMenu.shareSearchDescription', { - defaultMessage: 'Share Search', + defaultMessage: 'Share Discover session', }), iconType: 'share', testId: 'shareTopNavButton', @@ -108,7 +108,7 @@ export const getShareAppMenuItem = ({ objectType: 'search', objectTypeMeta: { title: i18n.translate('discover.share.shareModal.title', { - defaultMessage: 'Share this search', + defaultMessage: 'Share this Discover session', }), }, sharingData: { @@ -119,7 +119,7 @@ export const getShareAppMenuItem = ({ title: savedSearch.title || i18n.translate('discover.localMenu.fallbackReportTitle', { - defaultMessage: 'Untitled discover search', + defaultMessage: 'Untitled Discover session', }), }, isDirty: !savedSearch.id || stateContainer.appState.hasChanged(), diff --git a/src/plugins/discover/public/application/main/components/top_nav/esql_dataview_transition/esql_dataview_transition_modal.tsx b/src/plugins/discover/public/application/main/components/top_nav/esql_dataview_transition/esql_dataview_transition_modal.tsx index 342d8c4f1684..d52d25064d30 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/esql_dataview_transition/esql_dataview_transition_modal.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/esql_dataview_transition/esql_dataview_transition_modal.tsx @@ -57,7 +57,7 @@ export default function ESQLToDataViewTransitionModal({ {i18n.translate('discover.esqlToDataviewTransitionModalBody', { defaultMessage: - 'Switching data views removes the current ES|QL query. Save this search to avoid losing work.', + 'Switching data views removes the current ES|QL query. Save this session to avoid losing work.', })} diff --git a/src/plugins/discover/public/application/main/components/top_nav/get_top_nav_badges.tsx b/src/plugins/discover/public/application/main/components/top_nav/get_top_nav_badges.tsx index 13544f7f28de..9d6a3c8a9912 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/get_top_nav_badges.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/get_top_nav_badges.tsx @@ -71,7 +71,7 @@ export const getTopNavBadges = ({ getManagedContentBadge( i18n.translate('discover.topNav.managedContentLabel', { defaultMessage: - 'This saved search is managed by Elastic. Changes here must be saved to a new saved search.', + 'This Discover session is managed by Elastic. Changes here must be saved to a new Discover session.', }) ) ); diff --git a/src/plugins/discover/public/application/main/components/top_nav/on_save_search.tsx b/src/plugins/discover/public/application/main/components/top_nav/on_save_search.tsx index 63997c0d7b97..f1a2eff160db 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/on_save_search.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/on_save_search.tsx @@ -35,7 +35,7 @@ async function saveDataSource({ if (id) { services.toastNotifications.addSuccess({ title: i18n.translate('discover.notifications.savedSearchTitle', { - defaultMessage: `Search ''{savedSearchTitle}'' was saved`, + defaultMessage: `Discover session ''{savedSearchTitle}'' was saved`, values: { savedSearchTitle: savedSearch.title, }, @@ -56,7 +56,7 @@ async function saveDataSource({ function onError(error: Error) { services.toastNotifications.addDanger({ title: i18n.translate('discover.notifications.notSavedSearchTitle', { - defaultMessage: `Search ''{savedSearchTitle}'' was not saved.`, + defaultMessage: `Discover session ''{savedSearchTitle}'' was not saved.`, values: { savedSearchTitle: savedSearch.title, }, @@ -266,7 +266,7 @@ const SaveSearchObjectModal: React.FC<{ label={ } /> @@ -289,7 +289,7 @@ const SaveSearchObjectModal: React.FC<{ initialCopyOnSave={initialCopyOnSave} description={description} objectType={i18n.translate('discover.localMenu.saveSaveSearchObjectType', { - defaultMessage: 'search', + defaultMessage: 'Discover session', })} showDescription={true} options={options} @@ -299,7 +299,7 @@ const SaveSearchObjectModal: React.FC<{ managed ? i18n.translate('discover.localMenu.mustCopyOnSave', { defaultMessage: - 'Elastic manages this saved search. Save any changes to a new saved search.', + 'Elastic manages this Discover session. Save any changes to a new Discover session.', }) : undefined } diff --git a/src/plugins/discover/public/application/main/components/top_nav/open_search_panel.tsx b/src/plugins/discover/public/application/main/components/top_nav/open_search_panel.tsx index 7633bea3612b..bd4163a20d4d 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/open_search_panel.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/open_search_panel.tsx @@ -20,11 +20,10 @@ import { EuiFlyoutBody, EuiTitle, } from '@elastic/eui'; +import { SavedSearchType, SavedSearchTypeDisplayName } from '@kbn/saved-search-plugin/common'; import { SavedObjectFinder } from '@kbn/saved-objects-finder-plugin/public'; import { useDiscoverServices } from '../../../../hooks/use_discover_services'; -const SEARCH_OBJECT_TYPE = 'search'; - interface OpenSearchPanelProps { onClose: () => void; onOpenSavedSearch: (id: string) => void; @@ -43,7 +42,7 @@ export function OpenSearchPanel(props: OpenSearchPanelProps) {

@@ -59,15 +58,15 @@ export function OpenSearchPanel(props: OpenSearchPanelProps) { noItemsMessage={ } savedObjectMetaData={[ { - type: SEARCH_OBJECT_TYPE, + type: SavedSearchType, getIconForSavedObject: () => 'discoverApp', name: i18n.translate('discover.savedSearch.savedObjectName', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', }), }, ]} @@ -88,12 +87,12 @@ export function OpenSearchPanel(props: OpenSearchPanelProps) { onClick={props.onClose} data-test-subj="manageSearchesBtn" href={addBasePath( - `/app/management/kibana/objects?initialQuery=type:(${SEARCH_OBJECT_TYPE})` + `/app/management/kibana/objects?initialQuery=type:("${SavedSearchTypeDisplayName}")` )} > diff --git a/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.test.tsx b/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.test.tsx index a70b200a7434..3db9fb74f0ea 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.test.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.test.tsx @@ -73,25 +73,25 @@ describe('useTopNavLinks', () => { "testId": "openInspectorButton", }, Object { - "description": "New Search", + "description": "New session", "iconOnly": true, "iconType": "plus", "id": "new", - "label": "New", + "label": "New session", "run": [Function], "testId": "discoverNewButton", }, Object { - "description": "Open Saved Search", + "description": "Open session", "iconOnly": true, "iconType": "folderOpen", "id": "open", - "label": "Open", + "label": "Open session", "run": [Function], "testId": "discoverOpenButton", }, Object { - "description": "Share Search", + "description": "Share Discover session", "iconOnly": true, "iconType": "share", "id": "share", @@ -100,7 +100,7 @@ describe('useTopNavLinks', () => { "testId": "shareTopNavButton", }, Object { - "description": "Save Search", + "description": "Save session", "emphasize": true, "iconType": "save", "id": "save", @@ -149,25 +149,25 @@ describe('useTopNavLinks', () => { "testId": "openInspectorButton", }, Object { - "description": "New Search", + "description": "New session", "iconOnly": true, "iconType": "plus", "id": "new", - "label": "New", + "label": "New session", "run": [Function], "testId": "discoverNewButton", }, Object { - "description": "Open Saved Search", + "description": "Open session", "iconOnly": true, "iconType": "folderOpen", "id": "open", - "label": "Open", + "label": "Open session", "run": [Function], "testId": "discoverOpenButton", }, Object { - "description": "Share Search", + "description": "Share Discover session", "iconOnly": true, "iconType": "share", "id": "share", @@ -176,7 +176,7 @@ describe('useTopNavLinks', () => { "testId": "shareTopNavButton", }, Object { - "description": "Save Search", + "description": "Save session", "emphasize": true, "iconType": "save", "id": "save", diff --git a/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.tsx b/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.tsx index de9686711d10..608442da1408 100644 --- a/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.tsx +++ b/src/plugins/discover/public/application/main/components/top_nav/use_top_nav_links.tsx @@ -192,7 +192,7 @@ export const useTopNavLinks = ({ defaultMessage: 'Save', }), description: i18n.translate('discover.localMenu.saveSearchDescription', { - defaultMessage: 'Save Search', + defaultMessage: 'Save session', }), testId: 'discoverSaveButton', iconType: 'save', diff --git a/src/plugins/discover/public/components/saved_search_url_conflict_callout/saved_search_url_conflict_callout.ts b/src/plugins/discover/public/components/saved_search_url_conflict_callout/saved_search_url_conflict_callout.ts index 3c42d0301e6d..4a49a6cb2e07 100644 --- a/src/plugins/discover/public/components/saved_search_url_conflict_callout/saved_search_url_conflict_callout.ts +++ b/src/plugins/discover/public/components/saved_search_url_conflict_callout/saved_search_url_conflict_callout.ts @@ -29,7 +29,7 @@ export const SavedSearchURLConflictCallout = ({ if (otherObjectId) { return spaces.ui.components.getLegacyUrlConflict({ objectNoun: i18n.translate('discover.savedSearchURLConflictCallout.objectNoun', { - defaultMessage: '{savedSearch} search', + defaultMessage: `''{savedSearch}'' Discover session`, values: { savedSearch: savedSearch.title, }, diff --git a/src/plugins/discover/public/context_awareness/README.md b/src/plugins/discover/public/context_awareness/README.md index 31fa5ff9bfcd..ae42038b77aa 100644 --- a/src/plugins/discover/public/context_awareness/README.md +++ b/src/plugins/discover/public/context_awareness/README.md @@ -54,7 +54,7 @@ The context awareness framework is driven by two main supporting services called Each context level has a dedicated profile service, e.g. `RootProfileService`, which is responsible for accepting profile provider registrations and looping over each provider in order during context resolution to identify a matching profile. Each resolution call can result in only one matching profile, which is the first to return a match based on execution order. -A single `ProfilesManager` is instantiated on Discover load, or one per saved search panel in a dashboard. The profiles manager is responsible for the following: +A single `ProfilesManager` is instantiated on Discover load, or one per Discover session panel in a dashboard. The profiles manager is responsible for the following: - Managing state associated with the current Discover context. - Coordinating profile services and exposing resolution methods for each context level. diff --git a/src/plugins/discover/public/embeddable/constants.ts b/src/plugins/discover/public/embeddable/constants.ts index 313f2bbb99ed..938caa233b43 100644 --- a/src/plugins/discover/public/embeddable/constants.ts +++ b/src/plugins/discover/public/embeddable/constants.ts @@ -17,9 +17,9 @@ export const SEARCH_EMBEDDABLE_CELL_ACTIONS_TRIGGER_ID = export const SEARCH_EMBEDDABLE_CELL_ACTIONS_TRIGGER: Trigger = { id: SEARCH_EMBEDDABLE_CELL_ACTIONS_TRIGGER_ID, - title: 'Discover saved searches embeddable cell actions', + title: 'Discover session embeddable cell actions', description: - 'This trigger is used to replace the cell actions for Discover saved search embeddable grid.', + 'This trigger is used to replace the cell actions for Discover session embeddable grid.', } as const; export const DEFAULT_HEADER_ROW_HEIGHT_LINES = 3; diff --git a/src/plugins/discover/public/embeddable/get_search_embeddable_factory.tsx b/src/plugins/discover/public/embeddable/get_search_embeddable_factory.tsx index 1f97e2de6639..7c08cdc95e58 100644 --- a/src/plugins/discover/public/embeddable/get_search_embeddable_factory.tsx +++ b/src/plugins/discover/public/embeddable/get_search_embeddable_factory.tsx @@ -152,7 +152,7 @@ export const getSearchEmbeddableFactory = ({ }, getTypeDisplayName: () => i18n.translate('discover.embeddable.search.displayName', { - defaultMessage: 'search', + defaultMessage: 'Discover session', }), canLinkToLibrary: async () => { return ( diff --git a/src/plugins/discover/public/embeddable/initialize_edit_api.ts b/src/plugins/discover/public/embeddable/initialize_edit_api.ts index a99cea051962..acb489735d05 100644 --- a/src/plugins/discover/public/embeddable/initialize_edit_api.ts +++ b/src/plugins/discover/public/embeddable/initialize_edit_api.ts @@ -75,7 +75,7 @@ export function initializeEditApi< return { getTypeDisplayName: () => i18n.translate('discover.embeddable.search.displayName', { - defaultMessage: 'search', + defaultMessage: 'Discover session', }), onEdit: async () => { const appTarget = await getAppTarget(partialApi, discoverServices); diff --git a/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.test.ts b/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.test.ts index 4e4469188d0b..81f0ce8e1537 100644 --- a/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.test.ts +++ b/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.test.ts @@ -44,7 +44,7 @@ describe('useSavedSearchAliasMatchRedirect', () => { expect(spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith({ path: '#/view/aliasTargetId?_g=foo', aliasPurpose: 'savedObjectConversion', - objectNoun: 'my-title search', + objectNoun: `'my-title' Discover session`, }); }); diff --git a/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.ts b/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.ts index c4234e40612b..9bbfebe613c0 100644 --- a/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.ts +++ b/src/plugins/discover/public/hooks/saved_search_alias_match_redirect.ts @@ -35,7 +35,7 @@ export const useSavedSearchAliasMatchRedirect = ({ path: `${getSavedSearchUrl(aliasTargetId)}${history.location.search}`, aliasPurpose, objectNoun: i18n.translate('discover.savedSearchAliasMatchRedirect.objectNoun', { - defaultMessage: '{savedSearch} search', + defaultMessage: `''{savedSearch}'' Discover session`, values: { savedSearch: savedSearch.title, }, diff --git a/src/plugins/discover/public/plugin.tsx b/src/plugins/discover/public/plugin.tsx index 2529b4824610..08d6f9f6c741 100644 --- a/src/plugins/discover/public/plugin.tsx +++ b/src/plugins/discover/public/plugin.tsx @@ -429,7 +429,7 @@ export class DiscoverPlugin }, savedObjectType: SavedSearchType, savedObjectName: i18n.translate('discover.savedSearch.savedObjectName', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', }), getIconForSavedObject: () => 'discoverApp', }); diff --git a/src/plugins/discover/server/ui_settings.ts b/src/plugins/discover/server/ui_settings.ts index 03625807a838..9d2b86e57342 100644 --- a/src/plugins/discover/server/ui_settings.ts +++ b/src/plugins/discover/server/ui_settings.ts @@ -118,7 +118,7 @@ export const getUiSettings: ( description: i18n.translate('discover.advancedSettings.searchOnPageLoadText', { defaultMessage: 'Controls whether a search is executed when Discover first loads. This setting does not ' + - 'have an effect when loading a saved search.', + 'have an effect when loading a Discover session.', }), category: ['discover'], schema: schema.boolean(), @@ -129,7 +129,8 @@ export const getUiSettings: ( }), value: false, description: i18n.translate('discover.advancedSettings.docTableHideTimeColumnText', { - defaultMessage: "Hide the 'Time' column in Discover and in all Saved Searches on Dashboards.", + defaultMessage: + "Hide the 'Time' column in Discover and in all Discover session panels on Dashboards.", }), category: ['discover'], schema: schema.boolean(), diff --git a/src/plugins/embeddable/public/index.ts b/src/plugins/embeddable/public/index.ts index c3bb2a796b28..c5de8a9d7631 100644 --- a/src/plugins/embeddable/public/index.ts +++ b/src/plugins/embeddable/public/index.ts @@ -93,9 +93,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new EmbeddablePublicPlugin(initializerContext); } -export { - embeddableInputToSubject, - embeddableOutputToSubject, -} from './lib/embeddables/compatibility/embeddable_compatibility_utils'; - export { COMMON_EMBEDDABLE_GROUPING } from './lib/embeddables/common/constants'; diff --git a/src/plugins/embeddable/public/lib/embeddables/compatibility/embeddable_compatibility_utils.ts b/src/plugins/embeddable/public/lib/embeddables/compatibility/embeddable_compatibility_utils.ts deleted file mode 100644 index 6512d28d6bcf..000000000000 --- a/src/plugins/embeddable/public/lib/embeddables/compatibility/embeddable_compatibility_utils.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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { ViewMode } from '@kbn/presentation-publishing'; -import deepEqual from 'fast-deep-equal'; -import { BehaviorSubject, distinctUntilKeyChanged, map, Subscription } from 'rxjs'; -import { EmbeddableInput, EmbeddableOutput, IEmbeddable } from '../..'; -import { ViewMode as LegacyViewMode } from '../../types'; -import { CommonLegacyEmbeddable } from './legacy_embeddable_to_api'; - -export const embeddableInputToSubject = < - ValueType extends unknown = unknown, - LegacyInput extends EmbeddableInput = EmbeddableInput ->( - subscription: Subscription, - embeddable: IEmbeddable, - key: keyof LegacyInput, - useExplicitInput = false -) => { - const subject = new BehaviorSubject( - embeddable.getExplicitInput()?.[key] as ValueType - ); - subscription.add( - embeddable - .getInput$() - .pipe( - distinctUntilKeyChanged(key, (prev, current) => { - return deepEqual(prev, current); - }) - ) - .subscribe(() => subject.next(embeddable.getInput()?.[key] as ValueType)) - ); - return subject; -}; - -export const embeddableOutputToSubject = < - ValueType extends unknown = unknown, - LegacyOutput extends EmbeddableOutput = EmbeddableOutput ->( - subscription: Subscription, - embeddable: IEmbeddable, - key: keyof LegacyOutput -) => { - const subject = new BehaviorSubject( - embeddable.getOutput()[key] as ValueType - ); - subscription.add( - embeddable - .getOutput$() - .pipe(distinctUntilKeyChanged(key)) - .subscribe(() => subject.next(embeddable.getOutput()[key] as ValueType)) - ); - return subject; -}; - -export const mapLegacyViewModeToViewMode = (legacyViewMode?: LegacyViewMode): ViewMode => { - if (!legacyViewMode) return 'view'; - switch (legacyViewMode) { - case LegacyViewMode.VIEW: { - return 'view'; - } - case LegacyViewMode.EDIT: { - return 'edit'; - } - case LegacyViewMode.PREVIEW: { - return 'preview'; - } - case LegacyViewMode.PRINT: { - return 'print'; - } - default: { - return 'view'; - } - } -}; - -export const viewModeToSubject = ( - subscription: Subscription, - embeddable: CommonLegacyEmbeddable -) => { - const subject = new BehaviorSubject( - mapLegacyViewModeToViewMode(embeddable.getInput().viewMode) - ); - subscription.add( - embeddable - .getInput$() - .pipe( - distinctUntilKeyChanged('viewMode'), - map(({ viewMode }) => mapLegacyViewModeToViewMode(viewMode)) - ) - .subscribe((viewMode: ViewMode) => subject.next(viewMode)) - ); - return subject; -}; diff --git a/src/plugins/embeddable/public/lib/embeddables/compatibility/legacy_embeddable_to_api.ts b/src/plugins/embeddable/public/lib/embeddables/compatibility/legacy_embeddable_to_api.ts deleted file mode 100644 index 56fe9b82d1b2..000000000000 --- a/src/plugins/embeddable/public/lib/embeddables/compatibility/legacy_embeddable_to_api.ts +++ /dev/null @@ -1,302 +0,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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". - */ - -import { DataView } from '@kbn/data-views-plugin/common'; -import { - AggregateQuery, - compareFilters, - COMPARE_ALL_OPTIONS, - Filter, - Query, - TimeRange, -} from '@kbn/es-query'; -import type { ErrorLike } from '@kbn/expressions-plugin/common'; -import { i18n } from '@kbn/i18n'; -import { PhaseEvent, PhaseEventType } from '@kbn/presentation-publishing'; -import deepEqual from 'fast-deep-equal'; -import { isNil } from 'lodash'; -import { - BehaviorSubject, - map, - Subscription, - distinct, - combineLatest, - distinctUntilChanged, -} from 'rxjs'; -import { embeddableStart } from '../../../kibana_services'; -import { isFilterableEmbeddable } from '../../filterable_embeddable'; -import { - EmbeddableInput, - EmbeddableOutput, - IEmbeddable, - LegacyEmbeddableAPI, -} from '../i_embeddable'; -import { - embeddableInputToSubject, - embeddableOutputToSubject, - viewModeToSubject, -} from './embeddable_compatibility_utils'; - -export type CommonLegacyInput = EmbeddableInput & { savedObjectId?: string; timeRange: TimeRange }; -export type CommonLegacyOutput = EmbeddableOutput & { indexPatterns: DataView[] }; -export type CommonLegacyEmbeddable = IEmbeddable; - -type VisualizeEmbeddable = IEmbeddable<{ id: string }, EmbeddableOutput & { visTypeName: string }>; -function isVisualizeEmbeddable( - embeddable: IEmbeddable | VisualizeEmbeddable -): embeddable is VisualizeEmbeddable { - return embeddable.type === 'visualization'; -} - -const getEventStatus = (output: EmbeddableOutput): PhaseEventType => { - if (!isNil(output.error)) { - return 'error'; - } else if (output.rendered === true) { - return 'rendered'; - } else if (output.loading === false) { - return 'loaded'; - } else { - return 'loading'; - } -}; - -export const legacyEmbeddableToApi = ( - embeddable: CommonLegacyEmbeddable -): { api: Omit; destroyAPI: () => void } => { - const subscriptions = new Subscription(); - - /** - * Shortcuts for creating publishing subjects from the input and output subjects - */ - const inputKeyToSubject = ( - key: keyof CommonLegacyInput, - useExplicitInput?: boolean - ) => - embeddableInputToSubject( - subscriptions, - embeddable, - key, - useExplicitInput - ); - const outputKeyToSubject = (key: keyof CommonLegacyOutput) => - embeddableOutputToSubject(subscriptions, embeddable, key); - - /** - * Support editing of legacy embeddables - */ - const onEdit = () => { - throw new Error('Edit legacy embeddable not supported'); - }; - const getTypeDisplayName = () => - embeddableStart.getEmbeddableFactory(embeddable.type)?.getDisplayName() ?? - i18n.translate('embeddableApi.compatibility.defaultTypeDisplayName', { - defaultMessage: 'chart', - }); - const isEditingEnabled = () => false; - - /** - * Performance tracking - */ - const phase$ = new BehaviorSubject(undefined); - - let loadingStartTime = 0; - subscriptions.add( - embeddable - .getOutput$() - .pipe( - // Map loaded event properties - map((output) => { - if (output.loading === true) { - loadingStartTime = performance.now(); - } - return { - id: embeddable.id, - status: getEventStatus(output), - error: output.error, - }; - }), - // Dedupe - distinct((output) => loadingStartTime + output.id + output.status + !!output.error), - // Map loaded event properties - map((output): PhaseEvent => { - return { - ...output, - timeToEvent: performance.now() - loadingStartTime, - }; - }) - ) - .subscribe((statusOutput) => { - phase$.next(statusOutput); - }) - ); - - /** - * Publish state for Presentation panel - */ - const viewMode = viewModeToSubject(subscriptions, embeddable); - const dataLoading = outputKeyToSubject('loading'); - - const setHidePanelTitle = (hidePanelTitle?: boolean) => - embeddable.updateInput({ hidePanelTitles: hidePanelTitle }); - const hidePanelTitle = inputKeyToSubject('hidePanelTitles'); - - const setPanelTitle = (title?: string) => embeddable.updateInput({ title }); - const panelTitle = inputKeyToSubject('title'); - - const setPanelDescription = (description?: string) => embeddable.updateInput({ description }); - const panelDescription = inputKeyToSubject('description'); - - const defaultPanelTitle = outputKeyToSubject('defaultTitle'); - const defaultPanelDescription = outputKeyToSubject('defaultDescription'); - const disabledActionIds = inputKeyToSubject('disabledActions'); - - function getSavedObjectId(input: { savedObjectId?: string }, output: { savedObjectId?: string }) { - return output.savedObjectId ?? input.savedObjectId; - } - const savedObjectId = new BehaviorSubject( - getSavedObjectId(embeddable.getInput(), embeddable.getOutput()) - ); - subscriptions.add( - combineLatest([embeddable.getInput$(), embeddable.getOutput$()]) - .pipe( - map(([input, output]) => { - return getSavedObjectId(input, output); - }), - distinctUntilChanged() - ) - .subscribe((nextSavedObjectId) => { - savedObjectId.next(nextSavedObjectId); - }) - ); - - const blockingError = new BehaviorSubject(undefined); - subscriptions.add( - embeddable.getOutput$().subscribe({ - next: (output) => blockingError.next(output.error), - error: (error) => blockingError.next(error), - }) - ); - - const uuid = embeddable.id; - const disableTriggers = embeddable.getInput().disableTriggers; - - /** - * We treat all legacy embeddable types as if they can support local unified search state, because there is no programmatic way - * to tell when given a legacy embeddable what it's input could contain. All existing actions treat these as optional - * so if the Embeddable is incapable of publishing unified search state (i.e. markdown) then it will just be ignored. - */ - const timeRange$ = inputKeyToSubject('timeRange', true); - const setTimeRange = (nextTimeRange?: TimeRange) => - embeddable.updateInput({ timeRange: nextTimeRange }); - - const filters$: BehaviorSubject = new BehaviorSubject( - undefined - ); - - const query$: BehaviorSubject = new BehaviorSubject< - Query | AggregateQuery | undefined - >(undefined); - // if this embeddable is a legacy filterable embeddable, publish changes to those filters to the panelFilters subject. - if (isFilterableEmbeddable(embeddable)) { - embeddable.untilInitializationFinished().then(() => { - filters$.next(embeddable.getFilters()); - query$.next(embeddable.getQuery()); - - subscriptions.add( - embeddable.getInput$().subscribe(() => { - if ( - !compareFilters( - embeddable.filters$.getValue() ?? [], - embeddable.getFilters(), - COMPARE_ALL_OPTIONS - ) - ) { - filters$.next(embeddable.getFilters()); - } - if (!deepEqual(embeddable.query$.getValue() ?? [], embeddable.getQuery())) { - query$.next(embeddable.getQuery()); - } - }) - ); - }); - } - - const dataViews = outputKeyToSubject('indexPatterns'); - const isCompatibleWithUnifiedSearch = () => { - const isInputControl = - isVisualizeEmbeddable(embeddable) && - (embeddable as unknown as VisualizeEmbeddable).getOutput().visTypeName === - 'input_control_vis'; - - const isMarkdown = - isVisualizeEmbeddable(embeddable) && - (embeddable as VisualizeEmbeddable).getOutput().visTypeName === 'markdown'; - - const isImage = embeddable.type === 'image'; - const isLinks = embeddable.type === 'links'; - return !isInputControl && !isMarkdown && !isImage && !isLinks; - }; - - const hasLockedHoverActions$ = new BehaviorSubject(false); - - return { - api: { - uuid, - disableTriggers: disableTriggers ?? false, - viewMode, - dataLoading, - blockingError, - - phase$, - - onEdit, - isEditingEnabled, - getTypeDisplayName, - - timeRange$, - setTimeRange, - filters$, - query$, - isCompatibleWithUnifiedSearch, - - dataViews, - disabledActionIds, - setDisabledActionIds: (ids) => disabledActionIds.next(ids), - - hasLockedHoverActions$, - lockHoverActions: (lock: boolean) => hasLockedHoverActions$.next(lock), - - panelTitle, - setPanelTitle, - defaultPanelTitle, - - hidePanelTitle, - setHidePanelTitle, - - setPanelDescription, - panelDescription, - defaultPanelDescription, - - canLinkToLibrary: async () => false, - linkToLibrary: () => { - throw new Error('Link to library not supported for legacy embeddable'); - }, - - canUnlinkFromLibrary: async () => false, - unlinkFromLibrary: () => { - throw new Error('Unlink from library not supported for legacy embeddable'); - }, - - savedObjectId, - }, - destroyAPI: () => { - subscriptions.unsubscribe(); - }, - }; -}; diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx index 40fb391400a1..f20d65de3d60 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx @@ -14,18 +14,9 @@ import { merge } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, skip } from 'rxjs'; import { RenderCompleteDispatcher } from '@kbn/kibana-utils-plugin/public'; import { Adapters } from '../types'; -import { - EmbeddableError, - EmbeddableOutput, - IEmbeddable, - LegacyEmbeddableAPI, -} from './i_embeddable'; +import { EmbeddableError, EmbeddableOutput, IEmbeddable } from './i_embeddable'; import { EmbeddableInput, ViewMode } from '../../../common/types'; import { genericEmbeddableInputIsEqual, omitGenericEmbeddableInput } from './diff_embeddable_input'; -import { - CommonLegacyEmbeddable, - legacyEmbeddableToApi, -} from './compatibility/legacy_embeddable_to_api'; function getPanelTitle(input: EmbeddableInput, output: EmbeddableOutput) { if (input.hidePanelTitles) return ''; @@ -96,86 +87,12 @@ export abstract class Embeddable< ) .subscribe((title) => this.renderComplete.setTitle(title)); - const { api, destroyAPI } = legacyEmbeddableToApi(this as unknown as CommonLegacyEmbeddable); - this.destroyAPI = destroyAPI; - ({ - uuid: this.uuid, - disableTriggers: this.disableTriggers, - onEdit: this.onEdit, - viewMode: this.viewMode, - dataViews: this.dataViews, - panelTitle: this.panelTitle, - query$: this.query$, - dataLoading: this.dataLoading, - filters$: this.filters$, - blockingError: this.blockingError, - phase$: this.phase$, - setPanelTitle: this.setPanelTitle, - linkToLibrary: this.linkToLibrary, - hidePanelTitle: this.hidePanelTitle, - timeRange$: this.timeRange$, - isEditingEnabled: this.isEditingEnabled, - panelDescription: this.panelDescription, - defaultPanelDescription: this.defaultPanelDescription, - canLinkToLibrary: this.canLinkToLibrary, - disabledActionIds: this.disabledActionIds, - setDisabledActionIds: this.setDisabledActionIds, - unlinkFromLibrary: this.unlinkFromLibrary, - setHidePanelTitle: this.setHidePanelTitle, - defaultPanelTitle: this.defaultPanelTitle, - setTimeRange: this.setTimeRange, - getTypeDisplayName: this.getTypeDisplayName, - setPanelDescription: this.setPanelDescription, - canUnlinkFromLibrary: this.canUnlinkFromLibrary, - isCompatibleWithUnifiedSearch: this.isCompatibleWithUnifiedSearch, - savedObjectId: this.savedObjectId, - hasLockedHoverActions$: this.hasLockedHoverActions$, - lockHoverActions: this.lockHoverActions, - } = api); - setTimeout(() => { // after the constructor has finished, we initialize this embeddable if it isn't delayed if (!this.deferEmbeddableLoad) this.initializationFinished.complete(); }, 0); } - /** - * Assign compatibility API directly to the Embeddable instance. - */ - private destroyAPI; - public uuid: LegacyEmbeddableAPI['uuid']; - public disableTriggers: LegacyEmbeddableAPI['disableTriggers']; - public onEdit: LegacyEmbeddableAPI['onEdit']; - public viewMode: LegacyEmbeddableAPI['viewMode']; - public dataViews: LegacyEmbeddableAPI['dataViews']; - public query$: LegacyEmbeddableAPI['query$']; - public panelTitle: LegacyEmbeddableAPI['panelTitle']; - public dataLoading: LegacyEmbeddableAPI['dataLoading']; - public filters$: LegacyEmbeddableAPI['filters$']; - public phase$: LegacyEmbeddableAPI['phase$']; - public linkToLibrary: LegacyEmbeddableAPI['linkToLibrary']; - public blockingError: LegacyEmbeddableAPI['blockingError']; - public setPanelTitle: LegacyEmbeddableAPI['setPanelTitle']; - public timeRange$: LegacyEmbeddableAPI['timeRange$']; - public hidePanelTitle: LegacyEmbeddableAPI['hidePanelTitle']; - public isEditingEnabled: LegacyEmbeddableAPI['isEditingEnabled']; - public canLinkToLibrary: LegacyEmbeddableAPI['canLinkToLibrary']; - public panelDescription: LegacyEmbeddableAPI['panelDescription']; - public defaultPanelDescription: LegacyEmbeddableAPI['defaultPanelDescription']; - public disabledActionIds: LegacyEmbeddableAPI['disabledActionIds']; - public setDisabledActionIds: LegacyEmbeddableAPI['setDisabledActionIds']; - public unlinkFromLibrary: LegacyEmbeddableAPI['unlinkFromLibrary']; - public setTimeRange: LegacyEmbeddableAPI['setTimeRange']; - public defaultPanelTitle: LegacyEmbeddableAPI['defaultPanelTitle']; - public setHidePanelTitle: LegacyEmbeddableAPI['setHidePanelTitle']; - public getTypeDisplayName: LegacyEmbeddableAPI['getTypeDisplayName']; - public setPanelDescription: LegacyEmbeddableAPI['setPanelDescription']; - public canUnlinkFromLibrary: LegacyEmbeddableAPI['canUnlinkFromLibrary']; - public isCompatibleWithUnifiedSearch: LegacyEmbeddableAPI['isCompatibleWithUnifiedSearch']; - public savedObjectId: LegacyEmbeddableAPI['savedObjectId']; - public hasLockedHoverActions$: LegacyEmbeddableAPI['hasLockedHoverActions$']; - public lockHoverActions: LegacyEmbeddableAPI['lockHoverActions']; - public async getEditHref(): Promise { return this.getOutput().editUrl ?? undefined; } @@ -290,7 +207,6 @@ export abstract class Embeddable< this.inputSubject.complete(); this.outputSubject.complete(); - this.destroyAPI(); return; } diff --git a/src/plugins/embeddable/public/lib/embeddables/error_embeddable.tsx b/src/plugins/embeddable/public/lib/embeddables/error_embeddable.tsx index ffb5c197a4bc..b508d5aeb214 100644 --- a/src/plugins/embeddable/public/lib/embeddables/error_embeddable.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/error_embeddable.tsx @@ -32,6 +32,14 @@ export class ErrorEmbeddable extends Embeddable; + return ( + + ); } } diff --git a/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts b/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts index e1dbc3db2236..8cac11a075d1 100644 --- a/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts +++ b/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts @@ -8,55 +8,13 @@ */ import { ErrorLike } from '@kbn/expressions-plugin/common'; -import { - HasEditCapabilities, - HasType, - HasDisableTriggers, - PublishesBlockingError, - PublishesDataLoading, - PublishesDataViews, - PublishesDisabledActionIds, - PublishesUnifiedSearch, - HasUniqueId, - PublishesViewMode, - PublishesWritablePanelDescription, - PublishesWritablePanelTitle, - PublishesPhaseEvents, - PublishesSavedObjectId, - HasLegacyLibraryTransforms, - CanLockHoverActions, -} from '@kbn/presentation-publishing'; import { Observable } from 'rxjs'; import { EmbeddableInput } from '../../../common/types'; -import { EmbeddableHasTimeRange } from '../filterable_embeddable/types'; -import { HasInspectorAdapters } from '../inspector'; import { Adapters } from '../types'; export type EmbeddableError = ErrorLike; export type { EmbeddableInput }; -/** - * Types for compatibility between the legacy Embeddable system and the new system - */ -export type LegacyEmbeddableAPI = HasType & - HasUniqueId & - HasDisableTriggers & - PublishesPhaseEvents & - PublishesViewMode & - PublishesDataViews & - HasEditCapabilities & - PublishesDataLoading & - HasInspectorAdapters & - PublishesBlockingError & - PublishesUnifiedSearch & - PublishesDisabledActionIds & - PublishesWritablePanelTitle & - PublishesWritablePanelDescription & - Partial & - EmbeddableHasTimeRange & - PublishesSavedObjectId & - CanLockHoverActions; - export interface EmbeddableOutput { // Whether the embeddable is actively loading. loading?: boolean; @@ -83,7 +41,7 @@ export interface IEmbeddable< I extends EmbeddableInput = EmbeddableInput, O extends EmbeddableOutput = EmbeddableOutput, N = any -> extends LegacyEmbeddableAPI { +> { /** * The type of embeddable, this is what will be used to take a serialized * embeddable and find the correct factory for which to create an instance of it. diff --git a/src/plugins/embeddable/tsconfig.json b/src/plugins/embeddable/tsconfig.json index bf97096d1484..249612d6d0e4 100644 --- a/src/plugins/embeddable/tsconfig.json +++ b/src/plugins/embeddable/tsconfig.json @@ -19,7 +19,6 @@ "@kbn/saved-objects-finder-plugin", "@kbn/usage-collection-plugin", "@kbn/content-management-plugin", - "@kbn/data-views-plugin", "@kbn/presentation-panel-plugin", "@kbn/presentation-publishing", "@kbn/presentation-containers", diff --git a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.test.ts b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.test.ts index ab264d6ff1d1..a9463ca5083f 100644 --- a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.test.ts +++ b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.test.ts @@ -17,7 +17,7 @@ import { const DASHBOARD_FEATURE: FeatureCatalogueEntry = { id: 'dashboard', title: 'Dashboard', - description: 'Display and share a collection of visualizations and saved searches.', + description: 'Display and share a collection of visualizations and search results.', icon: 'dashboardApp', path: `/app/kibana#dashboard`, showOnHomePage: true, diff --git a/src/plugins/inspector/README.md b/src/plugins/inspector/README.md index 99984b53065a..f9eace25a25c 100644 --- a/src/plugins/inspector/README.md +++ b/src/plugins/inspector/README.md @@ -14,7 +14,7 @@ a specific view is available depends on the used adapters. ## Inspector Adapters Since the Inspector panel itself is not tied to a specific type of elements (visualizations, -saved searches, etc.), everything you need to open the inspector is a collection +Discover sessions, etc.), everything you need to open the inspector is a collection of so called inspector adapters. A single adapter can be any type of JavaScript class. Most likely an adapter offers some kind of logging capabilities for the element, that diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/__snapshots__/not_found_errors.test.tsx.snap b/src/plugins/saved_objects_management/public/management_section/object_view/components/__snapshots__/not_found_errors.test.tsx.snap index 0c5045a1c866..6e96c51be7be 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/__snapshots__/not_found_errors.test.tsx.snap +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/__snapshots__/not_found_errors.test.tsx.snap @@ -124,7 +124,7 @@ exports[`NotFoundErrors component renders correctly for search type 1`] = ` class="euiText emotion-euiText-s-euiTextColor-default" >
- The saved search associated with this object no longer exists. + The Discover session associated with this object no longer exists.
If you know what this error means, you can use the diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.test.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.test.tsx index 41919c9172e5..d1d53c0807ba 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.test.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.test.tsx @@ -26,7 +26,7 @@ describe('NotFoundErrors component', () => { const callOut = mounted.find('EuiCallOut'); expect(callOut.render()).toMatchSnapshot(); expect(mounted.text()).toMatchInlineSnapshot( - `"There is a problem with this saved objectThe saved search associated with this object no longer exists.If you know what this error means, you can use the Saved objects APIs(external, opens in a new tab or window) to fix it — otherwise click the delete button above."` + `"There is a problem with this saved objectThe Discover session associated with this object no longer exists.If you know what this error means, you can use the Saved objects APIs(external, opens in a new tab or window) to fix it — otherwise click the delete button above."` ); }); diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.tsx index e89762bd2105..ddee0bb9ee38 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/not_found_errors.tsx @@ -32,7 +32,7 @@ export const NotFoundErrors = ({ type, docLinks }: NotFoundErrors) => { return ( ); case 'index-pattern': diff --git a/src/plugins/saved_search/README.md b/src/plugins/saved_search/README.md index d2234f04494a..cf2762c23d23 100644 --- a/src/plugins/saved_search/README.md +++ b/src/plugins/saved_search/README.md @@ -1,3 +1,4 @@ # Saved search Contains the saved search saved object definition and helpers. +This object is created when a user saves their current session in the Discover app. diff --git a/src/plugins/saved_search/common/constants.ts b/src/plugins/saved_search/common/constants.ts index f30466d22096..cc5fdcebc6da 100644 --- a/src/plugins/saved_search/common/constants.ts +++ b/src/plugins/saved_search/common/constants.ts @@ -8,6 +8,8 @@ */ export const SavedSearchType = 'search'; +// While the legacy SO name has to stay "search" the display name can be customized. +export const SavedSearchTypeDisplayName = 'discover session'; // visible on Saved Objects page export const LATEST_VERSION = 1; diff --git a/src/plugins/saved_search/common/index.ts b/src/plugins/saved_search/common/index.ts index 1900a7e90d16..c29caaf9bcde 100644 --- a/src/plugins/saved_search/common/index.ts +++ b/src/plugins/saved_search/common/index.ts @@ -25,6 +25,7 @@ export enum VIEW_MODE { export { SavedSearchType, + SavedSearchTypeDisplayName, LATEST_VERSION, MIN_SAVED_SEARCH_SAMPLE_SIZE, MAX_SAVED_SEARCH_SAMPLE_SIZE, diff --git a/src/plugins/saved_search/public/plugin.ts b/src/plugins/saved_search/public/plugin.ts index 5570e0fc8d5a..17132a1a7a41 100644 --- a/src/plugins/saved_search/public/plugin.ts +++ b/src/plugins/saved_search/public/plugin.ts @@ -102,7 +102,7 @@ export class SavedSearchPublicPlugin latest: LATEST_VERSION, }, name: i18n.translate('savedSearch.contentManagementType', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', }), }); diff --git a/src/plugins/saved_search/public/services/saved_searches/check_for_duplicate_title.ts b/src/plugins/saved_search/public/services/saved_searches/check_for_duplicate_title.ts index 0efc945a867e..6eb364afec12 100644 --- a/src/plugins/saved_search/public/services/saved_searches/check_for_duplicate_title.ts +++ b/src/plugins/saved_search/public/services/saved_searches/check_for_duplicate_title.ts @@ -54,7 +54,7 @@ export const checkForDuplicateTitle = async ({ (await hasDuplicatedTitle(title, contentManagement)) ) { onTitleDuplicate(); - return Promise.reject(new Error(`Saved search title already exists: ${title}`)); + return Promise.reject(new Error(`Saved Discover session title already exists: ${title}`)); } return; diff --git a/src/plugins/saved_search/server/saved_objects/search.ts b/src/plugins/saved_search/server/saved_objects/search.ts index 153d95c6d7cb..90dbd6fbe620 100644 --- a/src/plugins/saved_search/server/saved_objects/search.ts +++ b/src/plugins/saved_search/server/saved_objects/search.ts @@ -11,6 +11,7 @@ import { ANALYTICS_SAVED_OBJECT_INDEX } from '@kbn/core-saved-objects-server'; import { SavedObjectsType } from '@kbn/core/server'; import { MigrateFunctionsObject } from '@kbn/kibana-utils-plugin/common'; import { getAllMigrations } from './search_migrations'; +import { SavedSearchTypeDisplayName } from '../../common/constants'; import { SCHEMA_SEARCH_V8_8_0, SCHEMA_SEARCH_MODEL_VERSION_1, @@ -32,6 +33,7 @@ export function getSavedSearchObjectType( management: { icon: 'discoverApp', defaultSearchField: 'title', + displayName: SavedSearchTypeDisplayName, importableAndExportable: true, getTitle(obj) { return obj.attributes.title; diff --git a/src/plugins/share/public/components/tabs/embed/embed_content.test.tsx b/src/plugins/share/public/components/tabs/embed/embed_content.test.tsx index ee9fdf01588d..edbb9ebb4799 100644 --- a/src/plugins/share/public/components/tabs/embed/embed_content.test.tsx +++ b/src/plugins/share/public/components/tabs/embed/embed_content.test.tsx @@ -18,12 +18,7 @@ describe('Share modal embed content tab', () => { beforeEach(() => { component = mountWithIntl( - jest.fn()} - shareableUrl="/home#/" - /> + ); }); diff --git a/src/plugins/share/public/components/tabs/embed/embed_content.tsx b/src/plugins/share/public/components/tabs/embed/embed_content.tsx index 5a9163097c8d..a3bc6048e64e 100644 --- a/src/plugins/share/public/components/tabs/embed/embed_content.tsx +++ b/src/plugins/share/public/components/tabs/embed/embed_content.tsx @@ -34,7 +34,6 @@ type EmbedProps = Pick< | 'objectType' | 'isDirty' > & { - setIsNotSaved: () => void; objectConfig?: ShareContextObjectTypeConfig; }; @@ -55,7 +54,6 @@ export const EmbedContent = ({ shareableUrl, objectType, objectConfig = {}, - setIsNotSaved, isDirty, }: EmbedProps) => { const isMounted = useMountedState(); @@ -67,10 +65,6 @@ export const EmbedContent = ({ const [anonymousAccessParameters] = useState(null); const [usePublicUrl] = useState(false); - useEffect(() => { - if (objectType !== 'dashboard') setIsNotSaved(); - }, [url, setIsNotSaved, objectType]); - const makeUrlEmbeddable = useCallback((tempUrl: string): string => { const embedParam = '?embed=true'; const urlHasQueryString = tempUrl.indexOf('?') !== -1; diff --git a/src/plugins/share/public/components/tabs/embed/index.tsx b/src/plugins/share/public/components/tabs/embed/index.tsx index 44d61833268c..3c74ce3fe0b1 100644 --- a/src/plugins/share/public/components/tabs/embed/index.tsx +++ b/src/plugins/share/public/components/tabs/embed/index.tsx @@ -8,35 +8,13 @@ */ import { i18n } from '@kbn/i18n'; -import React, { useCallback } from 'react'; +import React from 'react'; import { type IModalTabDeclaration } from '@kbn/shared-ux-tabbed-modal'; import { EmbedContent } from './embed_content'; import { useShareTabsContext } from '../../context'; -const EMBED_TAB_ACTIONS = { - SET_EMBED_URL: 'SET_EMBED_URL', - SET_IS_NOT_SAVED: 'SET_IS_NOT_SAVED', -}; - type IEmbedTab = IModalTabDeclaration<{ url: string; isNotSaved: boolean }>; -const embedTabReducer: IEmbedTab['reducer'] = (state = { url: '', isNotSaved: false }, action) => { - switch (action.type) { - case EMBED_TAB_ACTIONS.SET_IS_NOT_SAVED: - return { - ...state, - isNotSaved: action.payload, - }; - case EMBED_TAB_ACTIONS.SET_IS_NOT_SAVED: - return { - ...state, - isNotSaved: action.payload, - }; - default: - return state; - } -}; - const EmbedTabContent: NonNullable = ({ state, dispatch }) => { const { embedUrlParamExtensions, @@ -47,13 +25,6 @@ const EmbedTabContent: NonNullable = ({ state, dispatch }) isDirty, } = useShareTabsContext()!; - const setIsNotSaved = useCallback(() => { - dispatch({ - type: EMBED_TAB_ACTIONS.SET_IS_NOT_SAVED, - payload: objectType === 'dashboard' ? isDirty : false, - }); - }, [dispatch, objectType, isDirty]); - return ( = ({ state, dispatch }) shareableUrl, objectType, objectConfig: objectTypeMeta?.config?.embed, - isNotSaved: state?.isNotSaved, - setIsNotSaved, isDirty, }} /> @@ -75,6 +44,5 @@ export const embedTab: IEmbedTab = { name: i18n.translate('share.contextMenu.embedCodeTab', { defaultMessage: 'Embed', }), - reducer: embedTabReducer, content: EmbedTabContent, }; diff --git a/src/plugins/unified_doc_viewer/public/components/doc_viewer_flyout/use_flyout_a11y.tsx b/src/plugins/unified_doc_viewer/public/components/doc_viewer_flyout/use_flyout_a11y.tsx index 84c47cc4bd06..18cc98fb94b8 100644 --- a/src/plugins/unified_doc_viewer/public/components/doc_viewer_flyout/use_flyout_a11y.tsx +++ b/src/plugins/unified_doc_viewer/public/components/doc_viewer_flyout/use_flyout_a11y.tsx @@ -37,7 +37,7 @@ export const useFlyoutA11y = ({ isXlScreen }: { isXlScreen: boolean }) => { a11yProps: { ref: setFlyoutEl, role: isXlScreen ? 'dialog' : undefined, - tabindex: isXlScreen ? 0 : undefined, + tabIndex: isXlScreen ? 0 : undefined, 'aria-describedby': isXlScreen ? descriptionId : undefined, 'data-no-focus-lock': isXlScreen || undefined, }, diff --git a/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx b/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx index b83a3330cce2..41199116837c 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx @@ -63,7 +63,7 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) { const linkButtonAriaLabel = i18n.translate( 'visDefaultEditor.sidebar.savedSearch.linkButtonAriaLabel', { - defaultMessage: 'Link to saved search. Click to learn more or break link.', + defaultMessage: 'Link to Discover session. Click to learn more or break link.', } ); @@ -82,7 +82,7 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) {

@@ -134,7 +134,7 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) {

@@ -147,7 +147,7 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) { >

diff --git a/src/plugins/visualizations/public/visualize_app/utils/use/use_linked_search_updates.ts b/src/plugins/visualizations/public/visualize_app/utils/use/use_linked_search_updates.ts index 9a5ade9c4c26..ab2a51b2beef 100644 --- a/src/plugins/visualizations/public/visualize_app/utils/use/use_linked_search_updates.ts +++ b/src/plugins/visualizations/public/visualize_app/utils/use/use_linked_search_updates.ts @@ -48,7 +48,7 @@ export const useLinkedSearchUpdates = ( if (showToast) { services.toastNotifications.addSuccess( i18n.translate('visualizations.linkedToSearch.unlinkSuccessNotificationText', { - defaultMessage: `Unlinked from saved search ''{searchTitle}''`, + defaultMessage: `Unlinked from Discover session ''{searchTitle}''`, values: { searchTitle: savedSearch.title, }, diff --git a/src/plugins/visualizations/public/wizard/search_selection/search_selection.tsx b/src/plugins/visualizations/public/wizard/search_selection/search_selection.tsx index 62d775dbdc07..e0647737acb8 100644 --- a/src/plugins/visualizations/public/wizard/search_selection/search_selection.tsx +++ b/src/plugins/visualizations/public/wizard/search_selection/search_selection.tsx @@ -55,17 +55,17 @@ export class SearchSelection extends React.Component { noItemsMessage={i18n.translate( 'visualizations.newVisWizard.searchSelection.notFoundLabel', { - defaultMessage: 'No matching indices or saved searches found.', + defaultMessage: 'No matching indices or Discover sessions found.', } )} savedObjectMetaData={[ { type: 'search', - getIconForSavedObject: () => 'search', + getIconForSavedObject: () => 'discoverApp', name: i18n.translate( 'visualizations.newVisWizard.searchSelection.savedObjectType.search', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', } ), // ignore the saved searches that have text-based languages queries diff --git a/tsconfig.base.json b/tsconfig.base.json index 9b760a854bb5..6e1e67c3aa14 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -1160,8 +1160,8 @@ "@kbn/lint-packages-cli/*": ["packages/kbn-lint-packages-cli/*"], "@kbn/lint-ts-projects-cli": ["packages/kbn-lint-ts-projects-cli"], "@kbn/lint-ts-projects-cli/*": ["packages/kbn-lint-ts-projects-cli/*"], - "@kbn/lists-plugin": ["x-pack/plugins/lists"], - "@kbn/lists-plugin/*": ["x-pack/plugins/lists/*"], + "@kbn/lists-plugin": ["x-pack/solutions/security/plugins/lists"], + "@kbn/lists-plugin/*": ["x-pack/solutions/security/plugins/lists/*"], "@kbn/llm-tasks-plugin": ["x-pack/platform/plugins/shared/ai_infra/llm_tasks"], "@kbn/llm-tasks-plugin/*": ["x-pack/platform/plugins/shared/ai_infra/llm_tasks/*"], "@kbn/locator-examples-plugin": ["examples/locator_examples"], @@ -1364,8 +1364,8 @@ "@kbn/open-telemetry-instrumented-plugin/*": ["test/common/plugins/otel_metrics/*"], "@kbn/openapi-bundler": ["packages/kbn-openapi-bundler"], "@kbn/openapi-bundler/*": ["packages/kbn-openapi-bundler/*"], - "@kbn/openapi-common": ["packages/kbn-openapi-common"], - "@kbn/openapi-common/*": ["packages/kbn-openapi-common/*"], + "@kbn/openapi-common": ["src/platform/packages/shared/kbn-openapi-common"], + "@kbn/openapi-common/*": ["src/platform/packages/shared/kbn-openapi-common/*"], "@kbn/openapi-generator": ["packages/kbn-openapi-generator"], "@kbn/openapi-generator/*": ["packages/kbn-openapi-generator/*"], "@kbn/optimizer": ["packages/kbn-optimizer"], @@ -1568,8 +1568,8 @@ "@kbn/screenshot-mode-plugin/*": ["src/plugins/screenshot_mode/*"], "@kbn/screenshotting-example-plugin": ["x-pack/examples/screenshotting_example"], "@kbn/screenshotting-example-plugin/*": ["x-pack/examples/screenshotting_example/*"], - "@kbn/screenshotting-plugin": ["x-pack/plugins/screenshotting"], - "@kbn/screenshotting-plugin/*": ["x-pack/plugins/screenshotting/*"], + "@kbn/screenshotting-plugin": ["x-pack/platform/plugins/shared/screenshotting"], + "@kbn/screenshotting-plugin/*": ["x-pack/platform/plugins/shared/screenshotting/*"], "@kbn/screenshotting-server": ["packages/kbn-screenshotting-server"], "@kbn/screenshotting-server/*": ["packages/kbn-screenshotting-server/*"], "@kbn/search-api-keys-components": ["packages/kbn-search-api-keys-components"], @@ -1656,46 +1656,46 @@ "@kbn/security-test-endpoints-plugin/*": ["x-pack/test/security_functional/plugins/test_endpoints/*"], "@kbn/security-ui-components": ["x-pack/packages/security/ui_components"], "@kbn/security-ui-components/*": ["x-pack/packages/security/ui_components/*"], - "@kbn/securitysolution-autocomplete": ["packages/kbn-securitysolution-autocomplete"], - "@kbn/securitysolution-autocomplete/*": ["packages/kbn-securitysolution-autocomplete/*"], + "@kbn/securitysolution-autocomplete": ["x-pack/solutions/security/packages/kbn-securitysolution-autocomplete"], + "@kbn/securitysolution-autocomplete/*": ["x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/*"], "@kbn/securitysolution-data-table": ["x-pack/solutions/security/packages/data_table"], "@kbn/securitysolution-data-table/*": ["x-pack/solutions/security/packages/data_table/*"], "@kbn/securitysolution-ecs": ["src/platform/packages/shared/kbn-securitysolution-ecs"], "@kbn/securitysolution-ecs/*": ["src/platform/packages/shared/kbn-securitysolution-ecs/*"], - "@kbn/securitysolution-endpoint-exceptions-common": ["packages/kbn-securitysolution-endpoint-exceptions-common"], - "@kbn/securitysolution-endpoint-exceptions-common/*": ["packages/kbn-securitysolution-endpoint-exceptions-common/*"], - "@kbn/securitysolution-es-utils": ["packages/kbn-securitysolution-es-utils"], - "@kbn/securitysolution-es-utils/*": ["packages/kbn-securitysolution-es-utils/*"], - "@kbn/securitysolution-exception-list-components": ["packages/kbn-securitysolution-exception-list-components"], - "@kbn/securitysolution-exception-list-components/*": ["packages/kbn-securitysolution-exception-list-components/*"], - "@kbn/securitysolution-exceptions-common": ["packages/kbn-securitysolution-exceptions-common"], - "@kbn/securitysolution-exceptions-common/*": ["packages/kbn-securitysolution-exceptions-common/*"], - "@kbn/securitysolution-hook-utils": ["packages/kbn-securitysolution-hook-utils"], - "@kbn/securitysolution-hook-utils/*": ["packages/kbn-securitysolution-hook-utils/*"], - "@kbn/securitysolution-io-ts-alerting-types": ["packages/kbn-securitysolution-io-ts-alerting-types"], - "@kbn/securitysolution-io-ts-alerting-types/*": ["packages/kbn-securitysolution-io-ts-alerting-types/*"], - "@kbn/securitysolution-io-ts-list-types": ["packages/kbn-securitysolution-io-ts-list-types"], - "@kbn/securitysolution-io-ts-list-types/*": ["packages/kbn-securitysolution-io-ts-list-types/*"], - "@kbn/securitysolution-io-ts-types": ["packages/kbn-securitysolution-io-ts-types"], - "@kbn/securitysolution-io-ts-types/*": ["packages/kbn-securitysolution-io-ts-types/*"], - "@kbn/securitysolution-io-ts-utils": ["packages/kbn-securitysolution-io-ts-utils"], - "@kbn/securitysolution-io-ts-utils/*": ["packages/kbn-securitysolution-io-ts-utils/*"], - "@kbn/securitysolution-list-api": ["packages/kbn-securitysolution-list-api"], - "@kbn/securitysolution-list-api/*": ["packages/kbn-securitysolution-list-api/*"], - "@kbn/securitysolution-list-constants": ["packages/kbn-securitysolution-list-constants"], - "@kbn/securitysolution-list-constants/*": ["packages/kbn-securitysolution-list-constants/*"], - "@kbn/securitysolution-list-hooks": ["packages/kbn-securitysolution-list-hooks"], - "@kbn/securitysolution-list-hooks/*": ["packages/kbn-securitysolution-list-hooks/*"], - "@kbn/securitysolution-list-utils": ["packages/kbn-securitysolution-list-utils"], - "@kbn/securitysolution-list-utils/*": ["packages/kbn-securitysolution-list-utils/*"], - "@kbn/securitysolution-lists-common": ["packages/kbn-securitysolution-lists-common"], - "@kbn/securitysolution-lists-common/*": ["packages/kbn-securitysolution-lists-common/*"], - "@kbn/securitysolution-rules": ["packages/kbn-securitysolution-rules"], - "@kbn/securitysolution-rules/*": ["packages/kbn-securitysolution-rules/*"], - "@kbn/securitysolution-t-grid": ["packages/kbn-securitysolution-t-grid"], - "@kbn/securitysolution-t-grid/*": ["packages/kbn-securitysolution-t-grid/*"], - "@kbn/securitysolution-utils": ["packages/kbn-securitysolution-utils"], - "@kbn/securitysolution-utils/*": ["packages/kbn-securitysolution-utils/*"], + "@kbn/securitysolution-endpoint-exceptions-common": ["x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common"], + "@kbn/securitysolution-endpoint-exceptions-common/*": ["x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/*"], + "@kbn/securitysolution-es-utils": ["src/platform/packages/shared/kbn-securitysolution-es-utils"], + "@kbn/securitysolution-es-utils/*": ["src/platform/packages/shared/kbn-securitysolution-es-utils/*"], + "@kbn/securitysolution-exception-list-components": ["x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components"], + "@kbn/securitysolution-exception-list-components/*": ["x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/*"], + "@kbn/securitysolution-exceptions-common": ["x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common"], + "@kbn/securitysolution-exceptions-common/*": ["x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/*"], + "@kbn/securitysolution-hook-utils": ["x-pack/solutions/security/packages/kbn-securitysolution-hook-utils"], + "@kbn/securitysolution-hook-utils/*": ["x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/*"], + "@kbn/securitysolution-io-ts-alerting-types": ["x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types"], + "@kbn/securitysolution-io-ts-alerting-types/*": ["x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/*"], + "@kbn/securitysolution-io-ts-list-types": ["x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types"], + "@kbn/securitysolution-io-ts-list-types/*": ["x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/*"], + "@kbn/securitysolution-io-ts-types": ["src/platform/packages/shared/kbn-securitysolution-io-ts-types"], + "@kbn/securitysolution-io-ts-types/*": ["src/platform/packages/shared/kbn-securitysolution-io-ts-types/*"], + "@kbn/securitysolution-io-ts-utils": ["src/platform/packages/shared/kbn-securitysolution-io-ts-utils"], + "@kbn/securitysolution-io-ts-utils/*": ["src/platform/packages/shared/kbn-securitysolution-io-ts-utils/*"], + "@kbn/securitysolution-list-api": ["x-pack/solutions/security/packages/kbn-securitysolution-list-api"], + "@kbn/securitysolution-list-api/*": ["x-pack/solutions/security/packages/kbn-securitysolution-list-api/*"], + "@kbn/securitysolution-list-constants": ["x-pack/solutions/security/packages/kbn-securitysolution-list-constants"], + "@kbn/securitysolution-list-constants/*": ["x-pack/solutions/security/packages/kbn-securitysolution-list-constants/*"], + "@kbn/securitysolution-list-hooks": ["x-pack/solutions/security/packages/kbn-securitysolution-list-hooks"], + "@kbn/securitysolution-list-hooks/*": ["x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/*"], + "@kbn/securitysolution-list-utils": ["x-pack/solutions/security/packages/kbn-securitysolution-list-utils"], + "@kbn/securitysolution-list-utils/*": ["x-pack/solutions/security/packages/kbn-securitysolution-list-utils/*"], + "@kbn/securitysolution-lists-common": ["x-pack/solutions/security/packages/kbn-securitysolution-lists-common"], + "@kbn/securitysolution-lists-common/*": ["x-pack/solutions/security/packages/kbn-securitysolution-lists-common/*"], + "@kbn/securitysolution-rules": ["src/platform/packages/shared/kbn-securitysolution-rules"], + "@kbn/securitysolution-rules/*": ["src/platform/packages/shared/kbn-securitysolution-rules/*"], + "@kbn/securitysolution-t-grid": ["x-pack/solutions/security/packages/kbn-securitysolution-t-grid"], + "@kbn/securitysolution-t-grid/*": ["x-pack/solutions/security/packages/kbn-securitysolution-t-grid/*"], + "@kbn/securitysolution-utils": ["x-pack/solutions/security/packages/kbn-securitysolution-utils"], + "@kbn/securitysolution-utils/*": ["x-pack/solutions/security/packages/kbn-securitysolution-utils/*"], "@kbn/server-http-tools": ["packages/kbn-server-http-tools"], "@kbn/server-http-tools/*": ["packages/kbn-server-http-tools/*"], "@kbn/server-route-repository": ["src/platform/packages/shared/kbn-server-route-repository"], @@ -2076,8 +2076,8 @@ "@kbn/yarn-lock-validator/*": ["packages/kbn-yarn-lock-validator/*"], "@kbn/zod": ["packages/kbn-zod"], "@kbn/zod/*": ["packages/kbn-zod/*"], - "@kbn/zod-helpers": ["packages/kbn-zod-helpers"], - "@kbn/zod-helpers/*": ["packages/kbn-zod-helpers/*"], + "@kbn/zod-helpers": ["src/platform/packages/shared/kbn-zod-helpers"], + "@kbn/zod-helpers/*": ["src/platform/packages/shared/kbn-zod-helpers/*"], // END AUTOMATED PACKAGE LISTING // Allows for importing from `kibana` package for the exported types. "@emotion/core": ["typings/@emotion"] diff --git a/versions.json b/versions.json index 126e39ed0bad..e7ca2b8539bf 100644 --- a/versions.json +++ b/versions.json @@ -19,7 +19,7 @@ "previousMajor": true }, { - "version": "8.16.2", + "version": "8.16.3", "branch": "8.16", "previousMajor": true }, diff --git a/x-pack/.gitignore b/x-pack/.gitignore index 97efbef318c9..a5ef4968bd3b 100644 --- a/x-pack/.gitignore +++ b/x-pack/.gitignore @@ -6,6 +6,7 @@ /test/functional/apps/**/reports/session /test/reporting/configs/failure_debug/ /plugins/reporting/.chromium/ +/platform/plugins/shared/screenshotting/chromium/ /plugins/screenshotting/chromium/ /plugins/reporting/.phantom/ /.aws-config.json diff --git a/x-pack/.i18nrc.json b/x-pack/.i18nrc.json index a4482fdb8c4a..c01b9ef40aed 100644 --- a/x-pack/.i18nrc.json +++ b/x-pack/.i18nrc.json @@ -75,7 +75,7 @@ "xpack.licenseApiGuard": "platform/plugins/private/license_api_guard", "xpack.licenseMgmt": "platform/plugins/shared/license_management", "xpack.licensing": "plugins/licensing", - "xpack.lists": "plugins/lists", + "xpack.lists": "solutions/security/plugins/lists", "xpack.logstash": [ "plugins/logstash" ], @@ -128,7 +128,7 @@ "platform/plugins/private/rollup" ], "xpack.runtimeFields": "platform/plugins/private/runtime_fields", - "xpack.screenshotting": "plugins/screenshotting", + "xpack.screenshotting": "platform/plugins/shared/screenshotting", "xpack.searchSharedUI": "packages/search/shared_ui", "xpack.searchHomepage": "plugins/search_homepage", "xpack.searchIndices": "plugins/search_indices", diff --git a/x-pack/packages/kbn-ai-assistant/src/chat/chat_header.tsx b/x-pack/packages/kbn-ai-assistant/src/chat/chat_header.tsx index c4b4fcba0329..2488323842a1 100644 --- a/x-pack/packages/kbn-ai-assistant/src/chat/chat_header.tsx +++ b/x-pack/packages/kbn-ai-assistant/src/chat/chat_header.tsx @@ -19,7 +19,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { css } from '@emotion/css'; -import { AssistantAvatar } from '@kbn/observability-ai-assistant-plugin/public'; +import { AssistantIcon } from '@kbn/ai-assistant-icon'; import { ChatActionsMenu } from './chat_actions_menu'; import type { UseGenAIConnectorsResult } from '../hooks/use_genai_connectors'; import { FlyoutPositionMode } from './chat_flyout'; @@ -94,7 +94,7 @@ export function ChatHeader({ {loading ? ( ) : ( - + )} diff --git a/x-pack/packages/kbn-ai-assistant/src/chat/chat_item_avatar.tsx b/x-pack/packages/kbn-ai-assistant/src/chat/chat_item_avatar.tsx index ae78d55dd43f..0c6b6bf5de04 100644 --- a/x-pack/packages/kbn-ai-assistant/src/chat/chat_item_avatar.tsx +++ b/x-pack/packages/kbn-ai-assistant/src/chat/chat_item_avatar.tsx @@ -7,10 +7,10 @@ import React from 'react'; import { UserAvatar } from '@kbn/user-profile-components'; -import { css } from '@emotion/css'; import { EuiAvatar, EuiLoadingSpinner } from '@elastic/eui'; import type { AuthenticatedUser } from '@kbn/security-plugin/common'; -import { AssistantAvatar, MessageRole } from '@kbn/observability-ai-assistant-plugin/public'; +import { MessageRole } from '@kbn/observability-ai-assistant-plugin/public'; +import { AssistantAvatar } from '@kbn/ai-assistant-icon'; interface ChatAvatarProps { currentUser?: Pick | undefined; @@ -18,13 +18,6 @@ interface ChatAvatarProps { loading: boolean; } -const assistantAvatarClassName = css` - svg { - width: 16px; - height: 16px; - } -`; - export function ChatItemAvatar({ currentUser, role, loading }: ChatAvatarProps) { const isLoading = loading || !currentUser; @@ -39,14 +32,7 @@ export function ChatItemAvatar({ currentUser, role, loading }: ChatAvatarProps) case MessageRole.Assistant: case MessageRole.Elastic: case MessageRole.Function: - return ( - - ); + return ; case MessageRole.System: return ; diff --git a/x-pack/packages/kbn-ai-assistant/src/chat/welcome_message.tsx b/x-pack/packages/kbn-ai-assistant/src/chat/welcome_message.tsx index 2ce11d16905a..0783c7f64620 100644 --- a/x-pack/packages/kbn-ai-assistant/src/chat/welcome_message.tsx +++ b/x-pack/packages/kbn-ai-assistant/src/chat/welcome_message.tsx @@ -11,6 +11,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiSpacer, useCurrentEuiBreakpoint } from '@ import type { ActionConnector } from '@kbn/triggers-actions-ui-plugin/public'; import { GenerativeAIForObservabilityConnectorFeatureId } from '@kbn/actions-plugin/common'; import { isSupportedConnectorType } from '@kbn/observability-ai-assistant-plugin/public'; +import { AssistantBeacon } from '@kbn/ai-assistant-icon'; import type { UseKnowledgeBaseResult } from '../hooks/use_knowledge_base'; import type { UseGenAIConnectorsResult } from '../hooks/use_genai_connectors'; import { Disclaimer } from './disclaimer'; @@ -78,9 +79,11 @@ export function WelcomeMessage({ gutterSize="none" className={fullHeightClassName} > + + + - ) : null} - - diff --git a/x-pack/packages/kbn-ai-assistant/tsconfig.json b/x-pack/packages/kbn-ai-assistant/tsconfig.json index 159a38f67f42..c23f92085c28 100644 --- a/x-pack/packages/kbn-ai-assistant/tsconfig.json +++ b/x-pack/packages/kbn-ai-assistant/tsconfig.json @@ -38,5 +38,6 @@ "@kbn/share-plugin", "@kbn/ai-assistant-common", "@kbn/storybook", + "@kbn/ai-assistant-icon", ] } diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/tsconfig.json b/x-pack/packages/kbn-cloud-security-posture/storybook/config/tsconfig.json deleted file mode 100644 index 1f8b2275f519..000000000000 --- a/x-pack/packages/kbn-cloud-security-posture/storybook/config/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../../../../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - "types": [ - "jest", - "node", - "@kbn/ambient-storybook-types", - ] - }, - "include": [ - "**/*.ts" - ], - "kbn_references": [ - "@kbn/storybook", - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/x-pack/platform/packages/private/ml/aiops_components/src/document_count_chart/document_count_chart.tsx b/x-pack/platform/packages/private/ml/aiops_components/src/document_count_chart/document_count_chart.tsx index 6e44f01cbbd6..5a6f45f6a6ba 100644 --- a/x-pack/platform/packages/private/ml/aiops_components/src/document_count_chart/document_count_chart.tsx +++ b/x-pack/platform/packages/private/ml/aiops_components/src/document_count_chart/document_count_chart.tsx @@ -28,6 +28,7 @@ import { getSnappedTimestamps, getSnappedWindowParameters, getWindowParametersForTrigger, + useLogRateAnalysisBarColors, type DocumentCountStatsChangePoint, type LogRateHistogramItem, type WindowParameters, @@ -198,6 +199,7 @@ export const DocumentCountChart: FC = (props) => { const { data, uiSettings, fieldFormats, charts } = dependencies; const chartBaseTheme = charts.theme.useChartsBaseTheme(); + const barColors = useLogRateAnalysisBarColors(); const xAxisFormatter = fieldFormats.deserialize({ id: 'date' }); const useLegacyTimeAxis = uiSettings.get('visualization:useLegacyTimeAxis', false); @@ -422,8 +424,10 @@ export const DocumentCountChart: FC = (props) => { const baselineBadgeMarginLeft = (mlBrushMarginLeft ?? 0) + (windowParametersAsPixels?.baselineMin ?? 0); - const barColor = barColorOverride ? [barColorOverride] : undefined; - const barHighlightColor = barHighlightColorOverride ? [barHighlightColorOverride] : ['orange']; + const barColor = barColorOverride ? [barColorOverride] : barColors.barColor; + const barHighlightColor = barHighlightColorOverride + ? [barHighlightColorOverride] + : [barColors.barHighlightColor]; return ( <> diff --git a/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.test.tsx b/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.test.tsx index 4b8191de1d87..09c118e4d262 100644 --- a/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.test.tsx +++ b/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.test.tsx @@ -10,6 +10,8 @@ import { render, renderHook } from '@testing-library/react'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; +import type { EuiThemeComputed } from '@elastic/eui'; + import type { NumericChartData, OrdinalChartData, @@ -23,6 +25,10 @@ import { import { getFieldType, getLegendText, getXScaleType, useColumnChart } from './use_column_chart'; +const euiThemeMock = { + size: { base: '16px' }, +} as EuiThemeComputed; + describe('getFieldType()', () => { it('should return the Kibana field type for a given EUI data grid schema', () => { expect(getFieldType('text')).toBe('string'); @@ -103,63 +109,81 @@ describe('isUnsupportedChartData()', () => { describe('getLegendText()', () => { it('should return the chart legend text for unsupported chart types', () => { - expect(getLegendText(validUnsupportedChartData)).toBe('Chart not supported.'); + expect(getLegendText(validUnsupportedChartData, euiThemeMock)).toBe('Chart not supported.'); }); it('should return the chart legend text for empty datasets', () => { - expect(getLegendText(validNumericChartData)).toBe('0 documents contain field.'); + expect(getLegendText(validNumericChartData, euiThemeMock)).toBe('0 documents contain field.'); }); it('should return the chart legend text for boolean chart types', () => { const { getByText } = render( <> - {getLegendText({ - cardinality: 2, - data: [ - { key: 'true', key_as_string: 'true', doc_count: 10 }, - { key: 'false', key_as_string: 'false', doc_count: 20 }, - ], - id: 'the-id', - type: 'boolean', - })} + {getLegendText( + { + cardinality: 2, + data: [ + { key: 'true', key_as_string: 'true', doc_count: 10 }, + { key: 'false', key_as_string: 'false', doc_count: 20 }, + ], + id: 'the-id', + type: 'boolean', + }, + euiThemeMock + )} ); expect(getByText('true')).toBeInTheDocument(); expect(getByText('false')).toBeInTheDocument(); }); it('should return the chart legend text for ordinal chart data with less than max categories', () => { - expect(getLegendText({ ...validOrdinalChartData, data: [{ key: 'cat', doc_count: 10 }] })).toBe( - '10 categories' - ); + expect( + getLegendText( + { ...validOrdinalChartData, data: [{ key: 'cat', doc_count: 10 }] }, + euiThemeMock + ) + ).toBe('10 categories'); }); it('should return the chart legend text for ordinal chart data with more than max categories', () => { expect( - getLegendText({ - ...validOrdinalChartData, - cardinality: 30, - data: [{ key: 'cat', doc_count: 10 }], - }) + getLegendText( + { + ...validOrdinalChartData, + cardinality: 30, + data: [{ key: 'cat', doc_count: 10 }], + }, + euiThemeMock + ) ).toBe('top 20 of 30 categories'); }); it('should return the chart legend text for numeric datasets', () => { expect( - getLegendText({ - ...validNumericChartData, - data: [{ key: 1, doc_count: 10 }], - stats: [1, 100], - }) + getLegendText( + { + ...validNumericChartData, + data: [{ key: 1, doc_count: 10 }], + stats: [1, 100], + }, + euiThemeMock + ) ).toBe('1 - 100'); expect( - getLegendText({ - ...validNumericChartData, - data: [{ key: 1, doc_count: 10 }], - stats: [100, 100], - }) + getLegendText( + { + ...validNumericChartData, + data: [{ key: 1, doc_count: 10 }], + stats: [100, 100], + }, + euiThemeMock + ) ).toBe('100'); expect( - getLegendText({ - ...validNumericChartData, - data: [{ key: 1, doc_count: 10 }], - stats: [1.2345, 6.3456], - }) + getLegendText( + { + ...validNumericChartData, + data: [{ key: 1, doc_count: 10 }], + stats: [1.2345, 6.3456], + }, + euiThemeMock + ) ).toBe('1.23 - 6.35'); }); }); diff --git a/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.tsx b/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.tsx index f0ad27d46447..9292f17069e7 100644 --- a/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.tsx +++ b/x-pack/platform/packages/private/ml/data_grid/hooks/use_column_chart.tsx @@ -12,9 +12,13 @@ import { css } from '@emotion/react'; import useObservable from 'react-use/lib/useObservable'; -import { euiPaletteColorBlind, type EuiDataGridColumn } from '@elastic/eui'; +import { + useEuiTheme, + euiPaletteColorBlind, + type EuiDataGridColumn, + type EuiThemeComputed, +} from '@elastic/eui'; -import { euiThemeVars } from '@kbn/ui-theme'; import { i18n } from '@kbn/i18n'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; @@ -29,14 +33,6 @@ import { isNumericChartData, isOrdinalChartData } from '../lib/field_histograms' import { NON_AGGREGATABLE } from '../lib/common'; import type { DataGridItem } from '../lib/types'; -const cssHistogramLegendBoolean = css({ - width: '100%', - // This was originally $euiButtonMinWidth, but that - // is no longer exported from the EUI package, - // so we're replicating it here inline. - minWidth: `calc(${euiThemeVars.euiSize} * 7)`, -}); - const cssTextAlignCenter = css({ textAlign: 'center', }); @@ -97,6 +93,7 @@ export const getFieldType = (schema: EuiDataGridColumn['schema']): KBN_FIELD_TYP type LegendText = string | JSX.Element; export const getLegendText = ( chartData: ChartData, + euiTheme: EuiThemeComputed, maxChartColumns = MAX_CHART_COLUMNS ): LegendText => { if (chartData.type === 'unsupported') { @@ -112,6 +109,14 @@ export const getLegendText = ( } if (chartData.type === 'boolean') { + const cssHistogramLegendBoolean = css({ + width: '100%', + // This was originally $euiButtonMinWidth, but that + // is no longer exported from the EUI package, + // so we're replicating it here inline. + minWidth: `calc(${euiTheme.size.base} * 7)`, + }); + return ( @@ -171,6 +176,8 @@ export const useColumnChart = ( columnType: EuiDataGridColumn, maxChartColumns?: number ): ColumnChart => { + const { euiTheme } = useEuiTheme(); + const fieldType = getFieldType(columnType.schema); const hoveredRow = useObservable(hoveredRow$); @@ -231,7 +238,7 @@ export const useColumnChart = ( return { data, - legendText: getLegendText(chartData, maxChartColumns), + legendText: getLegendText(chartData, euiTheme, maxChartColumns), xScaleType, }; }; diff --git a/x-pack/platform/packages/private/ml/data_grid/tsconfig.json b/x-pack/platform/packages/private/ml/data_grid/tsconfig.json index db1fefe7ccca..e2c0a8146855 100644 --- a/x-pack/platform/packages/private/ml/data_grid/tsconfig.json +++ b/x-pack/platform/packages/private/ml/data_grid/tsconfig.json @@ -28,7 +28,6 @@ "@kbn/ml-agg-utils", "@kbn/ml-error-utils", "@kbn/ml-data-frame-analytics-utils", - "@kbn/ui-theme", "@kbn/i18n-react", "@kbn/ml-is-populated-object", "@kbn/ml-date-picker", diff --git a/x-pack/platform/packages/private/ml/field_stats_flyout/field_stats_flyout_provider.tsx b/x-pack/platform/packages/private/ml/field_stats_flyout/field_stats_flyout_provider.tsx index 4e7a501140b0..16eb8a48798b 100644 --- a/x-pack/platform/packages/private/ml/field_stats_flyout/field_stats_flyout_provider.tsx +++ b/x-pack/platform/packages/private/ml/field_stats_flyout/field_stats_flyout_provider.tsx @@ -7,7 +7,6 @@ import type { PropsWithChildren, FC } from 'react'; import React, { useCallback, useState } from 'react'; -import type { ThemeServiceStart } from '@kbn/core-theme-browser'; import type { DataView } from '@kbn/data-plugin/common'; import type { FieldStatsServices } from '@kbn/unified-field-list/src/components/field_stats'; import type { TimeRange as TimeRangeMs } from '@kbn/ml-date-picker'; @@ -36,7 +35,6 @@ import { PopulatedFieldsCacheManager } from './populated_fields/populated_fields export type FieldStatsFlyoutProviderProps = PropsWithChildren<{ dataView: DataView; fieldStatsServices: FieldStatsServices; - theme: ThemeServiceStart; timeRangeMs?: TimeRangeMs; dslQuery?: FieldStatsProps['dslQuery']; disablePopulatedFields?: boolean; @@ -65,7 +63,6 @@ export const FieldStatsFlyoutProvider: FC = (prop const { dataView, fieldStatsServices, - theme, timeRangeMs, dslQuery, disablePopulatedFields = false, @@ -174,7 +171,6 @@ export const FieldStatsFlyoutProvider: FC = (prop fieldValue, timeRangeMs, populatedFields, - theme, }} > = (props) => { const { field, label, onButtonClick, disabled, isEmpty, hideTrigger } = props; - const theme = useFieldStatsFlyoutThemeVars(); - const themeVars = useCurrentEuiThemeVars(theme); + const { euiTheme } = useEuiTheme(); const emptyFieldMessage = isEmpty ? ' ' + @@ -100,7 +104,7 @@ export const FieldStatsInfoButton: FC = (props) => { disabled={disabled === true} size="xs" iconType="fieldStatistics" - css={{ color: isEmpty ? themeVars.euiTheme.euiColorDisabled : undefined }} + css={{ color: isEmpty ? euiTheme.colors.textDisabled : undefined }} onClick={(ev: React.MouseEvent) => { if (ev.type === 'click') { ev.currentTarget.focus(); @@ -127,12 +131,12 @@ export const FieldStatsInfoButton: FC = (props) => { {!hideTrigger ? ( diff --git a/x-pack/platform/packages/private/ml/field_stats_flyout/options_list_with_stats/option_list_popover_footer.tsx b/x-pack/platform/packages/private/ml/field_stats_flyout/options_list_with_stats/option_list_popover_footer.tsx index 0bed94223b0c..b1bdb9c3e07d 100644 --- a/x-pack/platform/packages/private/ml/field_stats_flyout/options_list_with_stats/option_list_popover_footer.tsx +++ b/x-pack/platform/packages/private/ml/field_stats_flyout/options_list_with_stats/option_list_popover_footer.tsx @@ -6,25 +6,26 @@ */ import React from 'react'; import type { FC } from 'react'; -import { EuiPopoverFooter, EuiSwitch, EuiProgress, useEuiBackgroundColor } from '@elastic/eui'; +import { EuiPopoverFooter, EuiSwitch, EuiProgress, useEuiTheme } from '@elastic/eui'; import { css } from '@emotion/react'; import { i18n } from '@kbn/i18n'; -import { euiThemeVars } from '@kbn/ui-theme'; export const OptionsListPopoverFooter: FC<{ showEmptyFields: boolean; setShowEmptyFields: (showEmptyFields: boolean) => void; isLoading?: boolean; }> = ({ showEmptyFields, setShowEmptyFields, isLoading }) => { + const { euiTheme } = useEuiTheme(); + return ( {isLoading ? ( diff --git a/x-pack/platform/packages/private/ml/field_stats_flyout/tsconfig.json b/x-pack/platform/packages/private/ml/field_stats_flyout/tsconfig.json index 33e65f0cebca..1de626e740fc 100644 --- a/x-pack/platform/packages/private/ml/field_stats_flyout/tsconfig.json +++ b/x-pack/platform/packages/private/ml/field_stats_flyout/tsconfig.json @@ -23,14 +23,11 @@ "@kbn/i18n", "@kbn/react-field", "@kbn/ml-anomaly-utils", - "@kbn/ml-kibana-theme", "@kbn/ml-data-grid", "@kbn/ml-string-hash", "@kbn/ml-is-populated-object", "@kbn/ml-query-utils", "@kbn/ml-is-defined", "@kbn/field-types", - "@kbn/ui-theme", - "@kbn/core-theme-browser", ] } diff --git a/x-pack/platform/packages/private/ml/field_stats_flyout/use_field_stats_flyout_context.ts b/x-pack/platform/packages/private/ml/field_stats_flyout/use_field_stats_flyout_context.ts index 121426352e6e..2e58dbb1361a 100644 --- a/x-pack/platform/packages/private/ml/field_stats_flyout/use_field_stats_flyout_context.ts +++ b/x-pack/platform/packages/private/ml/field_stats_flyout/use_field_stats_flyout_context.ts @@ -7,7 +7,6 @@ import { createContext, useContext } from 'react'; import type { TimeRange as TimeRangeMs } from '@kbn/ml-date-picker'; -import type { ThemeServiceStart } from '@kbn/core-theme-browser'; /** * Represents the properties for the MLJobWizardFieldStatsFlyout component. @@ -22,7 +21,6 @@ interface MLJobWizardFieldStatsFlyoutProps { fieldValue?: string | number; timeRangeMs?: TimeRangeMs; populatedFields?: Set; - theme?: ThemeServiceStart; } /** @@ -36,7 +34,6 @@ export const MLFieldStatsFlyoutContext = createContext {}, timeRangeMs: undefined, populatedFields: undefined, - theme: undefined, }); /** @@ -52,17 +49,3 @@ export function useFieldStatsFlyoutContext() { return fieldStatsFlyoutContext; } - -/** - * Retrieves the theme vars from the field stats flyout context. - * @returns The theme vars. - */ -export function useFieldStatsFlyoutThemeVars() { - const { theme } = useFieldStatsFlyoutContext(); - - if (!theme) { - throw new Error('theme must be provided in the MLFieldStatsFlyoutContext'); - } - - return theme; -} diff --git a/x-pack/platform/packages/private/ml/kibana_theme/index.ts b/x-pack/platform/packages/private/ml/kibana_theme/index.ts index 0bd52263c70f..daa5b6ad8964 100644 --- a/x-pack/platform/packages/private/ml/kibana_theme/index.ts +++ b/x-pack/platform/packages/private/ml/kibana_theme/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { useIsDarkTheme, useCurrentEuiThemeVars, type EuiThemeType } from './src/hooks'; +export { useIsDarkTheme } from './src/hooks'; diff --git a/x-pack/platform/packages/private/ml/kibana_theme/src/hooks.ts b/x-pack/platform/packages/private/ml/kibana_theme/src/hooks.ts index ed156f56f025..68aa5bb4129a 100644 --- a/x-pack/platform/packages/private/ml/kibana_theme/src/hooks.ts +++ b/x-pack/platform/packages/private/ml/kibana_theme/src/hooks.ts @@ -8,11 +8,8 @@ import { useMemo } from 'react'; import { of } from 'rxjs'; import useObservable from 'react-use/lib/useObservable'; -import { euiDarkVars as euiThemeDark, euiLightVars as euiThemeLight } from '@kbn/ui-theme'; import type { ThemeServiceStart } from '@kbn/core-theme-browser'; -export type EuiThemeType = typeof euiThemeLight | typeof euiThemeDark; - const themeDefault = { darkMode: false }; /** @@ -28,11 +25,3 @@ export function useIsDarkTheme(theme: ThemeServiceStart): boolean { return darkMode; } - -/** - * Returns an EUI theme definition based on the currently applied theme. - */ -export function useCurrentEuiThemeVars(theme: ThemeServiceStart): { euiTheme: EuiThemeType } { - const isDarkMode = useIsDarkTheme(theme); - return useMemo(() => ({ euiTheme: isDarkMode ? euiThemeDark : euiThemeLight }), [isDarkMode]); -} diff --git a/x-pack/platform/packages/private/ml/kibana_theme/tsconfig.json b/x-pack/platform/packages/private/ml/kibana_theme/tsconfig.json index 263f34ba2758..1342e03481c5 100644 --- a/x-pack/platform/packages/private/ml/kibana_theme/tsconfig.json +++ b/x-pack/platform/packages/private/ml/kibana_theme/tsconfig.json @@ -14,7 +14,6 @@ "target/**/*" ], "kbn_references": [ - "@kbn/ui-theme", "@kbn/core-theme-browser", ] } diff --git a/x-pack/platform/packages/shared/kbn-cloud-security-posture/common/schema/graph/v1.ts b/x-pack/platform/packages/shared/kbn-cloud-security-posture/common/schema/graph/v1.ts index 076c685aca5b..5b1a48cf940b 100644 --- a/x-pack/platform/packages/shared/kbn-cloud-security-posture/common/schema/graph/v1.ts +++ b/x-pack/platform/packages/shared/kbn-cloud-security-posture/common/schema/graph/v1.ts @@ -12,7 +12,9 @@ export const graphRequestSchema = schema.object({ nodesLimit: schema.maybe(schema.number()), showUnknownTarget: schema.maybe(schema.boolean()), query: schema.object({ - eventIds: schema.arrayOf(schema.string()), + originEventIds: schema.arrayOf( + schema.object({ id: schema.string(), isAlert: schema.boolean() }) + ), // TODO: use zod for range validation instead of config schema start: schema.oneOf([schema.number(), schema.string()]), end: schema.oneOf([schema.number(), schema.string()]), diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/constants.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/constants.ts index 2d915870ca12..6ae763ef4096 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/constants.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/constants.ts @@ -5,6 +5,8 @@ * 2.0. */ +import { useEuiTheme } from '@elastic/eui'; + /** Log rate analysis settings */ export const LOG_RATE_ANALYSIS_SETTINGS = { /** @@ -32,7 +34,17 @@ export const LOG_RATE_ANALYSIS_SETTINGS = { export const RANDOM_SAMPLER_SEED = 3867412; /** Highlighting color for charts */ -export const LOG_RATE_ANALYSIS_HIGHLIGHT_COLOR = 'orange'; +export const useLogRateAnalysisBarColors = () => { + const { euiTheme } = useEuiTheme(); + return { + barColor: euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis0 + : euiTheme.colors.vis.euiColorVis0, + barHighlightColor: euiTheme.flags.hasVisColorAdjustment + ? 'orange' + : euiTheme.colors.vis.euiColorVis8, + }; +}; /** */ export const EMBEDDABLE_LOG_RATE_ANALYSIS_TYPE = 'aiopsLogRateAnalysisEmbeddable' as const; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/index.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/index.ts index 15762c09684c..36041bbcca7c 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/index.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -export { LOG_RATE_ANALYSIS_HIGHLIGHT_COLOR } from './constants'; +export { useLogRateAnalysisBarColors } from './constants'; export { getLogRateAnalysisTypeForHistogram } from './get_log_rate_analysis_type_for_histogram'; export { LOG_RATE_ANALYSIS_TYPE, type LogRateAnalysisType } from './log_rate_analysis_type'; export type { LogRateHistogramItem } from './log_rate_histogram_item'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/_index.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/_index.scss deleted file mode 100644 index ecc7a2fce1fa..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/_index.scss +++ /dev/null @@ -1 +0,0 @@ -@import 'common/components/index'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/_index.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/_index.scss deleted file mode 100644 index 232cb369a1d0..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/_index.scss +++ /dev/null @@ -1,2 +0,0 @@ -@import 'stats_table/index'; -@import 'top_values/top_values'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/document_count_content/document_count_chart/document_count_chart.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/document_count_content/document_count_chart/document_count_chart.tsx index d6adf432fd57..75d000e8e8a4 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/document_count_content/document_count_chart/document_count_chart.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/document_count_content/document_count_chart/document_count_chart.tsx @@ -7,7 +7,8 @@ import type { FC } from 'react'; import React, { useCallback, useMemo } from 'react'; -import { i18n } from '@kbn/i18n'; +import moment from 'moment'; + import type { BrushEndListener, ElementClickListener, @@ -15,12 +16,13 @@ import type { XYBrushEvent, } from '@elastic/charts'; import { Axis, HistogramBarSeries, Chart, Position, ScaleType, Settings } from '@elastic/charts'; -import moment from 'moment'; +import { useEuiTheme, EuiFlexGroup, EuiLoadingSpinner, EuiFlexItem } from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; import { getTimeZone } from '@kbn/visualization-utils'; import { MULTILAYER_TIME_AXIS_STYLE } from '@kbn/charts-plugin/common'; import type { LogRateHistogramItem } from '@kbn/aiops-log-rate-analysis'; -import { EuiFlexGroup, EuiLoadingSpinner, EuiFlexItem } from '@elastic/eui'; import { useDataVisualizerKibana } from '../../../../kibana_context'; interface Props { @@ -50,6 +52,7 @@ export const DocumentCountChart: FC = ({ interval, loading, }) => { + const { euiTheme } = useEuiTheme(); const { services: { data, uiSettings, fieldFormats, charts }, } = useDataVisualizerKibana(); @@ -154,6 +157,7 @@ export const DocumentCountChart: FC = ({ yAccessors={['value']} data={adjustedChartPoints} timeZone={timeZone} + color={euiTheme.colors.vis.euiColorVis0} yNice /> diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/link_card/link_card.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/link_card/link_card.tsx index b65092514d59..501b7385fbf6 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/link_card/link_card.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/link_card/link_card.tsx @@ -9,6 +9,7 @@ import type { FC } from 'react'; import React from 'react'; import { + useEuiTheme, EuiIcon, EuiText, EuiTitle, @@ -18,7 +19,6 @@ import { EuiLink, } from '@elastic/eui'; import type { EuiIconType } from '@elastic/eui/src/components/icon/icon'; -import { useCurrentEuiTheme } from '../../hooks/use_current_eui_theme'; export interface LinkCardProps { icon: EuiIconType | string; @@ -43,7 +43,7 @@ export const LinkCard: FC = ({ isDisabled, 'data-test-subj': dataTestSubj, }) => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const linkHrefAndOnClickProps = { ...(href ? { href } : {}), @@ -67,7 +67,7 @@ export const LinkCard: FC = ({ {...linkHrefAndOnClickProps} > - + diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/multi_select_picker/multi_select_picker.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/multi_select_picker/multi_select_picker.tsx index feabb32ecadb..8c3c06ba08ce 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/multi_select_picker/multi_select_picker.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/multi_select_picker/multi_select_picker.tsx @@ -6,6 +6,7 @@ */ import { + useEuiTheme, EuiFieldSearch, EuiFilterButton, EuiFilterGroup, @@ -21,7 +22,6 @@ import React, { useEffect, useState } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; import type { SerializedStyles } from '@emotion/react'; import { css } from '@emotion/react'; -import { useCurrentEuiTheme } from '../../hooks/use_current_eui_theme'; export interface Option { name?: string | ReactNode; @@ -60,7 +60,7 @@ export const MultiSelectPicker: FC<{ postfix?: React.ReactElement; cssStyles?: MultiSelectPickerStyles; }> = ({ options, onChange, title, checkedOptions, dataTestSubj, postfix, cssStyles }) => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const [items, setItems] = useState(options); const [searchTerm, setSearchTerm] = useState(''); @@ -153,8 +153,8 @@ export const MultiSelectPicker: FC<{ flexDirection: 'row', color: item.disabled === true - ? euiTheme.euiColorDisabledText - : euiTheme.euiTextColor, + ? euiTheme.colors.textDisabled + : euiTheme.colors.textParagraph, }} data-test-subj={`${dataTestSubj}-option-${item.value}${ checked ? '-checked' : '' diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/_index.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/_index.scss deleted file mode 100644 index ccd38b8506a9..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/_index.scss +++ /dev/null @@ -1,2 +0,0 @@ -@import 'components/field_data_expanded_row/index'; -@import 'components/field_data_row/index'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_index.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_index.scss deleted file mode 100644 index fdc591a140fe..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_index.scss +++ /dev/null @@ -1 +0,0 @@ -@import 'number_content'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_number_content.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_number_content.scss deleted file mode 100644 index 1f52b0763cdd..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/_number_content.scss +++ /dev/null @@ -1,4 +0,0 @@ -.metricDistributionChartContainer { - padding-top: $euiSizeXS; - width: 100%; -} diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/boolean_content.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/boolean_content.tsx index 669c48b1db8b..6be2d5e9fa28 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/boolean_content.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/boolean_content.tsx @@ -7,20 +7,26 @@ import type { FC } from 'react'; import React, { useMemo } from 'react'; + import { EuiSpacer } from '@elastic/eui'; import { Axis, BarSeries, Chart, Settings, ScaleType, LEGACY_LIGHT_THEME } from '@elastic/charts'; import { FormattedMessage } from '@kbn/i18n-react'; import { roundToDecimalPlace } from '@kbn/ml-number-utils'; import { i18n } from '@kbn/i18n'; + import { TopValues } from '../../../top_values'; + import type { FieldDataRowProps } from '../../types/field_data_row'; -import { ExpandedRowFieldHeader } from '../expanded_row_field_header'; import { getTFPercentage } from '../../utils'; import { useDataVizChartTheme } from '../../hooks'; + +import { ExpandedRowFieldHeader } from '../expanded_row_field_header'; + import { DocumentStatsTable } from './document_stats'; import { ExpandedRowContent } from './expanded_row_content'; import { ExpandedRowPanel } from './expanded_row_panel'; +import { useBarColor } from './use_bar_color'; function getPercentLabel(value: number): string { if (value === 0) { @@ -41,6 +47,8 @@ function getFormattedValue(value: number, totalCount: number): string { const BOOLEAN_DISTRIBUTION_CHART_HEIGHT = 70; export const BooleanContent: FC = ({ config, onAddFilter }) => { + const barColor = useBarColor(); + const fieldFormat = 'fieldFormat' in config ? config.fieldFormat : undefined; const formattedPercentages = useMemo(() => getTFPercentage(config), [config]); const theme = useDataVizChartTheme(); @@ -54,7 +62,7 @@ export const BooleanContent: FC = ({ config, onAddFilter }) = diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/ip_content.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/ip_content.tsx index 6baaf8e065d1..3cd12cb78a45 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/ip_content.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/ip_content.tsx @@ -7,12 +7,18 @@ import type { FC } from 'react'; import React from 'react'; -import type { FieldDataRowProps } from '../../types/field_data_row'; + import { TopValues } from '../../../top_values'; + +import type { FieldDataRowProps } from '../../types/field_data_row'; + import { DocumentStatsTable } from './document_stats'; import { ExpandedRowContent } from './expanded_row_content'; +import { useBarColor } from './use_bar_color'; export const IpContent: FC = ({ config, onAddFilter }) => { + const barColor = useBarColor(); + const { stats } = config; if (stats === undefined) return null; const { count, sampleCount, cardinality } = stats; @@ -26,7 +32,7 @@ export const IpContent: FC = ({ config, onAddFilter }) => { )} diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/keyword_content.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/keyword_content.tsx index ddca9193db2b..e2be5c86018c 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/keyword_content.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/keyword_content.tsx @@ -7,16 +7,24 @@ import type { FC } from 'react'; import React, { useEffect, useState } from 'react'; + import type { EMSTermJoinConfig } from '@kbn/maps-plugin/public'; -import type { FieldDataRowProps } from '../../types/field_data_row'; -import { TopValues } from '../../../top_values'; + import { useDataVisualizerKibana } from '../../../../../kibana_context'; + +import { TopValues } from '../../../top_values'; + +import type { FieldDataRowProps } from '../../types/field_data_row'; + import { DocumentStatsTable } from './document_stats'; import { ExpandedRowContent } from './expanded_row_content'; import { ChoroplethMap } from './choropleth_map'; import { ErrorMessageContent } from './error_message'; +import { useBarColor } from './use_bar_color'; export const KeywordContent: FC = ({ config, onAddFilter }) => { + const barColor = useBarColor(); + const [suggestion, setSuggestion] = useState(null); const { stats, fieldName } = config; const fieldFormat = 'fieldFormat' in config ? config.fieldFormat : undefined; @@ -62,14 +70,14 @@ export const KeywordContent: FC = ({ config, onAddFilter }) = {config.stats?.sampledValues && fieldName !== undefined ? ( diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/number_content.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/number_content.tsx index 8b121660e342..db0c2270fedb 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/number_content.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_expanded_row/number_content.tsx @@ -7,20 +7,34 @@ import type { FC, ReactNode } from 'react'; import React, { useMemo } from 'react'; +import { css } from '@emotion/react'; + import type { HorizontalAlignment } from '@elastic/eui'; -import { EuiBasicTable, EuiFlexItem, EuiText, LEFT_ALIGNMENT, RIGHT_ALIGNMENT } from '@elastic/eui'; +import { + useEuiTheme, + EuiBasicTable, + EuiFlexItem, + EuiText, + LEFT_ALIGNMENT, + RIGHT_ALIGNMENT, +} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import { isDefined } from '@kbn/ml-is-defined'; -import type { FieldDataRowProps } from '../../types/field_data_row'; + +import { TopValues } from '../../../top_values'; import { kibanaFieldFormat, numberAsOrdinal } from '../../../utils'; + +import type { FieldDataRowProps } from '../../types/field_data_row'; + import { MetricDistributionChart, buildChartDataFromStats } from '../metric_distribution_chart'; -import { TopValues } from '../../../top_values'; import { ExpandedRowFieldHeader } from '../expanded_row_field_header'; + import { DocumentStatsTable } from './document_stats'; import { ExpandedRowContent } from './expanded_row_content'; import { ExpandedRowPanel } from './expanded_row_panel'; +import { useBarColor } from './use_bar_color'; const METRIC_DISTRIBUTION_CHART_WIDTH = 260; const METRIC_DISTRIBUTION_CHART_HEIGHT = 200; @@ -32,6 +46,13 @@ interface SummaryTableItem { } export const NumberContent: FC = ({ config, onAddFilter }) => { + const { euiTheme } = useEuiTheme(); + + const metricDistributionChartContainer = css({ + paddingTop: euiTheme.size.xs, + width: '100%', + }); + const { stats } = config; const distributionChartData = useMemo( @@ -39,6 +60,8 @@ export const NumberContent: FC = ({ config, onAddFilter }) => [stats?.distribution] ); + const barColor = useBarColor(); + if (stats === undefined) return null; const { min, median, max, distribution } = stats; const fieldFormat = 'fieldFormat' in config ? config.fieldFormat : undefined; @@ -119,7 +142,7 @@ export const NumberContent: FC = ({ config, onAddFilter }) => @@ -141,7 +164,7 @@ export const NumberContent: FC = ({ config, onAddFilter }) => - + { + const { euiTheme } = useEuiTheme(); + + return euiTheme.flags.hasVisColorAdjustment ? 'success' : 'vis0'; +}; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_row/_index.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_row/_index.scss deleted file mode 100644 index 3afa182560e1..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/components/field_data_row/_index.scss +++ /dev/null @@ -1,3 +0,0 @@ -.dataVisualizerColumnHeaderIcon { - max-width: $euiSizeM; -} diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/data_visualizer_stats_table.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/data_visualizer_stats_table.tsx index e0e43efb694f..b4db9b26681e 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/data_visualizer_stats_table.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/data_visualizer_stats_table.tsx @@ -41,7 +41,6 @@ import { BooleanContentPreview } from './components/field_data_row'; import { calculateTableColumnsDimensions } from './utils'; import { DistinctValues } from './components/field_data_row/distinct_values'; import { FieldTypeIcon } from '../field_type_icon'; -import './_index.scss'; import type { FieldStatisticTableEmbeddableProps } from '../../../index_data_visualizer/embeddables/grid_embeddable/types'; import type { DataVisualizerTableItem } from './types'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_color_range.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_color_range.ts index d230da125c13..b929ec9a557d 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_color_range.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_color_range.ts @@ -7,8 +7,7 @@ import d3 from 'd3'; import { i18n } from '@kbn/i18n'; -import { useCurrentEuiTheme } from '../../../hooks/use_current_eui_theme'; - +import { useEuiTheme } from '@elastic/eui'; /** * Custom color scale factory that takes the amount of feature influencers * into account to adjust the contrast of the color range. This is used for @@ -155,16 +154,24 @@ export const useColorRange = ( colorRangeScale = COLOR_RANGE_SCALE.LINEAR, featureCount = 1 ) => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const colorRanges: Record = { [COLOR_RANGE.BLUE]: [ - d3.rgb(euiTheme.euiColorEmptyShade).toString(), - d3.rgb(euiTheme.euiColorVis1).toString(), + d3.rgb(euiTheme.colors.emptyShade).toString(), + d3 + .rgb( + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2 + ) + .toString(), ], [COLOR_RANGE.RED]: [ - d3.rgb(euiTheme.euiColorEmptyShade).toString(), - d3.rgb(euiTheme.euiColorDanger).toString(), + d3.rgb(euiTheme.colors.emptyShade).toString(), + d3.rgb(euiTheme.colors.danger).toString(), ], [COLOR_RANGE.RED_GREEN]: ['red', 'green'], [COLOR_RANGE.GREEN_RED]: ['green', 'red'], diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_data_viz_chart_theme.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_data_viz_chart_theme.ts index 269c9b55fc3d..cf21569de6eb 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_data_viz_chart_theme.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/stats_table/hooks/use_data_viz_chart_theme.ts @@ -5,18 +5,22 @@ * 2.0. */ -import type { PartialTheme } from '@elastic/charts'; import { useMemo } from 'react'; -import { useCurrentEuiTheme } from '../../../hooks/use_current_eui_theme'; + +import type { PartialTheme } from '@elastic/charts'; +import { useEuiFontSize, useEuiTheme } from '@elastic/eui'; + export const useDataVizChartTheme = (): PartialTheme => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; const chartTheme = useMemo(() => { - const AREA_SERIES_COLOR = euiTheme.euiColorVis0; + // Amsterdam + Borealis + const AREA_SERIES_COLOR = euiTheme.colors.vis.euiColorVis0; return { axes: { tickLabel: { - fontSize: parseInt(euiTheme.euiFontSizeXS, 10), - fontFamily: euiTheme.euiFontFamily, + fontSize: parseInt(euiFontSizeXS, 10), + fontFamily: euiTheme.font.family, fontStyle: 'italic', }, }, @@ -50,6 +54,6 @@ export const useDataVizChartTheme = (): PartialTheme => { area: { visible: true, opacity: 1 }, }, }; - }, [euiTheme]); + }, [euiFontSizeXS, euiTheme]); return chartTheme; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/_top_values.scss b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/_top_values.scss deleted file mode 100644 index bb227dd24d48..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/_top_values.scss +++ /dev/null @@ -1,7 +0,0 @@ -.fieldDataTopValuesContainer { - padding-top: $euiSizeXS; -} - -.topValuesValueLabelContainer { - margin-right: $euiSizeM; -} diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/top_values.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/top_values.tsx index 35c648e7135b..d3337a7f676d 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/top_values.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/top_values/top_values.tsx @@ -34,7 +34,7 @@ import type { FieldVisStats } from '../../../../../common/types'; import { ExpandedRowPanel } from '../stats_table/components/field_data_expanded_row/expanded_row_panel'; import { EMPTY_EXAMPLE } from '../examples_list/examples_list'; -interface Props { +interface TopValuesProps { stats: FieldVisStats | undefined; fieldFormat?: any; barColor?: EuiProgressProps['color']; @@ -53,7 +53,7 @@ function getPercentLabel(percent: number): string { } } -export const TopValues: FC = ({ +export const TopValues: FC = ({ stats, fieldFormat, barColor, @@ -72,7 +72,11 @@ export const TopValues: FC = ({ data: { fieldFormats }, }, } = useDataVisualizerKibana(); - const euiTheme = useEuiTheme(); + const euiThemeContext = useEuiTheme(); + const { euiTheme } = euiThemeContext; + + const fieldDataTopValuesContainer = css({ paddingTop: euiTheme.size.xs }); + const topValuesValueLabelContainer = css({ marginRight: euiTheme.size.m }); if (stats === undefined || !stats.topValues) return null; const { fieldName, sampleCount, approximate } = stats; @@ -175,7 +179,7 @@ export const TopValues: FC = ({ className={classNames('dvPanel__wrapper', compressed ? 'dvPanel--compressed' : undefined)} css={css` overflow-x: auto; - ${euiScrollBarStyles(euiTheme)} + ${euiScrollBarStyles(euiThemeContext)} `} > @@ -194,7 +198,8 @@ export const TopValues: FC = ({
{Array.isArray(topValues) ? topValues.map((value) => { @@ -210,7 +215,8 @@ export const TopValues: FC = ({ color={barColor} size="xs" label={value.key ? kibanaFieldFormat(value.key, fieldFormat) : displayValue} - className={classNames('eui-textTruncate', 'topValuesValueLabelContainer')} + className="eui-textTruncate" + css={topValuesValueLabelContainer} valueText={`${value.doc_count}${ totalDocuments !== undefined ? ` (${getPercentLabel(value.percent * 100)})` @@ -289,7 +295,8 @@ export const TopValues: FC = ({ defaultMessage="Other" /> } - className={classNames('eui-textTruncate', 'topValuesValueLabelContainer')} + className="eui-textTruncate" + css={topValuesValueLabelContainer} valueText={`${topValuesOtherCount}${ totalDocuments !== undefined ? ` (${getPercentLabel(topValuesOtherCountPercent * 100)})` diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_current_eui_theme.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_current_eui_theme.ts deleted file mode 100644 index bd2500b1b77e..000000000000 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_current_eui_theme.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { useCurrentEuiThemeVars } from '@kbn/ml-kibana-theme'; -import { useDataVisualizerKibana } from '../../kibana_context'; - -export function useCurrentEuiTheme() { - const { - services: { theme }, - } = useDataVisualizerKibana(); - - return useCurrentEuiThemeVars(theme).euiTheme; -} diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_overview_table.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_overview_table.tsx index 7de413c74b4d..ddbc3d4e9efe 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_overview_table.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_overview_table.tsx @@ -20,12 +20,12 @@ import { import { FieldTypeIcon } from '../common/components/field_type_icon'; import { COLLAPSE_ROW, EXPAND_ROW } from '../../../common/i18n_constants'; import { COMPARISON_LABEL, REFERENCE_LABEL } from './constants'; -import { useCurrentEuiTheme } from '../common/hooks/use_current_eui_theme'; import { type DataDriftField, type Feature, FETCH_STATUS } from './types'; import { formatSignificanceLevel } from './data_drift_utils'; import { SingleDistributionChart } from './charts/single_distribution_chart'; import { OverlapDistributionComparison } from './charts/overlap_distribution_chart'; import { DataDriftDistributionChart } from './charts/data_drift_distribution_chart'; +import { useDataDriftColors } from './use_data_drift_colors'; const dataComparisonYesLabel = i18n.translate('xpack.dataVisualizer.dataDrift.fieldTypeYesLabel', { defaultMessage: 'Yes', @@ -47,15 +47,8 @@ export const DataDriftOverviewTable = ({ data: Feature[]; status: FETCH_STATUS; } & UseTableState) => { - const euiTheme = useCurrentEuiTheme(); + const colors = useDataDriftColors(); - const colors = useMemo( - () => ({ - referenceColor: euiTheme.euiColorVis2, - comparisonColor: euiTheme.euiColorVis1, - }), - [euiTheme] - ); const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState>( {} ); diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx index 4623e886852d..229290a1ace2 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx @@ -45,7 +45,6 @@ import { useDataDriftStateManagerContext } from './use_state_manager'; import { useData } from '../common/hooks/use_data'; import type { DVKey, DVStorageMapped } from '../index_data_visualizer/types/storage'; import { DV_FROZEN_TIER_PREFERENCE } from '../index_data_visualizer/types/storage'; -import { useCurrentEuiTheme } from '../common/hooks/use_current_eui_theme'; import type { DataComparisonFullAppState } from './types'; import { getDefaultDataComparisonState } from './types'; import { useDataSource } from '../common/hooks/data_source_context'; @@ -55,6 +54,7 @@ import { COMPARISON_LABEL, REFERENCE_LABEL } from './constants'; import { SearchPanelContent } from '../index_data_visualizer/components/search_panel/search_bar'; import { useSearch } from '../common/hooks/use_search'; import { DocumentCountWithBrush } from './document_count_with_brush'; +import { useDataDriftColors } from './use_data_drift_colors'; const dataViewTitleHeader = css({ minWidth: '300px', @@ -264,12 +264,7 @@ export const DataDriftPage: FC = ({ initialSettings }) => { }); }, [dataService, searchQueryLanguage, searchString]); - const euiTheme = useCurrentEuiTheme(); - const colors = { - referenceColor: euiTheme.euiColorVis2, - comparisonColor: euiTheme.euiColorVis1, - overlapColor: '#490771', - }; + const colors = useDataDriftColors(); const [brushRanges, setBrushRanges] = useState(); diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/document_count_chart_single_brush/document_count_chart_singular.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/document_count_chart_single_brush/document_count_chart_singular.tsx index 94de2d2f4390..71b2cbdd3c2f 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/document_count_chart_single_brush/document_count_chart_singular.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/document_count_chart_single_brush/document_count_chart_singular.tsx @@ -19,6 +19,8 @@ import type { BarStyleAccessor, RectAnnotationSpec, } from '@elastic/charts/dist/chart_types/xy_chart/utils/specs'; +import { useEuiTheme } from '@elastic/eui'; + import { getTimeZone } from '@kbn/visualization-utils'; import { i18n } from '@kbn/i18n'; import type { IUiSettingsClient } from '@kbn/core/public'; @@ -27,10 +29,10 @@ import { MULTILAYER_TIME_AXIS_STYLE } from '@kbn/charts-plugin/common'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { ChartsPluginStart } from '@kbn/charts-plugin/public'; import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; - import { DualBrushAnnotation } from '@kbn/aiops-components'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiText } from '@elastic/eui'; + import { SingleBrush, getSingleBrushWindowParameters, @@ -174,6 +176,8 @@ export const DocumentCountChartWithBrush: FC = (props) const { data, uiSettings, fieldFormats, charts } = dependencies; + const { euiTheme } = useEuiTheme(); + const chartBaseTheme = charts.theme.useChartsBaseTheme(); const xAxisFormatter = fieldFormats.deserialize({ id: 'date' }); @@ -374,7 +378,7 @@ export const DocumentCountChartWithBrush: FC = (props) mlBrushWidth && mlBrushWidth > 0; - const barColor = barColorOverride ? [barColorOverride] : undefined; + const barColor = barColorOverride ? [barColorOverride] : euiTheme.colors.vis.euiColorVis0; const barHighlightColor = barHighlightColorOverride ? [barHighlightColorOverride] : ['orange']; return ( diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_colors.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_colors.ts new file mode 100644 index 000000000000..7d63ee4c7c25 --- /dev/null +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_colors.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useMemo } from 'react'; + +import { useEuiTheme } from '@elastic/eui'; + +export const useDataDriftColors = () => { + const { euiTheme } = useEuiTheme(); + + return useMemo( + () => ({ + // Amsterdam: euiTheme.colors.vis.euiColorVis2 + // Borealis: euiTheme.colors.vis.euiColorVis4 + referenceColor: euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis2 + : euiTheme.colors.vis.euiColorVis4, + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + comparisonColor: euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2, + overlapColor: '#490771', + }), + [euiTheme] + ); +}; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/about_panel.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/about_panel.tsx index 64f08822617f..e76fbf6e6549 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/about_panel.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/about_panel.tsx @@ -5,12 +5,13 @@ * 2.0. */ +import React, { type FC, useMemo } from 'react'; +import { css } from '@emotion/react'; + +import { useEuiTheme } from '@elastic/eui'; + import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; -import type { FC } from 'react'; -import React from 'react'; import { EuiFlexGroup, @@ -30,14 +31,20 @@ interface Props { hasPermissionToImport: boolean; } -const aboutPanelContentStyle = css({ - '.euiFilePicker__icon': { - width: euiThemeVars.euiSizeXXL, - height: euiThemeVars.euiSizeXXL, - }, -}); - export const AboutPanel: FC = ({ onFilePickerChange, hasPermissionToImport }) => { + const { euiTheme } = useEuiTheme(); + + const aboutPanelContentStyle = useMemo( + () => + css({ + '.euiFilePicker__icon': { + width: euiTheme.size.xxl, + height: euiTheme.size.xxl, + }, + }), + [euiTheme] + ); + return ( diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/welcome_content.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/welcome_content.tsx index a5437ad49dc2..af821dce63dd 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/welcome_content.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/about_panel/welcome_content.tsx @@ -5,33 +5,29 @@ * 2.0. */ -import { FormattedMessage } from '@kbn/i18n-react'; -import type { FC } from 'react'; -import React from 'react'; -import { euiThemeVars } from '@kbn/ui-theme'; +import React, { type FC, useMemo } from 'react'; import { css } from '@emotion/react'; -import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiSpacer, EuiText, EuiTitle } from '@elastic/eui'; - -import { useDataVisualizerKibana } from '../../../kibana_context'; +import { + useEuiTheme, + EuiFlexGroup, + EuiFlexItem, + EuiIcon, + EuiSpacer, + EuiText, + EuiTitle, +} from '@elastic/eui'; -const docIconStyle = css({ - marginLeft: euiThemeVars.euiSizeL, - marginTop: euiThemeVars.euiSizeXS, -}); +import { FormattedMessage } from '@kbn/i18n-react'; -const mainIconStyle = css({ - width: '96px', - height: '96px', - marginLeft: euiThemeVars.euiSizeXL, - marginRight: euiThemeVars.euiSizeL, -}); +import { useDataVisualizerKibana } from '../../../kibana_context'; interface Props { hasPermissionToImport: boolean; } export const WelcomeContent: FC = ({ hasPermissionToImport }) => { + const { euiTheme } = useEuiTheme(); const { services: { fileUpload: { getMaxBytesFormatted, getMaxTikaBytesFormatted }, @@ -40,6 +36,21 @@ export const WelcomeContent: FC = ({ hasPermissionToImport }) => { const maxFileSize = getMaxBytesFormatted(); const maxTikaFileSize = getMaxTikaBytesFormatted(); + const { docIconStyle, mainIconStyle } = useMemo(() => { + return { + docIconStyle: css({ + marginLeft: euiTheme.size.l, + marginTop: euiTheme.size.xs, + }), + mainIconStyle: css({ + width: '96px', + height: '96px', + marginLeft: euiTheme.size.xl, + marginRight: euiTheme.size.l, + }), + }; + }, [euiTheme]); + return ( diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/event_rate_chart.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/event_rate_chart.tsx index e8bde09ef24c..d60ab995d415 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/event_rate_chart.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/event_rate_chart.tsx @@ -5,8 +5,8 @@ * 2.0. */ -import type { FC } from 'react'; -import React from 'react'; +import React, { useMemo, type FC } from 'react'; + import type { PartialTheme } from '@elastic/charts'; import { HistogramBarSeries, @@ -16,10 +16,11 @@ import { Tooltip, TooltipType, } from '@elastic/charts'; +import { useEuiTheme } from '@elastic/eui'; + import { i18n } from '@kbn/i18n'; -import { euiLightVars } from '@kbn/ui-theme'; + import { Axes } from './axes'; -import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme'; export interface LineChartPoint { time: number | string; @@ -33,23 +34,26 @@ interface Props { } export const EventRateChart: FC = ({ eventRateChartData, height, width }) => { - const { euiColorLightShade } = useCurrentEuiTheme(); - const theme: PartialTheme = { - scales: { histogramPadding: 0.2 }, - background: { - color: 'transparent', - }, - axes: { - gridLine: { - horizontal: { - stroke: euiColorLightShade, - }, - vertical: { - stroke: euiColorLightShade, + const { euiTheme } = useEuiTheme(); + const theme: PartialTheme = useMemo( + () => ({ + scales: { histogramPadding: 0.2 }, + background: { + color: 'transparent', + }, + axes: { + gridLine: { + horizontal: { + stroke: euiTheme.colors.lightShade, + }, + vertical: { + stroke: euiTheme.colors.lightShade, + }, }, }, - }, - }; + }), + [euiTheme] + ); return (
= ({ eventRateChartData, height, width }) xAccessor={'time'} yAccessors={['value']} data={eventRateChartData} - color={euiLightVars.euiColorVis0} + // Amsterdam + Borealis + color={euiTheme.colors.vis.euiColorVis0} />
diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/field_badge.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/field_badge.tsx index 55dea99a4042..4a9caf694872 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/field_badge.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/field_badge.tsx @@ -7,11 +7,10 @@ import type { FC } from 'react'; import React from 'react'; -import { EuiBadge, EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui'; +import { useEuiTheme, EuiBadge, EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui'; import { FieldIcon } from '@kbn/react-field'; import { i18n } from '@kbn/i18n'; import { getSupportedFieldType } from '../../../common/components/fields_stats_grid/get_field_names'; -import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme'; interface Props { type: string | undefined; @@ -20,7 +19,9 @@ interface Props { } export const FieldBadge: FC = ({ type, value, name }) => { - const { euiColorLightestShade, euiColorLightShade } = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); + const euiColorLightestShade = euiTheme.colors.lightestShade; + const euiColorLightShade = euiTheme.colors.lightShade; const supportedType = getSupportedFieldType(type ?? 'unknown'); const tooltip = type ? i18n.translate('xpack.dataVisualizer.file.fileContents.fieldBadge.tooltip', { diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/use_text_parser.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/use_text_parser.tsx index 64684c758949..ba381d10af9b 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/use_text_parser.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/file_contents/use_text_parser.tsx @@ -6,18 +6,17 @@ */ import React, { useMemo } from 'react'; -import { EuiText } from '@elastic/eui'; +import { useEuiTheme, EuiText } from '@elastic/eui'; import type { FindFileStructureResponse } from '@kbn/file-upload-plugin/common'; import { FieldBadge } from './field_badge'; import { useDataVisualizerKibana } from '../../../kibana_context'; -import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme'; import { GrokHighlighter } from './grok_highlighter'; export function useGrokHighlighter() { const { services: { http }, } = useDataVisualizerKibana(); - const { euiSizeL } = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const createLines = useMemo( () => @@ -56,7 +55,7 @@ export function useGrokHighlighter() { return ( {formattedWords} @@ -64,7 +63,7 @@ export function useGrokHighlighter() { ); }); }, - [euiSizeL, http] + [euiTheme, http] ); return createLines; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_summary/failures.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_summary/failures.tsx index 2e29b081765c..15389fc404c7 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_summary/failures.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_summary/failures.tsx @@ -6,10 +6,9 @@ */ import { FormattedMessage } from '@kbn/i18n-react'; -import React, { Component } from 'react'; -import { euiThemeVars } from '@kbn/ui-theme'; +import React, { useState, type FC } from 'react'; -import { EuiAccordion, EuiPagination } from '@elastic/eui'; +import { useEuiTheme, EuiAccordion, EuiPagination } from '@elastic/eui'; import { css } from '@emotion/react'; const PAGE_SIZE = 100; @@ -22,63 +21,56 @@ export interface DocFailure { }; } -interface Props { +interface FailuresProps { failedDocs: DocFailure[]; } -interface State { - page: number; -} - const containerStyle = css({ maxHeight: '200px', overflowY: 'auto', }); -const errorStyle = css({ - color: euiThemeVars.euiColorDanger, -}); +export const Failures: FC = ({ failedDocs }) => { + const { euiTheme } = useEuiTheme(); -export class Failures extends Component { - state: State = { page: 0 }; + const [page, setPage] = useState(0); - _renderPaginationControl() { - return this.props.failedDocs.length > PAGE_SIZE ? ( - this.setState({ page })} - compressed - /> - ) : null; - } + const startIndex = page * PAGE_SIZE; + const endIndex = startIndex + PAGE_SIZE; - render() { - const startIndex = this.state.page * PAGE_SIZE; - const endIndex = startIndex + PAGE_SIZE; - return ( - + } + paddingSize="m" + > +
+ {failedDocs.length > PAGE_SIZE && ( + setPage(newPage)} + compressed /> - } - paddingSize="m" - > -
- {this._renderPaginationControl()} - {this.props.failedDocs.slice(startIndex, endIndex).map(({ item, reason, doc }) => ( -
-
- {item}: {reason} -
-
{JSON.stringify(doc)}
+ )} + {failedDocs.slice(startIndex, endIndex).map(({ item, reason, doc }) => ( +
+
+ {item}: {reason}
- ))} -
- - ); - } -} +
{JSON.stringify(doc)}
+
+ ))} +
+ + ); +}; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx index 6289a73e2a66..c8dbb53d68f4 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx @@ -4,7 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import '../_index.scss'; import type { FC, PropsWithChildren } from 'react'; import React from 'react'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_esql.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_esql.tsx index 5953144e715f..2f601498c848 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_esql.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_esql.tsx @@ -16,6 +16,7 @@ import { ESQLLangEditor } from '@kbn/esql/public'; import type { AggregateQuery } from '@kbn/es-query'; import { + useEuiTheme, useEuiBreakpoint, useIsWithinMaxBreakpoint, EuiFlexGroup, @@ -29,7 +30,6 @@ import { import type { DataView } from '@kbn/data-views-plugin/common'; import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils'; import { getOrCreateDataViewByIndexPattern } from '../../search_strategy/requests/get_data_view_by_index_pattern'; -import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme'; import { DATA_VISUALIZER_INDEX_VIEWER } from '../../constants/index_data_visualizer_viewer'; import { useDataVisualizerKibana } from '../../../kibana_context'; import type { GetAdditionalLinks } from '../../../common/components/results_links'; @@ -58,7 +58,7 @@ const DEFAULT_ESQL_QUERY = { esql: '' }; export const IndexDataVisualizerESQL: FC = (dataVisualizerProps) => { const { services } = useDataVisualizerKibana(); const { data } = services; - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); // Query that has been typed, but has not submitted with cmd + enter const [localQuery, setLocalQuery] = useState(DEFAULT_ESQL_QUERY); @@ -281,9 +281,9 @@ export const IndexDataVisualizerESQL: FC = (dataVi grow={false} data-test-subj="DataVisualizerESQLEditor" css={css({ - borderTop: euiTheme.euiBorderThin, - borderLeft: euiTheme.euiBorderThin, - borderRight: euiTheme.euiBorderThin, + borderTop: euiTheme.border.thin, + borderLeft: euiTheme.border.thin, + borderRight: euiTheme.border.thin, })} > = (dataVisualizerProps) => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const [savedRandomSamplerPreference, saveRandomSamplerPreference] = useStorage< DVKey, @@ -520,7 +520,7 @@ export const IndexDataVisualizerView: FC = (dataVi data-test-subj="dataViewTitleHeader" direction="row" alignItems="center" - css={{ padding: `${euiTheme.euiSizeS} 0`, marginRight: `${euiTheme.euiSize}` }} + css={{ padding: `${euiTheme.size.s} 0`, marginRight: `${euiTheme.size.base}` }} >

{currentDataView.getName()}

diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/search_panel/field_type_filter.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/search_panel/field_type_filter.tsx index 2c9faf9d9a85..b7e3790620e3 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/search_panel/field_type_filter.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/components/search_panel/field_type_filter.tsx @@ -7,11 +7,10 @@ import type { FC } from 'react'; import React, { useMemo } from 'react'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { useEuiTheme, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { css } from '@emotion/react'; import { getFieldTypeName } from '@kbn/field-utils'; -import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme'; import { FieldTypesHelpPopover } from '../../../common/components/field_types_filter/field_types_help_popover'; import { FieldTypeIcon } from '../../../common/components/field_type_icon'; import type { Option } from '../../../common/components/multi_select_picker'; @@ -22,7 +21,7 @@ export const DataVisualizerFieldTypeFilter: FC<{ setVisibleFieldTypes(q: string[]): void; visibleFieldTypes: string[]; }> = ({ indexedFieldTypes, setVisibleFieldTypes, visibleFieldTypes }) => { - const euiTheme = useCurrentEuiTheme(); + const { euiTheme } = useEuiTheme(); const options: Option[] = useMemo(() => { return indexedFieldTypes.map((indexedFieldName) => { const label = getFieldTypeName(indexedFieldName) ?? indexedFieldName; @@ -61,7 +60,7 @@ export const DataVisualizerFieldTypeFilter: FC<{ postfix={} cssStyles={{ filterGroup: css` - margin-left: ${euiTheme.euiSizeS}; + margin-left: ${euiTheme.size.s}; `, }} /> diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/embeddables/field_stats/field_stats_initializer.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/embeddables/field_stats/field_stats_initializer.tsx index eb829e9a20cd..4f53fc389140 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/embeddables/field_stats/field_stats_initializer.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/embeddables/field_stats/field_stats_initializer.tsx @@ -6,6 +6,8 @@ */ import { + mathWithUnits, + useEuiTheme, EuiButton, EuiButtonEmpty, EuiCodeBlock, @@ -28,7 +30,6 @@ import React, { useMemo, useState, useCallback } from 'react'; import { ENABLE_ESQL, getESQLAdHocDataview } from '@kbn/esql-utils'; import type { AggregateQuery } from '@kbn/es-query'; import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; import { useDataVisualizerKibana } from '../../../kibana_context'; import { FieldStatsESQLEditor } from './field_stats_esql_editor'; import type { @@ -61,6 +62,12 @@ export const FieldStatisticsInitializer: FC = ({ onPreview, isNewPanel, }) => { + const euiContext = useEuiTheme(); + const { euiTheme } = euiContext; + + // FIXME: add a token for this on euiTheme.components. https://github.com/elastic/eui/issues/8217 + const formMaxWidth = mathWithUnits(euiTheme.size.base, (x) => x * 25); + const { data: { dataViews }, unifiedSearch: { @@ -130,7 +137,7 @@ export const FieldStatisticsInitializer: FC = ({ hasBorder={true} css={css` pointer-events: auto; - background-color: ${euiThemeVars.euiColorEmptyShade}; + background-color: ${euiTheme.colors.emptyShade}; `} data-test-subj="editFlyoutHeader" > @@ -171,8 +178,8 @@ export const FieldStatisticsInitializer: FC = ({ css={css` // styles needed to display extra drop targets that are outside of the config panel main area overflow-y: auto; - padding-left: ${euiThemeVars.euiFormMaxWidth}; - margin-left: -${euiThemeVars.euiFormMaxWidth}; + padding-left: ${formMaxWidth}; + margin-left: -${formMaxWidth}; pointer-events: none; .euiFlyoutBody__overflow { -webkit-mask-image: none; @@ -190,7 +197,7 @@ export const FieldStatisticsInitializer: FC = ({ padding: 0; block-size: 100%; } - border-bottom: 2px solid ${euiThemeVars.euiBorderColor}; + border-bottom: 2px solid ${euiTheme.border.color}; `} > = ({ defaultMessage: 'Data view', } )} - css={css({ padding: euiThemeVars.euiSizeM })} + css={css({ padding: euiTheme.size.m })} > { if (!isDataView(fetchedDataView) && fetchedSavedSearch === undefined) { setError( i18n.translate('xpack.transform.searchItems.errorInitializationTitle', { - defaultMessage: `An error occurred initializing the Kibana data view or saved search.`, + defaultMessage: `An error occurred initializing the Kibana data view or Discover session.`, }) ); return; diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_form.tsx b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_form.tsx index 92300d5580cb..43efc8b1b4ca 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_form.tsx +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_form.tsx @@ -377,8 +377,8 @@ export const StepDefineForm: FC = React.memo((props) => { fullWidth label={ searchItems?.savedSearch?.id !== undefined - ? i18n.translate('xpack.transform.stepDefineForm.savedSearchLabel', { - defaultMessage: 'Saved search', + ? i18n.translate('xpack.transform.stepDefineForm.discoverSessionLabel', { + defaultMessage: 'Discover session', }) : i18n.translate('xpack.transform.stepDefineForm.searchFilterLabel', { defaultMessage: 'Search filter', diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_summary.tsx b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_summary.tsx index b284eb3e1a02..9fc938cd2028 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_summary.tsx +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/step_define_summary.tsx @@ -141,8 +141,8 @@ export const StepDefineSummary: FC = ({ {searchItems.savedSearch !== undefined && searchItems.savedSearch.id !== undefined && ( {searchItems.savedSearch.title} diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/wizard/wizard.tsx b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/wizard/wizard.tsx index 2c078f93627c..ab2865b85eb8 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/wizard/wizard.tsx +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/wizard/wizard.tsx @@ -111,7 +111,7 @@ export const CreateTransformWizardContext = createContext<{ export const Wizard: FC = React.memo(({ cloneConfig, searchItems }) => { const { showNodeInfo } = useEnabledFeatures(); const appDependencies = useAppDependencies(); - const { uiSettings, data, fieldFormats, charts, theme } = appDependencies; + const { uiSettings, data, fieldFormats, charts } = appDependencies; const { dataView } = searchItems; // The current WIZARD_STEP @@ -247,7 +247,6 @@ export const Wizard: FC = React.memo(({ cloneConfig, searchItems }) fieldStatsServices={fieldStatsServices} timeRangeMs={stepDefineState.timeRangeMs} dslQuery={transformConfig.source.query} - theme={theme} > = ({ noItemsMessage={i18n.translate( 'xpack.transform.newTransform.searchSelection.notFoundLabel', { - defaultMessage: 'No matching indices or saved searches found.', + defaultMessage: 'No matching indices or saved Discover sessions found.', } )} savedObjectMetaData={[ { type: 'search', - getIconForSavedObject: () => 'search', + getIconForSavedObject: () => 'discoverApp', name: i18n.translate( - 'xpack.transform.newTransform.searchSelection.savedObjectType.search', + 'xpack.transform.newTransform.searchSelection.savedObjectType.discoverSession', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', } ), showSavedObject: (savedObject: SavedObject) => diff --git a/x-pack/platform/plugins/private/translations/translations/fr-FR.json b/x-pack/platform/plugins/private/translations/translations/fr-FR.json index 162b2b57ab64..82df2e0b71b5 100644 --- a/x-pack/platform/plugins/private/translations/translations/fr-FR.json +++ b/x-pack/platform/plugins/private/translations/translations/fr-FR.json @@ -1454,7 +1454,6 @@ "dashboard.emptyScreen.noPermissionsTitle": "Ce tableau de bord est vide.", "dashboard.emptyScreen.viewModeSubtitle": "Accédez au mode de modification, puis commencez à ajouter vos visualisations.", "dashboard.emptyScreen.viewModeTitle": "Ajouter des visualisations à votre tableau de bord", - "dashboard.featureCatalogue.dashboardDescription": "Affichez et partagez une collection de visualisations et de recherches enregistrées.", "dashboard.featureCatalogue.dashboardSubtitle": "Analysez des données à l’aide de tableaux de bord.", "dashboard.featureCatalogue.dashboardTitle": "Dashboard", "dashboard.labs.enableLabsDescription": "Cet indicateur détermine si l'utilisateur a accès au bouton Ateliers, moyen rapide d'activer et de désactiver les fonctionnalités de la version d'évaluation technique dans le tableau de bord.", @@ -1582,7 +1581,6 @@ "data.advancedSettings.courier.requestPreferenceTitle": "Préférence de requête", "data.advancedSettings.defaultIndexText": "Utilisé par Discover et Visualisations lorsqu'une vue de données n'est pas définie.", "data.advancedSettings.defaultIndexTitle": "Vue de données par défaut", - "data.advancedSettings.docTableHighlightText": "Cela permet de mettre les résultats en surbrillance dans le tableau de bord Discover ainsi que dans les recherches enregistrées. À noter que la mise en surbrillance ralentit les requêtes dans le cas de documents volumineux.", "data.advancedSettings.docTableHighlightTitle": "Mettre les résultats en surbrillance", "data.advancedSettings.histogram.barTargetText": "Tente de générer ce nombre de compartiments lorsque l’intervalle \"auto\" est utilisé dans des histogrammes numériques et de date.", "data.advancedSettings.histogram.barTargetTitle": "Nombre de compartiments cible", @@ -2511,7 +2509,6 @@ "discover.advancedSettings.discover.showFieldStatisticsDescription": "Activez le {fieldStatisticsDocs} pour afficher des détails tels que les valeurs minimale et maximale d'un champ numérique ou une carte d'un champ géographique. Cette fonctionnalité est en version bêta et susceptible d'être modifiée.", "discover.advancedSettings.discover.showMultifields": "Afficher les champs multiples", "discover.advancedSettings.discover.showMultifieldsDescription": "Détermine si les {multiFields} doivent s'afficher dans la fenêtre de document étendue. Dans la plupart des cas, les champs multiples sont les mêmes que les champs d'origine. Cette option est uniquement disponible lorsque le paramètre `searchFieldsFromSource` est désactivé.", - "discover.advancedSettings.docTableHideTimeColumnText": "Permet de masquer la colonne ''Time'' dans Discover et dans toutes les recherches enregistrées des tableaux de bord.", "discover.advancedSettings.docTableHideTimeColumnTitle": "Masquer la colonne ''Time''", "discover.advancedSettings.fieldsPopularLimitText": "Les N champs les plus populaires à afficher", "discover.advancedSettings.fieldsPopularLimitTitle": "Limite de champs populaires", @@ -2523,7 +2520,6 @@ "discover.advancedSettings.sampleRowsPerPageTitle": "Lignes par page", "discover.advancedSettings.sampleSizeText": "Définit le nombre maximum de lignes pour l'ensemble du tableau de documents.", "discover.advancedSettings.sampleSizeTitle": "Lignes max. par tableau", - "discover.advancedSettings.searchOnPageLoadText": "Détermine si une recherche est exécutée lors du premier chargement de Discover. Ce paramètre n'a pas d'effet lors du chargement d’une recherche enregistrée.", "discover.advancedSettings.searchOnPageLoadTitle": "Recherche au chargement de la page", "discover.advancedSettings.sortDefaultOrderText": "Détermine le sens de tri par défaut pour les vues de données temporelles dans l'application Discover.", "discover.advancedSettings.sortDefaultOrderTitle": "Sens de tri par défaut", @@ -2533,7 +2529,6 @@ "discover.alerts.manageRulesAndConnectors": "Gérer les règles et les connecteurs", "discover.alerts.missedTimeFieldToolTip": "La vue de données ne possède pas de champ temporel.", "discover.badge.readOnly.text": "Lecture seule", - "discover.badge.readOnly.tooltip": "Impossible d’enregistrer les recherches", "discover.context.breadcrumb": "Documents relatifs", "discover.context.contextOfTitle": "Les documents relatifs à #{anchorId}", "discover.context.failedToLoadAnchorDocumentDescription": "Échec de chargement du document ancré", @@ -2581,7 +2576,6 @@ "discover.dropZoneTableLabel": "Abandonner la zone pour ajouter un champ en tant que colonne dans la table", "discover.embeddable.inspectorRequestDescription": "Cette requête interroge Elasticsearch afin de récupérer les données pour la recherche.", "discover.embeddable.search.dataViewError": "Vue de données {indexPatternId} manquante", - "discover.embeddable.search.displayName": "rechercher", "discover.errorCalloutESQLReferenceButtonLabel": "Ouvrir la référence ES|QL", "discover.errorCalloutShowErrorMessage": "Afficher les détails", "discover.esqlMode.selectedColumnsCallout": "Affichage de {selectedColumnsNumber} champs sur {esqlQueryColumnsNumber}. Ajoutez-en d’autres depuis la liste des champs disponibles.", @@ -2590,7 +2584,6 @@ "discover.esqlToDataViewTransitionModal.feedbackLink": "Soumettre des commentaires ES|QL", "discover.esqlToDataViewTransitionModal.saveButtonLabel": "Sauvegarder et basculer", "discover.esqlToDataViewTransitionModal.title": "Modifications non enregistrées", - "discover.esqlToDataviewTransitionModalBody": "Un changement de vue de données supprime la requête ES|QL en cours. Sauvegardez cette recherche pour éviter de perdre votre travail.", "discover.fieldChooser.availableFieldsTooltip": "Champs disponibles pour l'affichage dans le tableau.", "discover.fieldChooser.discoverField.addFieldTooltip": "Ajouter le champ en tant que colonne", "discover.fieldChooser.discoverField.removeFieldTooltip": "Supprimer le champ du tableau", @@ -2618,19 +2611,10 @@ "discover.loadingDocuments": "Chargement des documents", "discover.localMenu.alertsDescription": "Alertes", "discover.localMenu.esqlTooltipLabel": "ES|QL est le nouveau langage de requête canalisé puissant d'Elastic.", - "discover.localMenu.fallbackReportTitle": "Recherche Discover sans titre", "discover.localMenu.inspectTitle": "Inspecter", "discover.localMenu.localMenu.alertsTitle": "Alertes", - "discover.localMenu.localMenu.newSearchTitle": "Nouveauté", - "discover.localMenu.mustCopyOnSave": "Elastic gère cette recherche enregistrée. Enregistrez les modifications dans une nouvelle recherche enregistrée.", - "discover.localMenu.newSearchDescription": "Nouvelle recherche", "discover.localMenu.openInspectorForSearchDescription": "Ouvrir l'inspecteur de recherche", - "discover.localMenu.openSavedSearchDescription": "Ouvrir une recherche enregistrée", - "discover.localMenu.openTitle": "Ouvrir", - "discover.localMenu.saveSaveSearchObjectType": "rechercher", - "discover.localMenu.saveSearchDescription": "Enregistrer la recherche", "discover.localMenu.saveTitle": "Enregistrer", - "discover.localMenu.shareSearchDescription": "Partager la recherche", "discover.localMenu.shareTitle": "Partager", "discover.localMenu.switchToClassicTitle": "Basculer vers le classique", "discover.localMenu.switchToClassicTooltipLabel": "Passez à la syntaxe KQL ou Lucene.", @@ -2696,8 +2680,6 @@ "discover.noResults.suggestion.tryText": "Voici quelques solutions à essayer :", "discover.notifications.invalidTimeRangeText": "La plage temporelle spécifiée n'est pas valide. (de : \"{from}\" à \"{to}\")", "discover.notifications.invalidTimeRangeTitle": "Plage temporelle non valide", - "discover.notifications.notSavedSearchTitle": "La recherche \"{savedSearchTitle}\" n'a pas été enregistrée.", - "discover.notifications.savedSearchTitle": "La recherche \"{savedSearchTitle}\" a été enregistrée", "discover.pageTitleWithoutSavedSearch": "Discover - Recherche non encore enregistrée", "discover.pageTitleWithSavedSearch": "Discover - {savedSearchTitle}", "discover.panelsToggle.hideChartButton": "Masquer le graphique", @@ -2706,24 +2688,15 @@ "discover.panelsToggle.showSidebarButton": "Afficher la barre latérale", "discover.rootBreadcrumb": "Discover", "discover.sampleData.viewLinkLabel": "Discover", - "discover.savedSearch.savedObjectName": "Recherche enregistrée", - "discover.savedSearchAliasMatchRedirect.objectNoun": "Recherche {savedSearch}", "discover.savedSearchEmbeddable.action.viewSavedSearch.displayName": "Ouvrir dans Discover", - "discover.savedSearchURLConflictCallout.objectNoun": "Recherche {savedSearch}", "discover.searchingTitle": "Recherche", "discover.serverLocatorExtension.titleFromLocatorUnknown": "Recherche inconnue", - "discover.share.shareModal.title": "Partager cette recherche", "discover.showingDefaultDataViewWarningDescription": "Affichage de la vue de données par défaut : \"{loadedDataViewTitle}\" ({loadedDataViewId})", "discover.showingSavedDataViewWarningDescription": "Affichage de la vue de données enregistrée : \"{ownDataViewTitle}\" ({ownDataViewId})", "discover.singleDocRoute.errorMessage": "Aucune donnée correspondante pour l'ID {dataViewId}", "discover.singleDocRoute.errorTitle": "Une erreur s'est produite", "discover.skipToBottomButtonLabel": "Atteindre la fin du tableau", - "discover.topNav.managedContentLabel": "Cette recherche sauvegardée est gérée par Elastic. Les modifications effectuées ici doivent être enregistrées dans une nouvelle recherche sauvegardée.", - "discover.topNav.openSearchPanel.manageSearchesButtonLabel": "Gérer les recherches", - "discover.topNav.openSearchPanel.noSearchesFoundDescription": "Aucune recherche correspondante trouvée.", - "discover.topNav.openSearchPanel.openSearchTitle": "Ouvrir une recherche", "discover.topNav.saveModal.storeTimeWithSearchToggleDescription": "Mettez à jour le filtre temporel et actualisez l'intervalle pour afficher la sélection actuelle lors de l'utilisation de cette recherche.", - "discover.topNav.saveModal.storeTimeWithSearchToggleLabel": "Stocker la durée avec la recherche enregistrée", "discover.uninitializedRefreshButtonText": "Actualiser les données", "discover.uninitializedText": "Saisissez une requête, ajoutez quelques filtres, ou cliquez simplement sur Actualiser afin d’extraire les résultats pour la requête en cours.", "discover.uninitializedTitle": "Commencer la recherche", @@ -2799,7 +2772,6 @@ "embeddableApi.common.constants.grouping.annotations": "Annotations et Navigation", "embeddableApi.common.constants.grouping.legacy": "Hérité", "embeddableApi.common.constants.grouping.other": "Autre", - "embeddableApi.compatibility.defaultTypeDisplayName": "graphique", "embeddableApi.contextMenuTrigger.description": "Une nouvelle action sera ajoutée au menu contextuel du panneau", "embeddableApi.contextMenuTrigger.title": "Menu contextuel", "embeddableApi.errors.embeddableFactoryNotFound": "Impossible de charger {type}. Veuillez effectuer une mise à niveau vers la distribution par défaut d'Elasticsearch et de Kibana avec la licence appropriée.", @@ -2844,7 +2816,6 @@ "embeddableExamples.unifiedFieldList.displayName": "Liste des champs", "embeddableExamples.unifiedFieldList.noDefaultDataViewErrorMessage": "La liste de champs doit être utilisée avec au moins une vue de données présente", "embeddableExamples.unifiedFieldList.selectDataViewMessage": "Veuillez sélectionner une vue de données", - "esql.advancedSettings.enableESQLDescription": "Ce paramètre active ES|QL dans Kibana. En le désactivant, vous cacherez l'interface utilisateur ES|QL de diverses applications. Cependant, les utilisateurs pourront accéder aux recherches enregistrées ES|QL, en plus des visualisations, etc.", "esql.advancedSettings.enableESQLTitle": "Activer ES|QL", "esql.triggers.updateEsqlQueryTrigger": "Mettre à jour la requête ES|QL", "esql.triggers.updateEsqlQueryTriggerDescription": "Mettre à jour la requête ES|QL en utilisant une nouvelle requête", @@ -5074,7 +5045,6 @@ "indexPatternManagement.editIndexPattern.source.table.matchesHeader": "Correspondances", "indexPatternManagement.editIndexPattern.source.table.notMatchedLabel": "Le filtre source ne correspond à aucun champ connu.", "indexPatternManagement.editIndexPattern.source.table.saveAria": "Enregistrer", - "indexPatternManagement.editIndexPattern.sourceLabel": "Les filtres de champ peuvent être utilisés pour exclure un ou plusieurs champs lors de la récupération d'un document. Cela se produit lors de l'affichage d'un document dans l'application Discover ou avec un tableau affichant les résultats d'une recherche enregistrée dans l'application Dashboard. Si vous avez des documents avec des champs de grande taille ou peu importants, il pourrait être utile de filtrer ces champs à ce niveau plus bas.", "indexPatternManagement.editIndexPattern.sourcePlaceholder": "filtre de champ, accepte les caractères génériques (par ex. `user*` pour filtrer les champs commençant par `user`)", "indexPatternManagement.editIndexPattern.tabs.fieldsHeader": "Champs", "indexPatternManagement.editIndexPattern.tabs.relationshipsHeader": "Relations ({count})", @@ -6667,9 +6637,7 @@ "savedObjectsManagement.view.inspectCodeEditorAriaLabel": "inspecter { title }", "savedObjectsManagement.view.inspectItemTitle": "Inspecter {title}", "savedObjectsManagement.view.savedObjectProblemErrorMessage": "Un problème est survenu avec cet objet enregistré.", - "savedObjectsManagement.view.savedSearchDoesNotExistErrorMessage": "La recherche enregistrée associée à cet objet n'existe plus.", "savedObjectsManagement.view.viewItemButtonLabel": "Afficher {title}", - "savedSearch.contentManagementType": "Recherche enregistrée", "savedSearch.kibana_context.filters.help": "Spécifier des filtres génériques Kibana", "savedSearch.kibana_context.help": "Met à jour le contexte général de Kibana.", "savedSearch.kibana_context.q.help": "Spécifier une recherche en texte libre Kibana", @@ -7292,6 +7260,14 @@ "securitySolutionPackages.alertSuppressionRuleDetails.upsell": "La suppression d'alertes est configurée mais elle ne sera pas appliquée en raison d'une licence insuffisante", "securitySolutionPackages.alertSuppressionRuleForm.upsell": "La suppression d'alertes est activée avec la licence {requiredLicense} ou supérieure", "securitySolutionPackages.beta.label": "Bêta", + "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "Échec", + "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "S. O.", + "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "Réussite", + "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "Échec de la recherche", + "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "Niveau de sécurité du cloud", + "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "Résultats", + "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "Règles", + "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "Gestion des vulnérabilités natives du cloud", "securitySolutionPackages.dataTable.ariaLabel": "Alertes", "securitySolutionPackages.dataTable.columnHeaders.flyout.pane.removeColumnButtonLabel": "Supprimer la colonne", "securitySolutionPackages.dataTable.eventRenderedView.eventSummary.column": "Résumé des événements", @@ -7621,6 +7597,7 @@ "share.urlService.redirect.RedirectManager.missingParamLocator": "ID du localisateur non spécifié. Spécifiez le paramètre de recherche \"l\" dans l'URL ; ce devrait être un ID de localisateur existant.", "share.urlService.redirect.RedirectManager.missingParamParams": "Paramètres du localisateur non spécifiés. Spécifiez le paramètre de recherche \"p\" dans l'URL ; ce devrait être un objet sérialisé JSON des paramètres du localisateur.", "share.urlService.redirect.RedirectManager.missingParamVersion": "Version des paramètres du localisateur non spécifiée. Spécifiez le paramètre de recherche \"v\" dans l'URL ; ce devrait être la version de Kibana au moment de la génération des paramètres du localisateur.", + "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "Erreur inconnue", "sharedUXPackages.buttonToolbar.buttons.addFromLibrary.libraryButtonLabel": "Ajouter depuis la bibliothèque", "sharedUXPackages.buttonToolbar.toolbar.errorToolbarText": "Il y a plus de 120 boutons supplémentaires. Nous vous invitons à limiter le nombre de boutons.", "sharedUXPackages.card.noData.description": "Utilisez Elastic Agent pour collecter de manière simple et unifiée les données de vos machines.", @@ -8073,8 +8050,6 @@ "unifiedDataTable.rowHeight.single": "Unique", "unifiedDataTable.rowHeightLabel": "Hauteur de ligne de cellule", "unifiedDataTable.sampleSizeSettings.sampleSizeLabel": "Taille de l'échantillon", - "unifiedDataTable.searchGenerationWithDescription": "Tableau généré par la recherche {searchTitle}", - "unifiedDataTable.searchGenerationWithDescriptionGrid": "Tableau généré par la recherche {searchTitle} ({searchDescription})", "unifiedDataTable.selectAllDocs": "Tout sélectionner ({rowsCount})", "unifiedDataTable.selectAllRowsOnPageColumnHeader": "Sélectionner toutes les lignes visibles", "unifiedDataTable.selectColumnHeader": "Sélectionner la colonne", @@ -8645,11 +8620,6 @@ "visDefaultEditor.sidebar.errorButtonTooltip": "Les erreurs dans les champs mis en évidence doivent être corrigées.", "visDefaultEditor.sidebar.indexPatternAriaLabel": "Modèle d'indexation : {title}", "visDefaultEditor.sidebar.savedSearch.goToDiscoverButtonText": "Afficher cette recherche dans Discover", - "visDefaultEditor.sidebar.savedSearch.linkButtonAriaLabel": "Lier à la recherche enregistrée. Cliquez pour en savoir plus ou rompre le lien.", - "visDefaultEditor.sidebar.savedSearch.popoverHelpText": "Les modifications apportées ultérieurement à cette recherche enregistrée sont reflétées dans la visualisation. Pour désactiver les mises à jour automatiques, supprimez le lien.", - "visDefaultEditor.sidebar.savedSearch.popoverTitle": "Lié à la recherche enregistrée", - "visDefaultEditor.sidebar.savedSearch.titleAriaLabel": "Recherche enregistrée : {title}", - "visDefaultEditor.sidebar.savedSearch.unlinkSavedSearchButtonText": "Supprimer le lien avec la recherche enregistrée", "visDefaultEditor.sidebar.tabs.dataLabel": "Données", "visDefaultEditor.sidebar.tabs.optionsLabel": "Options", "visDefaultEditor.sidebar.updateChartButtonLabel": "Mettre à jour", @@ -9640,7 +9610,6 @@ "visualizations.helpMenu.appName": "Bibliothèque Visualize", "visualizations.legacyCharts.conditionalMessage.noPermissions": "Contactez votre administrateur système pour passer à l'ancienne bibliothèque.", "visualizations.legacyUrlConflict.objectNoun": "Visualisation {visName}", - "visualizations.linkedToSearch.unlinkSuccessNotificationText": "Dissocié de la recherche enregistrée \"{searchTitle}\"", "visualizations.listing.betaTitle": "Bêta", "visualizations.listing.betaTooltip": "Cette visualisation est en version bêta et susceptible d'être modifiée. La conception et le code sont moins matures que les fonctionnalités officielles en disponibilité générale et sont fournis tels quels sans aucune garantie. Les fonctionnalités bêta ne sont pas soumises aux accords de niveau de service d'assistance des fonctionnalités officielles en disponibilité générale", "visualizations.listing.breadcrumb": "Bibliothèque Visualize", @@ -9673,9 +9642,7 @@ "visualizations.newVisWizard.learnMoreText": "Envie d'en savoir plus ?", "visualizations.newVisWizard.newVisTypeTitle": "Nouveau {visTypeName}", "visualizations.newVisWizard.resultsFound": "{resultCount, plural, one {type trouvé} other {types trouvés}}", - "visualizations.newVisWizard.searchSelection.notFoundLabel": "Aucun recherche enregistrée ni aucun index correspondants n'ont été trouvés.", "visualizations.newVisWizard.searchSelection.savedObjectType.dataView": "Vue de données", - "visualizations.newVisWizard.searchSelection.savedObjectType.search": "Recherche enregistrée", "visualizations.newVisWizard.title": "Nouvelle visualisation", "visualizations.noDataView.label": "vue de données", "visualizations.noMatchRoute.bannerText": "L'application Visualize ne reconnaît pas cet itinéraire : {route}.", @@ -9981,7 +9948,6 @@ "xpack.aiops.correlations.veryLowImpactText": "Très bas", "xpack.aiops.dataGrid.field.documentCountChart.seriesLabel": "compte du document", "xpack.aiops.dataGrid.field.documentCountChartSplit.seriesLabel": "Autre compte du document", - "xpack.aiops.dataSourceContext.errorTitle": "Impossible de récupérer la vue de données ou la recherche enregistrée", "xpack.aiops.dataViewNotBasedOnTimeSeriesWarning.title": "La vue de données \"{dataViewTitle}\" n'est pas basée sur une série temporelle.", "xpack.aiops.documentCountChart.baselineBadgeLabel": "Référence de base", "xpack.aiops.documentCountChart.deviationBadgeLabel": "général", @@ -12674,7 +12640,6 @@ "xpack.canvas.functions.savedMap.args.titleHelpText": "Titre de la carte", "xpack.canvas.functions.savedMap.args.zoomHelpText": "Niveau de zoom de la carte", "xpack.canvas.functions.savedMapHelpText": "Renvoie un objet incorporable pour un objet de carte enregistré.", - "xpack.canvas.functions.savedSearchHelpText": "Renvoie un objet incorporable pour un objet de recherche enregistré", "xpack.canvas.functions.savedVisualization.args.colorsHelpText": "Définit la couleur à utiliser pour une série spécifique", "xpack.canvas.functions.savedVisualization.args.hideLegendHelpText": "Spécifie l'option pour masquer la légende", "xpack.canvas.functions.savedVisualization.args.idHelpText": "ID de l'objet de visualisation enregistré", @@ -14640,7 +14605,6 @@ "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilities": "Vulnérabilités", "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilityCount": "Vulnérabilités", "xpack.csp.common.component.multiSelectFilter.searchWord": "Recherche", - "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "Erreur inconnue", "xpack.csp.compactFormattedNumber.naTitle": "S. O.", "xpack.csp.complianceScoreBar.tooltipTitle": "{failed} échecs et {passed} réussites de résultats", "xpack.csp.complianceScoreChart.counterButtonLink.failedFindingsTooltip": "Échec des résultats", @@ -14655,9 +14619,6 @@ "xpack.csp.createPackagePolicy.customAssetsTab.rulesViewLabel": "Afficher les règles CSP", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityDashboardViewLabel": "Afficher le tableau de bord CNVM", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityFindingsViewLabel": "Afficher les résultats des vulnérabilités", - "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "Échec", - "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "S. O.", - "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "Réussite", "xpack.csp.cspIntegration.gcpCloudCredentials.cloudFormationSupportedMessage": "La fonctionnalité Lancer Cloud Shell pour obtenir les informations d'identification de façon automatisée n’est pas pris en charge dans la version d'intégration actuelle. Veuillez effectuer une mise à niveau vers la dernière version pour activer Lancer Cloud Shell pour les informations d'identification automatisées.", "xpack.csp.cspmIntegration.awsOption.benchmarkTitle": "CIS AWS", "xpack.csp.cspmIntegration.awsOption.nameTitle": "AWS", @@ -14741,7 +14702,6 @@ "xpack.csp.findings.distributionBar.totalPassedLabel": "Réussite des résultats", "xpack.csp.findings.errorCallout.pageSearchErrorTitle": "Une erreur s’est produite lors de la récupération des résultats de recherche.", "xpack.csp.findings.errorCallout.showErrorButtonLabel": "Afficher le message d'erreur", - "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "Échec de la recherche", "xpack.csp.findings.findingsFlyout.calloutTitle": "Certains champs ne sont pas fournis par {vendor}", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceId": "ID ressource", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceName": "Nom de ressource", @@ -14911,10 +14871,6 @@ "xpack.csp.kspmIntegration.integration.shortNameTitle": "KSPM", "xpack.csp.kspmIntegration.vanillaOption.benchmarkTitle": "CIS Kubernetes", "xpack.csp.kspmIntegration.vanillaOption.nameTitle": "Autogéré", - "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "Niveau de sécurité du cloud", - "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "Résultats", - "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "Règles", - "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "Gestion des vulnérabilités natives du cloud", "xpack.csp.noFindingsStates.indexing.indexingButtonTitle": "Évaluation du niveau en cours", "xpack.csp.noFindingsStates.indexing.indexingDescription": "En attente de la collecte et de l'indexation des données. Revenez plus tard pour voir vos résultats", "xpack.csp.noFindingsStates.indexTimeout.indexTimeoutDescription": "La collecte des résultats prend plus de temps que prévu. {docs}.", @@ -15575,7 +15531,6 @@ "xpack.dataVisualizer.index.lensChart.countLabel": "Décompte", "xpack.dataVisualizer.index.lensChart.maximumOfLabel": "Maximum de {fieldName}", "xpack.dataVisualizer.index.lensChart.topValuesLabel": "Valeurs les plus élevées", - "xpack.dataVisualizer.index.savedSearchErrorMessage": "Erreur lors de la récupération de la recherche enregistrée {savedSearchId}", "xpack.dataVisualizer.multiSelectPicker.NoFiltersFoundMessage": "Aucun filtre trouvé", "xpack.dataVisualizer.nameCollisionMsg": "\"{name}\" existe déjà, veuillez fournir un nom unique", "xpack.dataVisualizer.noData": "Aucune donnée", @@ -19775,7 +19730,6 @@ "xpack.features.ossFeatures.discoverSearchSessionsFeatureName": "Stocker les sessions de recherche", "xpack.features.ossFeatures.discoverShortUrlSubFeatureName": "URL courtes", "xpack.features.ossFeatures.discoverStoreSearchSessionsPrivilegeName": "Stocker les sessions de recherche", - "xpack.features.ossFeatures.reporting.dashboardDownloadCSV": "Générer les rapports CSV depuis les panneaux des recherches enregistrées", "xpack.features.ossFeatures.reporting.dashboardGenerateScreenshot": "Générer des rapports PDF ou PNG", "xpack.features.ossFeatures.reporting.discoverGenerateCSV": "Générer des rapports CSV", "xpack.features.ossFeatures.reporting.reportingTitle": "Reporting", @@ -20760,7 +20714,6 @@ "xpack.fleet.epm.assetTitles.mlModules": "Configurations de la détection d'anomalies", "xpack.fleet.epm.assetTitles.osqueryPackAssets": "Packs Osquery", "xpack.fleet.epm.assetTitles.osquerySavedQuery": "Requêtes Osquery enregistrées", - "xpack.fleet.epm.assetTitles.savedSearches": "Recherches enregistrées", "xpack.fleet.epm.assetTitles.securityRules": "Règles de sécurité", "xpack.fleet.epm.assetTitles.tag": "Balises", "xpack.fleet.epm.assetTitles.transforms": "Transformations", @@ -22384,8 +22337,6 @@ "xpack.idxMgmt.goToDiscover.discoverIndexButtonLabel": "Découvrir les index", "xpack.idxMgmt.goToDiscover.showIndexToolTip": "Montrer {indexName} dans Discover", "xpack.idxMgmt.home.appTitle": "Gestion des index", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesDescription": "Vérification des privilèges…", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesErrorMessage": "Erreur lors de la récupération des privilèges utilisateur depuis le serveur.", "xpack.idxMgmt.home.componentTemplates.confirmButtonLabel": "Supprimer {numComponentTemplatesToDelete, plural, one {le modèle de composant} other {les modèles de composants} }", "xpack.idxMgmt.home.componentTemplates.deleteModal.cancelButtonLabel": "Annuler", "xpack.idxMgmt.home.componentTemplates.deleteModal.deleteDescription": "Vous êtes sur le point de supprimer {numComponentTemplatesToDelete, plural, one {ce modèle de composant} other {ces modèles de composants} } :", @@ -22394,8 +22345,6 @@ "xpack.idxMgmt.home.componentTemplates.deleteModal.multipleErrorsNotificationMessageText": "Erreur lors de la suppression de {count} modèles de composants", "xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteMultipleNotificationMessageText": "{numSuccesses, plural, one {# modèle de composant supprimé} other {# modèles de composants supprimés}}", "xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteSingleNotificationMessageText": "Le modèle de composant \"{componentTemplateName}\" a bien été supprimé", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeDescription": "Pour utiliser les modèles de composants, vous devez posséder {privilegesCount, plural, one {ce privilège de cluster} other {ces privilèges de cluster}} : {missingPrivileges}.", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeTitle": "Privilèges de cluster requis", "xpack.idxMgmt.home.componentTemplates.emptyPromptButtonLabel": "Créer un modèle de composant", "xpack.idxMgmt.home.componentTemplates.emptyPromptDescription": "Par exemple, vous pouvez créer un modèle de composant pour les paramètres d'index réutilisables dans tous les modèles d'index.", "xpack.idxMgmt.home.componentTemplates.emptyPromptDocumentionLink": "En savoir plus.", @@ -24333,8 +24282,6 @@ "xpack.infra.logsPage.toolbar.logFilterErrorToastTitle": "Erreur de filtrage du log", "xpack.infra.logsSettingsPage.loadingButtonLabel": "Chargement", "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription": "La maintenance des panneaux de flux de logs n'est plus assurée. Essayez d'utiliser {savedSearchDocsLink} pour une visualisation similaire.", - "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription.savedSearchesLinkLabel": "recherches enregistrées", - "xpack.infra.logStreamEmbeddable.description": "Ajoutez un tableau de logs de diffusion en direct. Pour une expérience plus efficace, nous vous recommandons d'utiliser la page Découvrir pour créer une recherche enregistrée au lieu d'utiliser Logs Stream.", "xpack.infra.logStreamEmbeddable.displayName": "Logs Stream (déclassé)", "xpack.infra.logStreamEmbeddable.title": "Flux de log", "xpack.infra.logStreamPageTemplate.backtoLogsStream": "Retour au flux de logs", @@ -29111,15 +29058,10 @@ "xpack.ml.dataframe.analytics.create.resultsFieldHelpText": "Définissez le nom du champ dans lequel les résultats de l'analyse doivent être stockés. La valeur par défaut est ml.", "xpack.ml.dataframe.analytics.create.resultsFieldInputAriaLabel": "Nom du champ dans lequel les résultats de l'analyse doivent être stockés.", "xpack.ml.dataframe.analytics.create.resultsFieldLabel": "Champ de résultats", - "xpack.ml.dataframe.analytics.create.savedSearchLabel": "Recherche enregistrée", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabel": "Matrice de nuages de points", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabelHelpText": "Permet de visualiser les relations entre les paires de champs inclus sélectionnés.", - "xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutBody": "La recherche enregistrée \"{savedSearchTitle}\" utilise la vue de données \"{dataViewName}\".", "xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutTitle": "Les vues de données utilisant la recherche inter-clusters ne sont pas prises en charge.", - "xpack.ml.dataFrame.analytics.create.searchSelection.errorGettingDataViewTitle": "Erreur lors du chargement de la vue de données utilisée par la recherche enregistrée", - "xpack.ml.dataFrame.analytics.create.searchSelection.notFoundLabel": "Aucun recherche enregistrée ni aucun index correspondants n'ont été trouvés.", "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.dataView": "Vue de données", - "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.search": "Recherche enregistrée", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitInputAriaLabel": "Les arbres de décision dépassant cette profondeur sont pénalisés dans les calculs de perte.", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitLabel": "Limite de profondeur d'arborescence non stricte", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitText": "Les arbres de décision dépassant cette profondeur sont pénalisés dans les calculs de perte. Doit être supérieur ou égal à 0.", @@ -29412,7 +29354,6 @@ "xpack.ml.dataGridChart.notEnoughData": "0 document contient le champ.", "xpack.ml.dataGridChart.singleCategoryLegend": "{cardinality, plural, one {# catégorie} other {# catégories}}", "xpack.ml.dataGridChart.topCategoriesLegend": "Premières {maxChartColumns} des catégories {cardinality}", - "xpack.ml.dataSourceContext.errorTitle": "Impossible de récupérer la vue de données ou la recherche enregistrée", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationDescription": "La détection des anomalies ne s'exécute que sur des index temporels", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationTitle": "La vue de données {dataViewIndexPattern} n'est pas basée sur une série temporelle", "xpack.ml.dataViewUtils.createDataViewSwitchLabel": "Créer une vue de données", @@ -29655,7 +29596,6 @@ "xpack.ml.feature.reserved.description": "Pour accorder l'accès aux utilisateurs, vous devez également affecter le rôle machine_learning_user ou machine_learning_admin.", "xpack.ml.featureFeedbackButton.tellUsWhatYouThinkLink": "Dites-nous ce que vous pensez !", "xpack.ml.featureRegistry.mlFeatureName": "Machine Learning", - "xpack.ml.featureRegistry.privilegesTooltip": "L'octroi des privilèges de fonctionnalité Tout ou Lire au Machine Learning accordera également les privilèges de fonctionnalité équivalents à certains types d'objets Kibana enregistrés, à savoir les modèles d'indexation, les tableaux de bord, les recherches et visualisations enregistrées ainsi que les tâches de Machine Learning, les modèles entraînés et les objets de modules enregistrés.", "xpack.ml.fieldTypeIcon.booleanTypeAriaLabel": "type booléen", "xpack.ml.fieldTypeIcon.dateTypeAriaLabel": "type de données", "xpack.ml.fieldTypeIcon.geoPointTypeAriaLabel": "Type {geoPointParam}", @@ -30456,7 +30396,6 @@ "xpack.ml.newJob.recognize.running.startedAriaLabel": "Démarré", "xpack.ml.newJob.recognize.running.startFailedAriaLabel": "Échec du démarrage", "xpack.ml.newJob.recognize.runningLabel": "En cours d'exécution", - "xpack.ml.newJob.recognize.savedSearchPageTitle": "recherche enregistrée {savedSearchTitle}", "xpack.ml.newJob.recognize.saveJobOverrideLabel": "Enregistrer", "xpack.ml.newJob.recognize.searchesLabel": "Recherches", "xpack.ml.newJob.recognize.searchWillBeOverwrittenLabel": "La recherche sera écrasée", @@ -30465,7 +30404,6 @@ "xpack.ml.newJob.recognize.startDatafeedAfterSaveLabel": "Démarrer le flux de données après l'enregistrement", "xpack.ml.newJob.recognize.useDedicatedIndexLabel": "Utiliser l'index dédié", "xpack.ml.newJob.recognize.useFullDataLabel": "Utiliser l'ensemble des données {dataViewIndexPattern}", - "xpack.ml.newJob.recognize.usingSavedSearchDescription": "L'utilisation d'une recherche enregistrée signifie que la recherche utilisée dans les flux de données sera différente de celles par défaut que nous fournissons dans le module {moduleId}.", "xpack.ml.newJob.recognize.viewResultsAriaLabel": "Afficher les résultats", "xpack.ml.newJob.recognize.viewResultsLinkText": "Afficher les résultats", "xpack.ml.newJob.recognize.visualizationsLabel": "Visualisations", @@ -30485,7 +30423,6 @@ "xpack.ml.newJob.wizard.datafeedStep.dataView.description": "La vue de données actuellement utilisée pour cette tâche.", "xpack.ml.newJob.wizard.datafeedStep.dataView.step0.title": "Changer de vue de données", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.dataView": "Vue de données", - "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.noMatchingError": "Aucun recherche enregistrée ni aucun index correspondants n'ont été trouvés.", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.title": "Sélectionner une nouvelle vue de données pour la tâche", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.ApplyButton": "Appliquer", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.backButton": "Retour", @@ -30595,8 +30532,6 @@ "xpack.ml.newJob.wizard.jobType.rareAriaLabel": "Tâche rare", "xpack.ml.newJob.wizard.jobType.rareDescription": "Détectez les valeurs rares dans les données temporelles.", "xpack.ml.newJob.wizard.jobType.rareTitle": "Rare", - "xpack.ml.newJob.wizard.jobType.savedSearchPageTitleLabel": "recherche enregistrée {savedSearchTitle}", - "xpack.ml.newJob.wizard.jobType.selectDifferentIndexLinkText": "Sélectionnez une autre vue de données ou une autre recherche enregistrée.", "xpack.ml.newJob.wizard.jobType.singleMetricAriaLabel": "Tâche à indicateur unique", "xpack.ml.newJob.wizard.jobType.singleMetricDescription": "Détectez les anomalies dans une série temporelle unique.", "xpack.ml.newJob.wizard.jobType.singleMetricTitle": "Indicateur unique", @@ -30606,7 +30541,6 @@ "xpack.ml.newJob.wizard.jsonFlyout.autoSetJobCreatorTimeRange.error": "Erreur lors de la récupération des heures de début et de fin de l'index", "xpack.ml.newJob.wizard.jsonFlyout.closeButton": "Fermer", "xpack.ml.newJob.wizard.jsonFlyout.datafeed.title": "JSON de configuration du flux de données", - "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutText": "Vous ne pouvez pas altérer les index utilisés par le flux de données. Pour sélectionner une autre vue de données ou une autre recherche enregistrée, accédez à l’étape 1 de l’assistant et sélectionnez l’option permettant de changer de vue de données.", "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutTitle": "Les index ont été modifiés", "xpack.ml.newJob.wizard.jsonFlyout.job.title": "JSON de configuration de la tâche", "xpack.ml.newJob.wizard.jsonFlyout.saveButton": "Enregistrer", @@ -30738,10 +30672,7 @@ "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.title": "Restaurer le snapshot du modèle {ssId}", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.contents": "Tous les résultats de détection des anomalies postérieurs au {date} seront supprimés.", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.title": "Les données d'anomalie seront supprimées", - "xpack.ml.newJob.wizard.searchSelection.notFoundLabel": "Aucune vue de données ni recherche enregistrée correspondante détectée.", "xpack.ml.newJob.wizard.searchSelection.savedObjectType.dataView": "Vue de données", - "xpack.ml.newJob.wizard.searchSelection.savedObjectType.search": "Recherche enregistrée", - "xpack.ml.newJob.wizard.selectDataViewOrSavedSearch": "Sélectionner une vue de données ou une recherche enregistrée", "xpack.ml.newJob.wizard.shopValidationButton": "Ignorer la validation", "xpack.ml.newJob.wizard.step.configureDatafeedTitle": "Configurer le flux de données", "xpack.ml.newJob.wizard.step.jobDetailsTitle": "Détails de la tâche", @@ -30753,7 +30684,6 @@ "xpack.ml.newJob.wizard.stepComponentWrapper.jobDetailsTitle": "Détails de la tâche", "xpack.ml.newJob.wizard.stepComponentWrapper.pickFieldsTitle": "Choisir les champs", "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleDataView": "Nouvelle tâche de la vue de données {dataViewName}", - "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleSavedSearch": "Nouvelle tâche de la recherche enregistrée {title}", "xpack.ml.newJob.wizard.stepComponentWrapper.timeRangeTitle": "Plage temporelle", "xpack.ml.newJob.wizard.stepComponentWrapper.validationTitle": "Validation", "xpack.ml.newJob.wizard.summaryStep.convertToAdvancedButton": "Convertir en tâche avancée", @@ -37591,7 +37521,6 @@ "xpack.securitySolution.detectionEngine.body.summary.message": "La règle {ruleName} a généré {signalsCount} alertes", "xpack.securitySolution.detectionEngine.buttonManageRules": "Gérer les règles", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkActionConfirmationCloseButtonLabel": "Fermer", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmation.confirmButtonLabel": "Modifier {customRulesCount, plural, =1 {# règle personnalisée} other {# règles personnalisées}}", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmationCancelButtonLabel": "Annuler", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxHelpText": "Entrez le modèle des index Elasticsearch que vous souhaitez ajouter. Par défaut, le menu déroulant comprend des modèles d'indexation définis dans les paramètres avancés de la solution Security.", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxLabel": "Ajouter des modèles d'indexation pour les règles sélectionnées", @@ -37625,8 +37554,6 @@ "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setInvestigationFieldsWarningCallout": "Vous êtes sur le point d'écraser des champs en surbrillance personnalisés pour {rulesCount, plural, one {la règle sélectionnée} other {les # règles sélectionnées}}. Pour appliquer et enregistrer les modifications, cliquez sur Enregistrer.", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setTagsWarningCallout": "Vous êtes sur le point d'écraser les balises pour {rulesCount, plural, one {# règle sélectionnée} other {# règles sélectionnées}}. Sélectionnez Enregistrer pour appliquer les modifications.", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.tagsComoboxRequiredErrorMessage": "Au moins une balise est requise.", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkExportConfirmation.confirmButtonLabel": "Exporter {customRulesCount, plural, =1 {# règle personnalisée} other {# règles personnalisées}}", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkManualRuleRunConfirmation.confirmButtonLabel": "Planifier {customRulesCount, plural, =1 {# règle personnalisée} other {# règles personnalisées}}", "xpack.securitySolution.detectionEngine.components.allRules.bulkDeleteConfirmationTitle": "Confirmer la suppression groupée", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationCancel": "Annuler", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationConfirm": "Supprimer", @@ -37775,7 +37702,6 @@ "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.multiSelectFields.placeholderText": "Sélectionner un champ", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.placeholderText": "Sélectionner un champ", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsLabel": "Champs", - "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsMin": "Au moins un champ est requis.", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.referencesUrlInvalidError": "Le format de l’URL n’est pas valide.", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.resetDefaultIndicesButton": "Réinitialiser sur les modèles d'indexation par défaut", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.rulePreviewTitle": "Aperçu de la règle", @@ -38848,7 +38774,6 @@ "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addRuleActionsTitle": "Ajouter des actions sur les règles", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addTagsTitle": "Ajouter des balises", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.applyTimelineTemplateTitle": "Appliquer le modèle de chronologie", - "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkActionConfirmationPartlyTitle": "L'action peut être appliquée uniquement à {customRulesCount, plural, =1 {# règle personnalisée} other {# règles personnalisées}}", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditConfirmationDeniedTitle": "Impossible de modifier {rulesCount, plural, =1 {# règle} other {# règles}}.", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastDescription": "{rulesCount, plural, =1 {# règle est} other {# règles sont}} en cours de mise à jour.", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastNotifyButtonLabel": "M'envoyer une notification à la fin", @@ -39081,7 +39006,6 @@ "xpack.securitySolution.detectionEngine.userUnauthenticatedMsgBody": "Vous ne disposez pas des autorisations requises pour visualiser le moteur de détection. Pour une aide supplémentaire, contactez votre administrateur.", "xpack.securitySolution.detectionEngine.userUnauthenticatedTitle": "Autorisations de moteur de détection requises", "xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errMin": "La taille de la fenêtre d'historique doit être supérieure à 0.", - "xpack.securitySolution.detectionEngine.validations.stepDefineRule.newTermsFieldsMax": "Le nombre de champs doit être de 3 au maximum.", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityFieldFieldData.thresholdCardinalityFieldNotSuppliedMessage": "Un champ Cardinalité est requis.", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityValueFieldData.numberGreaterThanOrEqualOneErrorMessage": "La valeur doit être supérieure ou égale à un.", "xpack.securitySolution.detectionEngine.validations.thresholdFieldFieldData.arrayLengthGreaterThanMaxErrorMessage": "Le nombre de champs doit être de 3 au maximum.", @@ -42382,7 +42306,6 @@ "xpack.securitySolution.timelines.components.templateFilter.elasticTitle": "Modèles Elastic", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_error": "Erreur pendant l'enregistrement de la recherche Discover", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_unknown_error": "Erreur inconnue pendant l'enregistrement de la recherche Discover", - "xpack.securitySolution.timelines.discoverInTimeline.savedSearchTitle": "Recherche sauvegardée pour la chronologie – {title}", "xpack.securitySolution.timelines.newTemplateTimelineButtonLabel": "Créer un nouveau modèle de chronologie", "xpack.securitySolution.timelines.newTimelineButtonLabel": "Créer une nouvelle chronologie", "xpack.securitySolution.timelines.pageTitle": "Chronologies", @@ -44383,7 +44306,6 @@ "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.disabledTitle": "Rechercher les objets existants", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledText": "Utilisez cette option pour créer une ou plusieurs copies de l'objet dans le même espace.", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledTitle": "Créer de nouveaux objets avec des ID aléatoires", - "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.text": "Copier cet objet et ses objets associés. Pour les tableaux de bord, les visualisations associées, modèles d'indexation et recherches enregistrées sont également copiés.", "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.title": "Inclure les objets associés", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.disabledLabel": "Demander une action en cas de conflit", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.enabledLabel": "Écraser automatiquement les conflits", @@ -47156,15 +47078,12 @@ "xpack.transform.newTransform.chooseSourceTitle": "Choisir une source", "xpack.transform.newTransform.newTransformTitle": "Nouvelle transformation", "xpack.transform.newTransform.searchSelection.createADataView": "Créer une vue de données", - "xpack.transform.newTransform.searchSelection.notFoundLabel": "Aucun recherche enregistrée ni aucun index correspondants n'ont été trouvés.", "xpack.transform.newTransform.searchSelection.savedObjectType.dataView": "Vue de données", - "xpack.transform.newTransform.searchSelection.savedObjectType.search": "Recherche enregistrée", "xpack.transform.pivotPreview.copyClipboardTooltip": "Copier la déclaration Dev Console de l'aperçu de la transformation dans le presse-papiers.", "xpack.transform.pivotPreview.PivotPreviewIncompleteConfigCalloutBody": "Veuillez choisir au moins un champ Regrouper par et une agrégation.", "xpack.transform.pivotPreview.PivotPreviewNoDataCalloutBody": "La requête d'aperçu n'a renvoyé aucune donnée. Veuillez vous assurer que la requête facultative renvoie des données et que les valeurs existent pour le champ utilisé par le champ Regrouper par et le champ d'agrégation.", "xpack.transform.pivotPreview.transformPreviewTitle": "Aperçu de la transformation", "xpack.transform.progress": "Progression", - "xpack.transform.searchItems.errorInitializationTitle": "Une erreur s'est produite lors de l'initialisation de la vue de données Kibana ou de la recherche enregistrée.", "xpack.transform.statsBar.batchTransformsLabel": "Lot", "xpack.transform.statsBar.continuousTransformsLabel": "Continu", "xpack.transform.statsBar.failedTransformsLabel": "Échoué", @@ -47246,7 +47165,6 @@ "xpack.transform.stepDefineForm.runtimeEditorSwitchModalTitle": "Les modifications seront perdues", "xpack.transform.stepDefineForm.runtimeFieldsLabel": "Champs de temps d'exécution", "xpack.transform.stepDefineForm.runtimeFieldsListLabel": "{runtimeFields}", - "xpack.transform.stepDefineForm.savedSearchLabel": "Recherche enregistrée", "xpack.transform.stepDefineForm.searchFilterLabel": "Filtre de recherche", "xpack.transform.stepDefineForm.sortFieldOptionsEmptyError": "Aucun champ de date n'est disponible pour effectuer le tri. Pour utiliser un autre type de champ, copiez la configuration dans le presse-papiers et continuez à créer la transformation dans la Console.", "xpack.transform.stepDefineForm.sortHelpText": "Sélectionnez le champ de date à utiliser pour identifier le document le plus récent.", @@ -47259,7 +47177,6 @@ "xpack.transform.stepDefineSummary.groupByLabel": "Regrouper par", "xpack.transform.stepDefineSummary.queryCodeBlockLabel": "Recherche", "xpack.transform.stepDefineSummary.queryLabel": "Requête", - "xpack.transform.stepDefineSummary.savedSearchLabel": "Recherche enregistrée", "xpack.transform.stepDefineSummary.timeRangeLabel": "Plage temporelle", "xpack.transform.stepDetailsForm.advancedSettingsAccordionButtonContent": "Paramètres avancés", "xpack.transform.stepDetailsForm.continuousModeAriaLabel": "Choisissez un retard.", diff --git a/x-pack/platform/plugins/private/translations/translations/ja-JP.json b/x-pack/platform/plugins/private/translations/translations/ja-JP.json index b2bd6e25ec1f..225937ebae1b 100644 --- a/x-pack/platform/plugins/private/translations/translations/ja-JP.json +++ b/x-pack/platform/plugins/private/translations/translations/ja-JP.json @@ -1454,7 +1454,6 @@ "dashboard.emptyScreen.noPermissionsTitle": "このダッシュボードは空です。", "dashboard.emptyScreen.viewModeSubtitle": "編集モードに切り替えて、ビジュアライゼーションの追加を開始します。", "dashboard.emptyScreen.viewModeTitle": "ダッシュボードにビジュアライゼーションを追加", - "dashboard.featureCatalogue.dashboardDescription": "ビジュアライゼーションと保存された検索のコレクションの表示と共有を行います。", "dashboard.featureCatalogue.dashboardSubtitle": "ダッシュボードでデータを分析します。", "dashboard.featureCatalogue.dashboardTitle": "ダッシュボード", "dashboard.labs.enableLabsDescription": "このフラグはビューアーで[ラボ]ボタンを使用できるかどうかを決定します。ダッシュボードで実験的機能を有効および無効にするための簡単な方法です。", @@ -1581,7 +1580,6 @@ "data.advancedSettings.courier.requestPreferenceTitle": "リクエスト設定", "data.advancedSettings.defaultIndexText": "データビューが設定されていないときに、検索とビジュアライゼーションによって使用されます。", "data.advancedSettings.defaultIndexTitle": "デフォルトのデータビュー", - "data.advancedSettings.docTableHighlightText": "Discover と保存された検索ダッシュボードの結果をハイライトします。ハイライトすることで、大きなドキュメントを扱う際にリクエストが遅くなります。", "data.advancedSettings.docTableHighlightTitle": "結果をハイライト", "data.advancedSettings.histogram.barTargetText": "日付ヒストグラムで「自動」間隔を使用する際、この数に近いバケットの作成を試みます", "data.advancedSettings.histogram.barTargetTitle": "目標バケット数", @@ -2510,7 +2508,6 @@ "discover.advancedSettings.discover.showFieldStatisticsDescription": "{fieldStatisticsDocs}を有効にすると、数値フィールドの最大/最小値やジオフィールドの地図といった詳細が表示されます。この機能はベータ段階で、変更される可能性があります。", "discover.advancedSettings.discover.showMultifields": "マルチフィールドを表示", "discover.advancedSettings.discover.showMultifieldsDescription": "拡張ドキュメントビューに{multiFields}が表示されるかどうかを制御します。ほとんどの場合、マルチフィールドは元のフィールドと同じです。「searchFieldsFromSource」がオフのときにのみこのオプションを使用できます。", - "discover.advancedSettings.docTableHideTimeColumnText": "Discover と、ダッシュボードのすべての保存された検索で、「時刻」列を非表示にします。", "discover.advancedSettings.docTableHideTimeColumnTitle": "「時刻」列を非表示", "discover.advancedSettings.fieldsPopularLimitText": "最も頻繁に使用されるフィールドのトップNを表示します", "discover.advancedSettings.fieldsPopularLimitTitle": "頻繁に使用されるフィールドの制限", @@ -2522,7 +2519,6 @@ "discover.advancedSettings.sampleRowsPerPageTitle": "ページごとの行数", "discover.advancedSettings.sampleSizeText": "ドキュメントテーブル全体の最大行数を設定します。", "discover.advancedSettings.sampleSizeTitle": "テーブルごとの最大行数", - "discover.advancedSettings.searchOnPageLoadText": "Discover の最初の読み込み時に検索を実行するかを制御します。この設定は、保存された検索の読み込み時には影響しません。", "discover.advancedSettings.searchOnPageLoadTitle": "ページの読み込み時の検索", "discover.advancedSettings.sortDefaultOrderText": "Discover アプリのデータビューに基づく時刻のデフォルトの並べ替え方向をコントロールします。", "discover.advancedSettings.sortDefaultOrderTitle": "デフォルトの並べ替え方向", @@ -2532,7 +2528,6 @@ "discover.alerts.manageRulesAndConnectors": "ルールとコネクターの管理", "discover.alerts.missedTimeFieldToolTip": "データビューには時間フィールドがありません。", "discover.badge.readOnly.text": "読み取り専用", - "discover.badge.readOnly.tooltip": "検索を保存できません", "discover.context.breadcrumb": "周りのドキュメント", "discover.context.contextOfTitle": "#{anchorId}の周りのドキュメント", "discover.context.failedToLoadAnchorDocumentDescription": "アンカードキュメントの読み込みに失敗しました", @@ -2580,7 +2575,6 @@ "discover.dropZoneTableLabel": "フィールドを列として表に追加するには、ゾーンをドロップします", "discover.embeddable.inspectorRequestDescription": "このリクエストはElasticsearchにクエリーをかけ、検索データを取得します。", "discover.embeddable.search.dataViewError": "データビュー{indexPatternId}が見つかりません", - "discover.embeddable.search.displayName": "検索", "discover.errorCalloutESQLReferenceButtonLabel": "ES|QL参照を開く", "discover.errorCalloutShowErrorMessage": "詳細を表示", "discover.esqlMode.selectedColumnsCallout": "{esqlQueryColumnsNumber}フィールド中{selectedColumnsNumber}フィールドを表示中です。利用可能なフィールドリストからさらに追加します。", @@ -2589,7 +2583,6 @@ "discover.esqlToDataViewTransitionModal.feedbackLink": "ES|QLフィードバックを送信", "discover.esqlToDataViewTransitionModal.saveButtonLabel": "保存して切り替え", "discover.esqlToDataViewTransitionModal.title": "保存されていない変更", - "discover.esqlToDataviewTransitionModalBody": "データビューを切り替えると、現在のES|QLクエリが削除されます。作業が失われないようにするには、この検索を保存してください。", "discover.fieldChooser.availableFieldsTooltip": "フィールドをテーブルに表示できます。", "discover.fieldChooser.discoverField.addFieldTooltip": "フィールドを列として追加", "discover.fieldChooser.discoverField.removeFieldTooltip": "フィールドを表から削除", @@ -2617,19 +2610,10 @@ "discover.loadingDocuments": "ドキュメントを読み込み中", "discover.localMenu.alertsDescription": "アラート", "discover.localMenu.esqlTooltipLabel": "ES|QLはElasticの強力な新しいパイプクエリ言語です。", - "discover.localMenu.fallbackReportTitle": "無題のDiscover検索", "discover.localMenu.inspectTitle": "検査", "discover.localMenu.localMenu.alertsTitle": "アラート", - "discover.localMenu.localMenu.newSearchTitle": "新規", - "discover.localMenu.mustCopyOnSave": "Elasticはこの保存された検索を管理します。変更は新しい保存された検索に保存されます。", - "discover.localMenu.newSearchDescription": "新規検索", "discover.localMenu.openInspectorForSearchDescription": "検索用にインスペクターを開きます", - "discover.localMenu.openSavedSearchDescription": "保存された検索を開きます", - "discover.localMenu.openTitle": "開く", - "discover.localMenu.saveSaveSearchObjectType": "検索", - "discover.localMenu.saveSearchDescription": "検索を保存します", "discover.localMenu.saveTitle": "保存", - "discover.localMenu.shareSearchDescription": "検索を共有します", "discover.localMenu.shareTitle": "共有", "discover.localMenu.switchToClassicTitle": "クラシックに切り替える", "discover.localMenu.switchToClassicTooltipLabel": "KQLまたはLucene構文に切り替えます。", @@ -2695,8 +2679,6 @@ "discover.noResults.suggestion.tryText": "次の方法を試してください:", "discover.notifications.invalidTimeRangeText": "指定された時間範囲が無効です。(開始:''{from}''、終了:''{to}'')", "discover.notifications.invalidTimeRangeTitle": "無効な時間範囲", - "discover.notifications.notSavedSearchTitle": "検索''{savedSearchTitle}''は保存されませんでした。", - "discover.notifications.savedSearchTitle": "検索''{savedSearchTitle}''が保存されました。", "discover.pageTitleWithoutSavedSearch": "Discover - 検索は保存されていません", "discover.pageTitleWithSavedSearch": "Discover - {savedSearchTitle}", "discover.panelsToggle.hideChartButton": "グラフを非表示", @@ -2705,24 +2687,15 @@ "discover.panelsToggle.showSidebarButton": "サイドバーを表示", "discover.rootBreadcrumb": "Discover", "discover.sampleData.viewLinkLabel": "Discover", - "discover.savedSearch.savedObjectName": "保存検索", - "discover.savedSearchAliasMatchRedirect.objectNoun": "{savedSearch}検索", "discover.savedSearchEmbeddable.action.viewSavedSearch.displayName": "Discoverで開く", - "discover.savedSearchURLConflictCallout.objectNoun": "{savedSearch}検索", "discover.searchingTitle": "検索中", "discover.serverLocatorExtension.titleFromLocatorUnknown": "不明な検索", - "discover.share.shareModal.title": "この検索を共有", "discover.showingDefaultDataViewWarningDescription": "デフォルトデータビューを表示しています:\"{loadedDataViewTitle}\" ({loadedDataViewId})", "discover.showingSavedDataViewWarningDescription": "保存されたデータビューを表示しています:\"{ownDataViewTitle}\" ({ownDataViewId})", "discover.singleDocRoute.errorMessage": "ID {dataViewId}の一致するデータビューが見つかりません", "discover.singleDocRoute.errorTitle": "エラーが発生しました", "discover.skipToBottomButtonLabel": "テーブルの最後に移動", - "discover.topNav.managedContentLabel": "この保存された検索は、Elasticによって管理されます。この変更は、新しく保存された検索に保存する必要があります。", - "discover.topNav.openSearchPanel.manageSearchesButtonLabel": "検索の管理", - "discover.topNav.openSearchPanel.noSearchesFoundDescription": "一致する検索が見つかりませんでした。", - "discover.topNav.openSearchPanel.openSearchTitle": "検索を開く", "discover.topNav.saveModal.storeTimeWithSearchToggleDescription": "この検索を使用するときには、時間フィルターを更新し、現在の選択に合わせて間隔を更新します。", - "discover.topNav.saveModal.storeTimeWithSearchToggleLabel": "保存された検索で時間を保存", "discover.uninitializedRefreshButtonText": "データを更新", "discover.uninitializedText": "クエリーを作成、フィルターを追加、または[更新]をクリックして、現在のクエリーの結果を取得します。", "discover.uninitializedTitle": "検索開始", @@ -2794,7 +2767,6 @@ "embeddableApi.common.constants.grouping.annotations": "注釈とナビゲーション", "embeddableApi.common.constants.grouping.legacy": "レガシー", "embeddableApi.common.constants.grouping.other": "Other", - "embeddableApi.compatibility.defaultTypeDisplayName": "チャート", "embeddableApi.contextMenuTrigger.description": "新しいアクションがパネルのコンテキストメニューに追加されます", "embeddableApi.contextMenuTrigger.title": "コンテキストメニュー", "embeddableApi.errors.embeddableFactoryNotFound": "{type} を読み込めません。Elasticsearch と Kibanaのデフォルトのディストリビューションを適切なライセンスでアップグレードしてください。", @@ -2839,7 +2811,6 @@ "embeddableExamples.unifiedFieldList.displayName": "フィールドリスト", "embeddableExamples.unifiedFieldList.noDefaultDataViewErrorMessage": "フィールドリストは、1つ以上のデータビューで使用する必要があります。", "embeddableExamples.unifiedFieldList.selectDataViewMessage": "データビューを選択してください", - "esql.advancedSettings.enableESQLDescription": "この設定はKibanaのES|QLを有効にします。オフにすると、さまざまなアプリケーションからES|QLユーザーインターフェースが非表示になります。ただし、ユーザーは、既存のES|QLで保存された検索、ビジュアライゼーションなどにアクセスできます。", "esql.advancedSettings.enableESQLTitle": "ES|QLを有効化", "esql.triggers.updateEsqlQueryTrigger": "ES|QLクエリを更新", "esql.triggers.updateEsqlQueryTriggerDescription": "ES|QLクエリを新しいクエリで更新", @@ -5069,7 +5040,6 @@ "indexPatternManagement.editIndexPattern.source.table.matchesHeader": "一致", "indexPatternManagement.editIndexPattern.source.table.notMatchedLabel": "ソースフィルターが既知のフィールドと一致しません。", "indexPatternManagement.editIndexPattern.source.table.saveAria": "保存", - "indexPatternManagement.editIndexPattern.sourceLabel": "フィールドフィルターは、ドキュメントの取得時に 1 つまたは複数のフィールドを除外するのに使用される場合もあります。これは Discover アプリでのドキュメントの表示中、またはダッシュボードアプリの保存された検索の結果を表示する表で起こります。ドキュメントに大きなフィールドや重要ではないフィールドが含まれている場合、この程度の低いレベルでフィルターにより除外すると良いかもしれません。", "indexPatternManagement.editIndexPattern.sourcePlaceholder": "フィールドフィルター、ワイルドカード使用可(例:「user*」と入力して「user」で始まるフィールドをフィルタリング)", "indexPatternManagement.editIndexPattern.tabs.fieldsHeader": "フィールド", "indexPatternManagement.editIndexPattern.tabs.relationshipsHeader": "関係({count})", @@ -6547,9 +6517,7 @@ "savedObjectsManagement.view.inspectCodeEditorAriaLabel": "{ title }の検査", "savedObjectsManagement.view.inspectItemTitle": "{title}の検査", "savedObjectsManagement.view.savedObjectProblemErrorMessage": "この保存されたオブジェクトに問題があります", - "savedObjectsManagement.view.savedSearchDoesNotExistErrorMessage": "このオブジェクトに関連付けられた保存された検索は現在存在しません。", "savedObjectsManagement.view.viewItemButtonLabel": "{title}を表示", - "savedSearch.contentManagementType": "保存検索", "savedSearch.kibana_context.filters.help": "Kibana ジェネリックフィルターを指定します", "savedSearch.kibana_context.help": "Kibana グローバルコンテキストを更新します", "savedSearch.kibana_context.q.help": "自由形式の Kibana テキストクエリーを指定します", @@ -7170,6 +7138,14 @@ "securitySolutionPackages.alertSuppressionRuleDetails.upsell": "アラート非表示が構成されていますが、ライセンス不足のため適用されません", "securitySolutionPackages.alertSuppressionRuleForm.upsell": "アラートの非表示は、{requiredLicense}ライセンス以上で有効です", "securitySolutionPackages.beta.label": "ベータ", + "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "失敗", + "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "N/A", + "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "合格", + "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "検索失敗", + "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "クラウドセキュリティ態勢", + "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "調査結果", + "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "ルール", + "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "Cloud Native Vulnerability Management", "securitySolutionPackages.dataTable.ariaLabel": "アラート", "securitySolutionPackages.dataTable.columnHeaders.flyout.pane.removeColumnButtonLabel": "列を削除", "securitySolutionPackages.dataTable.eventRenderedView.eventSummary.column": "イベント概要", @@ -7498,6 +7474,7 @@ "share.urlService.redirect.RedirectManager.missingParamLocator": "ロケーターIDが指定されていません。URLで「l」検索パラメーターを指定します。これは既存のロケーターIDにしてください。", "share.urlService.redirect.RedirectManager.missingParamParams": "ロケーターパラメーターが指定されていません。URLで「p」検索パラメーターを指定します。これはロケーターパラメーターのJSONシリアル化オブジェクトにしてください。", "share.urlService.redirect.RedirectManager.missingParamVersion": "ロケーターパラメーターバージョンが指定されていません。URLで「v」検索パラメーターを指定します。これはロケーターパラメーターが生成されたときのKibanaのリリースバージョンです。", + "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "不明なエラー", "sharedUXPackages.buttonToolbar.buttons.addFromLibrary.libraryButtonLabel": "ライブラリから追加", "sharedUXPackages.buttonToolbar.toolbar.errorToolbarText": "120以上のボタンがあります。ボタンの数を制限することを検討してください。", "sharedUXPackages.card.noData.description": "Elasticエージェントを使用すると、シンプルで統一された方法でコンピューターからデータを収集するできます。", @@ -7949,8 +7926,6 @@ "unifiedDataTable.rowHeight.single": "単一", "unifiedDataTable.rowHeightLabel": "セル行高さ", "unifiedDataTable.sampleSizeSettings.sampleSizeLabel": "サンプルサイズ", - "unifiedDataTable.searchGenerationWithDescription": "検索{searchTitle}で生成されたテーブル", - "unifiedDataTable.searchGenerationWithDescriptionGrid": "検索{searchTitle}で生成されたテーブル({searchDescription})", "unifiedDataTable.selectAllDocs": "すべての{rowsCount}を選択", "unifiedDataTable.selectAllRowsOnPageColumnHeader": "すべての表示行を選択", "unifiedDataTable.selectColumnHeader": "列を選択", @@ -8521,11 +8496,6 @@ "visDefaultEditor.sidebar.errorButtonTooltip": "ハイライトされたフィールドのエラーを解決する必要があります。", "visDefaultEditor.sidebar.indexPatternAriaLabel": "インデックスパターン:{title}", "visDefaultEditor.sidebar.savedSearch.goToDiscoverButtonText": "Discover にこの検索を表示", - "visDefaultEditor.sidebar.savedSearch.linkButtonAriaLabel": "保存された検索へのリンク。クリックして詳細を確認するかリンクを解除します。", - "visDefaultEditor.sidebar.savedSearch.popoverHelpText": "保存したこの検索に今後加える修正は、ビジュアライゼーションに反映されます。自動更新を無効にするには、リンクを削除します。", - "visDefaultEditor.sidebar.savedSearch.popoverTitle": "保存された検索にリンクされています", - "visDefaultEditor.sidebar.savedSearch.titleAriaLabel": "保存された検索:{title}", - "visDefaultEditor.sidebar.savedSearch.unlinkSavedSearchButtonText": "保存された検索へのリンクを削除", "visDefaultEditor.sidebar.tabs.dataLabel": "データ", "visDefaultEditor.sidebar.tabs.optionsLabel": "オプション", "visDefaultEditor.sidebar.updateChartButtonLabel": "更新", @@ -9515,7 +9485,6 @@ "visualizations.helpMenu.appName": "Visualizeライブラリ", "visualizations.legacyCharts.conditionalMessage.noPermissions": "古いライブラリに切り替えるには、システム管理者に連絡してください。", "visualizations.legacyUrlConflict.objectNoun": "{visName}ビジュアライゼーション", - "visualizations.linkedToSearch.unlinkSuccessNotificationText": "保存された検索''{searchTitle}''からリンクが解除されました", "visualizations.listing.betaTitle": "ベータ", "visualizations.listing.betaTooltip": "このビジュアライゼーションはベータ段階で、変更される可能性があります。デザインとコードはオフィシャルGA機能よりも完成度が低く、現状のまま保証なしで提供されています。ベータ機能にはオフィシャルGA機能のSLAが適用されません", "visualizations.listing.breadcrumb": "Visualizeライブラリ", @@ -9548,9 +9517,7 @@ "visualizations.newVisWizard.learnMoreText": "詳細について", "visualizations.newVisWizard.newVisTypeTitle": "新規 {visTypeName}", "visualizations.newVisWizard.resultsFound": "{resultCount, plural, other {個のタイプ}} が見つかりました", - "visualizations.newVisWizard.searchSelection.notFoundLabel": "一致インデックスまたは保存した検索が見つかりません。", "visualizations.newVisWizard.searchSelection.savedObjectType.dataView": "データビュー", - "visualizations.newVisWizard.searchSelection.savedObjectType.search": "保存検索", "visualizations.newVisWizard.title": "新規ビジュアライゼーション", "visualizations.noDataView.label": "データビュー", "visualizations.noMatchRoute.bannerText": "Visualizeアプリケーションはこのルートを認識できません。{route}", @@ -9857,7 +9824,6 @@ "xpack.aiops.correlations.veryLowImpactText": "非常に低い", "xpack.aiops.dataGrid.field.documentCountChart.seriesLabel": "ドキュメントカウント", "xpack.aiops.dataGrid.field.documentCountChartSplit.seriesLabel": "他のドキュメントカウント", - "xpack.aiops.dataSourceContext.errorTitle": "データビューまたは保存された検索を取得できません", "xpack.aiops.dataViewNotBasedOnTimeSeriesWarning.title": "データビュー\"{dataViewTitle}\"は時系列に基づいていません。", "xpack.aiops.documentCountChart.baselineBadgeLabel": "ベースライン", "xpack.aiops.documentCountChart.deviationBadgeLabel": "偏差", @@ -12544,7 +12510,6 @@ "xpack.canvas.functions.savedMap.args.titleHelpText": "マップのタイトル", "xpack.canvas.functions.savedMap.args.zoomHelpText": "マップのズームレベル", "xpack.canvas.functions.savedMapHelpText": "保存されたマップオブジェクトの埋め込み可能なオブジェクトを返します。", - "xpack.canvas.functions.savedSearchHelpText": "保存検索オブジェクトの埋め込み可能なオブジェクトを返します", "xpack.canvas.functions.savedVisualization.args.colorsHelpText": "特定のシリーズに使用する色を指定します", "xpack.canvas.functions.savedVisualization.args.hideLegendHelpText": "凡例を非表示にするオプションを指定します", "xpack.canvas.functions.savedVisualization.args.idHelpText": "保存されたビジュアライゼーションオブジェクトのID", @@ -14507,7 +14472,6 @@ "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilities": "脆弱性", "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilityCount": "脆弱性", "xpack.csp.common.component.multiSelectFilter.searchWord": "検索", - "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "不明なエラー", "xpack.csp.compactFormattedNumber.naTitle": "N/A", "xpack.csp.complianceScoreBar.tooltipTitle": "{failed}が失敗し、{passed}が調査結果に合格しました", "xpack.csp.complianceScoreChart.counterButtonLink.failedFindingsTooltip": "失敗した調査結果", @@ -14522,9 +14486,6 @@ "xpack.csp.createPackagePolicy.customAssetsTab.rulesViewLabel": "CSPルールを表示", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityDashboardViewLabel": "CNVMダッシュボードを表示", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityFindingsViewLabel": "脆弱性の調査結果を表示", - "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "失敗", - "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "N/A", - "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "合格", "xpack.csp.cspIntegration.gcpCloudCredentials.cloudFormationSupportedMessage": "Launch Cloud ShellLaunch Cloud Formation for Automated Credentialsは、現在の統合バージョンではサポートされていません。Launch Cloud Shell for Automated Credentialsを有効化するには、最新バージョンにアップグレードしてください。", "xpack.csp.cspmIntegration.awsOption.benchmarkTitle": "CIS AWS", "xpack.csp.cspmIntegration.awsOption.nameTitle": "AWS", @@ -14607,7 +14568,6 @@ "xpack.csp.findings.distributionBar.totalPassedLabel": "合格した調査結果", "xpack.csp.findings.errorCallout.pageSearchErrorTitle": "検索結果の取得中にエラーが発生しました", "xpack.csp.findings.errorCallout.showErrorButtonLabel": "エラーメッセージを表示", - "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "検索失敗", "xpack.csp.findings.findingsFlyout.calloutTitle": "一部のフィールドは{vendor}によって提供されていません", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceId": "リソースID", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceName": "リソース名", @@ -14776,10 +14736,6 @@ "xpack.csp.kspmIntegration.integration.shortNameTitle": "KSPM", "xpack.csp.kspmIntegration.vanillaOption.benchmarkTitle": "CIS Kubernetes", "xpack.csp.kspmIntegration.vanillaOption.nameTitle": "自己管理", - "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "クラウドセキュリティ態勢", - "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "調査結果", - "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "ルール", - "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "Cloud Native Vulnerability Management", "xpack.csp.noFindingsStates.indexing.indexingButtonTitle": "態勢評価中", "xpack.csp.noFindingsStates.indexing.indexingDescription": "データの収集とインデックス作成を待機しています。結果を表示するには、しばらくたってから確認してください", "xpack.csp.noFindingsStates.indexTimeout.indexTimeoutDescription": "調査結果の収集に想定よりも時間がかかっています。{docs}。", @@ -15438,7 +15394,6 @@ "xpack.dataVisualizer.index.lensChart.countLabel": "カウント", "xpack.dataVisualizer.index.lensChart.maximumOfLabel": "{fieldName}の最大", "xpack.dataVisualizer.index.lensChart.topValuesLabel": "トップの値", - "xpack.dataVisualizer.index.savedSearchErrorMessage": "保存された検索{savedSearchId}の取得エラー", "xpack.dataVisualizer.multiSelectPicker.NoFiltersFoundMessage": "フィルターが見つかりません", "xpack.dataVisualizer.nameCollisionMsg": "「{name}」はすでに存在します。一意の名前を入力してください。", "xpack.dataVisualizer.noData": "データなし", @@ -19632,7 +19587,6 @@ "xpack.features.ossFeatures.discoverSearchSessionsFeatureName": "検索セッションの保存", "xpack.features.ossFeatures.discoverShortUrlSubFeatureName": "短い URL", "xpack.features.ossFeatures.discoverStoreSearchSessionsPrivilegeName": "検索セッションの保存", - "xpack.features.ossFeatures.reporting.dashboardDownloadCSV": "保存された検索パネルからCSVレポートを生成", "xpack.features.ossFeatures.reporting.dashboardGenerateScreenshot": "PDFまたはPNGレポートを生成", "xpack.features.ossFeatures.reporting.discoverGenerateCSV": "CSVレポートを生成", "xpack.features.ossFeatures.reporting.reportingTitle": "レポート", @@ -20618,7 +20572,6 @@ "xpack.fleet.epm.assetTitles.mlModules": "異常検知構成", "xpack.fleet.epm.assetTitles.osqueryPackAssets": "Osqueryパック", "xpack.fleet.epm.assetTitles.osquerySavedQuery": "Osqueryの保存されたクエリー", - "xpack.fleet.epm.assetTitles.savedSearches": "保存された検索", "xpack.fleet.epm.assetTitles.securityRules": "セキュリティルール", "xpack.fleet.epm.assetTitles.tag": "タグ", "xpack.fleet.epm.assetTitles.transforms": "トランスフォーム", @@ -22242,8 +22195,6 @@ "xpack.idxMgmt.goToDiscover.discoverIndexButtonLabel": "Discoverインデックス", "xpack.idxMgmt.goToDiscover.showIndexToolTip": "Discoverで{indexName}を表示", "xpack.idxMgmt.home.appTitle": "インデックス管理", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesDescription": "権限を確認中…", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesErrorMessage": "サーバーからユーザー特権を取得中にエラーが発生。", "xpack.idxMgmt.home.componentTemplates.confirmButtonLabel": "{numComponentTemplatesToDelete, plural, other {個のコンポーネントテンプレート} }を削除", "xpack.idxMgmt.home.componentTemplates.deleteModal.cancelButtonLabel": "キャンセル", "xpack.idxMgmt.home.componentTemplates.deleteModal.deleteDescription": "{numComponentTemplatesToDelete, plural, one {このコンポーネントテンプレート} other {これらのコンポーネントテンプレート} }を削除しようとしています。", @@ -22252,8 +22203,6 @@ "xpack.idxMgmt.home.componentTemplates.deleteModal.multipleErrorsNotificationMessageText": "{count}個のコンポーネントテンプレートの削除エラー", "xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteMultipleNotificationMessageText": "{numSuccesses, plural, other {# 個のコンポーネントテンプレート}}を削除しました", "xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteSingleNotificationMessageText": "コンポーネントテンプレート''{componentTemplateName}''を削除しました", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeDescription": "コンポーネントテンプレートを使用するには、{privilegesCount, plural, one {このクラスター特権} other {これらのクラスター特権}}が必要です:{missingPrivileges}。", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeTitle": "クラスターの権限が必要です", "xpack.idxMgmt.home.componentTemplates.emptyPromptButtonLabel": "コンポーネントテンプレートを作成", "xpack.idxMgmt.home.componentTemplates.emptyPromptDescription": "たとえば、インデックステンプレート全体で再利用できるインデックス設定のコンポーネントテンプレートを作成できます。", "xpack.idxMgmt.home.componentTemplates.emptyPromptDocumentionLink": "詳細情報", @@ -24194,8 +24143,6 @@ "xpack.infra.logsPage.toolbar.logFilterErrorToastTitle": "ログフィルターエラー", "xpack.infra.logsSettingsPage.loadingButtonLabel": "読み込み中", "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription": "ログストリームパネルは管理されていません。{savedSearchDocsLink}を同様の視覚化に活用してください。", - "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription.savedSearchesLinkLabel": "保存された検索", - "xpack.infra.logStreamEmbeddable.description": "ライブストリーミングログのテーブルを追加します。体験を効率化するために、ログストリームを使用するのではなく、検出ページを使用して、保存された検索を作成することをお勧めします。", "xpack.infra.logStreamEmbeddable.displayName": "ログストリーム(廃止予定)", "xpack.infra.logStreamEmbeddable.title": "ログストリーム", "xpack.infra.logStreamPageTemplate.backtoLogsStream": "ログストリームに戻る", @@ -28972,15 +28919,10 @@ "xpack.ml.dataframe.analytics.create.resultsFieldHelpText": "分析の結果を格納するフィールドの名前を定義します。デフォルトはmlです。", "xpack.ml.dataframe.analytics.create.resultsFieldInputAriaLabel": "分析の結果を格納するフィールドの名前。", "xpack.ml.dataframe.analytics.create.resultsFieldLabel": "結果フィールド", - "xpack.ml.dataframe.analytics.create.savedSearchLabel": "保存検索", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabel": "散布図マトリックス", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabelHelpText": "選択した分析対象フィールドのペアの間の関係を可視化します。", - "xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutBody": "保存された検索''{savedSearchTitle}''はデータビュー''{dataViewName}''を使用しています。", "xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutTitle": "クラスター横断検索を使用するデータビューはサポートされていません。", - "xpack.ml.dataFrame.analytics.create.searchSelection.errorGettingDataViewTitle": "保存された検索で使用されているデータビューの読み込みエラー", - "xpack.ml.dataFrame.analytics.create.searchSelection.notFoundLabel": "一致インデックスまたは保存した検索が見つかりません。", "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.dataView": "データビュー", - "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.search": "保存検索", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitInputAriaLabel": "この深さを超える決定木は、損失計算でペナルティがあります。", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitLabel": "ソフトツリー深さ上限値", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitText": "この深さを超える決定木は、損失計算でペナルティがあります。0以上でなければなりません。", @@ -29272,7 +29214,6 @@ "xpack.ml.dataGridChart.notEnoughData": "0個のドキュメントにフィールドが含まれます。", "xpack.ml.dataGridChart.singleCategoryLegend": "{cardinality, plural, other {# カテゴリ}}", "xpack.ml.dataGridChart.topCategoriesLegend": "上位 {maxChartColumns}/{cardinality} カテゴリ", - "xpack.ml.dataSourceContext.errorTitle": "データビューまたは保存された検索を取得できません", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationDescription": "異常検知は時間ベースのインデックスでのみ実行されます", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationTitle": "データビュー{dataViewIndexPattern}は時系列に基づいていません。", "xpack.ml.dataViewUtils.createDataViewSwitchLabel": "データビューを作成", @@ -29516,7 +29457,6 @@ "xpack.ml.feature.reserved.description": "ユーザーアクセスを許可するには、machine_learning_user か machine_learning_admin ロールのどちらかを割り当てる必要があります。", "xpack.ml.featureFeedbackButton.tellUsWhatYouThinkLink": "ご意見をお聞かせください。", "xpack.ml.featureRegistry.mlFeatureName": "機械学習", - "xpack.ml.featureRegistry.privilegesTooltip": "機械学習にすべてまたは読み取り機能権限を付与すると、特定のタイプのKibanaで保存されたオブジェクト(インデックスパターン、ダッシュボード、保存された検索、ビジュアライゼーション、機械学習ジョブ、学習済みモデル、モジュールで保存されたオブジェクト)にも同等の機能権限が付与されます。", "xpack.ml.fieldTypeIcon.booleanTypeAriaLabel": "ブールタイプ", "xpack.ml.fieldTypeIcon.dateTypeAriaLabel": "日付タイプ", "xpack.ml.fieldTypeIcon.geoPointTypeAriaLabel": "{geoPointParam} タイプ", @@ -30319,7 +30259,6 @@ "xpack.ml.newJob.recognize.running.startedAriaLabel": "開始", "xpack.ml.newJob.recognize.running.startFailedAriaLabel": "開始に失敗", "xpack.ml.newJob.recognize.runningLabel": "実行中", - "xpack.ml.newJob.recognize.savedSearchPageTitle": "saved search {savedSearchTitle}", "xpack.ml.newJob.recognize.saveJobOverrideLabel": "保存", "xpack.ml.newJob.recognize.searchesLabel": "検索", "xpack.ml.newJob.recognize.searchWillBeOverwrittenLabel": "検索は上書きされます", @@ -30328,7 +30267,6 @@ "xpack.ml.newJob.recognize.startDatafeedAfterSaveLabel": "保存後データフィードを開始", "xpack.ml.newJob.recognize.useDedicatedIndexLabel": "専用インデックスを使用", "xpack.ml.newJob.recognize.useFullDataLabel": "完全な{dataViewIndexPattern}データを使用", - "xpack.ml.newJob.recognize.usingSavedSearchDescription": "保存検索を使用すると、データフィードで使用されるクエリーが、{moduleId} モジュールでデフォルトで提供されるものと異なるものになります。", "xpack.ml.newJob.recognize.viewResultsAriaLabel": "結果を表示", "xpack.ml.newJob.recognize.viewResultsLinkText": "結果を表示", "xpack.ml.newJob.recognize.visualizationsLabel": "ビジュアライゼーション", @@ -30348,7 +30286,6 @@ "xpack.ml.newJob.wizard.datafeedStep.dataView.description": "現在このジョブで使用されているデータビュー。", "xpack.ml.newJob.wizard.datafeedStep.dataView.step0.title": "データビューを変更", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.dataView": "データビュー", - "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.noMatchingError": "一致インデックスまたは保存した検索が見つかりません。", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.title": "ジョブの新しいデータビューを選択", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.ApplyButton": "適用", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.backButton": "戻る", @@ -30458,8 +30395,6 @@ "xpack.ml.newJob.wizard.jobType.rareAriaLabel": "まれなジョブ", "xpack.ml.newJob.wizard.jobType.rareDescription": "時系列データでまれな値を検出します。", "xpack.ml.newJob.wizard.jobType.rareTitle": "ほとんどない", - "xpack.ml.newJob.wizard.jobType.savedSearchPageTitleLabel": "saved search {savedSearchTitle}", - "xpack.ml.newJob.wizard.jobType.selectDifferentIndexLinkText": "別のデータビューまたは保存された検索を選択", "xpack.ml.newJob.wizard.jobType.singleMetricAriaLabel": "シングルメトリックジョブ", "xpack.ml.newJob.wizard.jobType.singleMetricDescription": "単独の時系列の異常を検知します。", "xpack.ml.newJob.wizard.jobType.singleMetricTitle": "シングルメトリック", @@ -30469,7 +30404,6 @@ "xpack.ml.newJob.wizard.jsonFlyout.autoSetJobCreatorTimeRange.error": "インデックスの開始時刻と終了時刻の取得中にエラーが発生しました", "xpack.ml.newJob.wizard.jsonFlyout.closeButton": "閉じる", "xpack.ml.newJob.wizard.jsonFlyout.datafeed.title": "データフィード構成 JSON", - "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutText": "データフィードで使用されているインデックスはここで変更できません。別のデータビューまたは保存された検索を選択するには、ウィザードのステップ1に進み、[インデックスパターンを変更]オプションを選択します。", "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutTitle": "インデックスが変更されました", "xpack.ml.newJob.wizard.jsonFlyout.job.title": "ジョブ構成 JSON", "xpack.ml.newJob.wizard.jsonFlyout.saveButton": "保存", @@ -30601,10 +30535,7 @@ "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.title": "モデルスナップショット{ssId}に戻す", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.contents": "{date}後のすべての異常検知結果は削除されます。", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.title": "異常値データが削除されます", - "xpack.ml.newJob.wizard.searchSelection.notFoundLabel": "一致データビューまたは保存された検索が見つかりません。", "xpack.ml.newJob.wizard.searchSelection.savedObjectType.dataView": "データビュー", - "xpack.ml.newJob.wizard.searchSelection.savedObjectType.search": "保存検索", - "xpack.ml.newJob.wizard.selectDataViewOrSavedSearch": "データビューまたは保存された検索を選択", "xpack.ml.newJob.wizard.shopValidationButton": "検証をスキップ", "xpack.ml.newJob.wizard.step.configureDatafeedTitle": "データフィードの構成", "xpack.ml.newJob.wizard.step.jobDetailsTitle": "ジョブの詳細", @@ -30616,7 +30547,6 @@ "xpack.ml.newJob.wizard.stepComponentWrapper.jobDetailsTitle": "ジョブの詳細", "xpack.ml.newJob.wizard.stepComponentWrapper.pickFieldsTitle": "フィールドを選択", "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleDataView": "データビュー{dataViewName}の新しいジョブ", - "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleSavedSearch": "保存された検索 {title} からの新規ジョブ", "xpack.ml.newJob.wizard.stepComponentWrapper.timeRangeTitle": "時間範囲", "xpack.ml.newJob.wizard.stepComponentWrapper.validationTitle": "検証", "xpack.ml.newJob.wizard.summaryStep.convertToAdvancedButton": "高度なジョブに変換", @@ -37449,7 +37379,6 @@ "xpack.securitySolution.detectionEngine.body.summary.message": "ルール{ruleName}は{signalsCount}件のアラートを生成しました", "xpack.securitySolution.detectionEngine.buttonManageRules": "ルールの管理", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkActionConfirmationCloseButtonLabel": "閉じる", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmation.confirmButtonLabel": "{customRulesCount, plural, other {# 個のカスタムルール}}を編集", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmationCancelButtonLabel": "キャンセル", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxHelpText": "追加するElasticsearchインデックスのパターンを入力します。デフォルトでは、ドロップダウンには、セキュリティソリューション詳細設定で定義されたインデックスパターンが含まれます。", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxLabel": "選択したルールのインデックスパターンを追加", @@ -37483,8 +37412,6 @@ "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setInvestigationFieldsWarningCallout": "選択した{rulesCount, plural, other {#個のルール}}のカスタムハイライトされたフィールドを上書きしようとしています。変更を適用して、保存するには、[保存]をクリックします。", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setTagsWarningCallout": "{rulesCount, plural, other {# 個の選択したルール}}のタグを上書きしようとしています。[保存]をクリックすると、変更が適用されます。\n", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.tagsComoboxRequiredErrorMessage": "1つ以上のタグが必要です。", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkExportConfirmation.confirmButtonLabel": "{customRulesCount, plural, other {# 個のカスタムルール}}をエクスポート", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkManualRuleRunConfirmation.confirmButtonLabel": "{customRulesCount, plural, other {# 個のカスタムルール}}をスケジュール", "xpack.securitySolution.detectionEngine.components.allRules.bulkDeleteConfirmationTitle": "一括削除の確認", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationCancel": "キャンセル", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationConfirm": "削除", @@ -37633,7 +37560,6 @@ "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.multiSelectFields.placeholderText": "フィールドを選択", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.placeholderText": "フィールドを選択", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsLabel": "フィールド", - "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsMin": "1つ以上のフィールドが必要です。", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.referencesUrlInvalidError": "URLの形式が無効です", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.resetDefaultIndicesButton": "デフォルトインデックスパターンにリセット", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.rulePreviewTitle": "ルールプレビュー", @@ -38705,7 +38631,6 @@ "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addRuleActionsTitle": "ルールアクションを追加", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addTagsTitle": "タグを追加", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.applyTimelineTemplateTitle": "タイムラインテンプレートを適用", - "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkActionConfirmationPartlyTitle": "このアクションは、{customRulesCount, plural, other {#個のカスタムルール}}にのみ適用できます", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditConfirmationDeniedTitle": "{rulesCount, plural, other {# 個のルール}}を編集できません", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastDescription": "{rulesCount, plural, other {#個のルール}}を更新しています。", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastNotifyButtonLabel": "完了時に通知", @@ -38938,7 +38863,6 @@ "xpack.securitySolution.detectionEngine.userUnauthenticatedMsgBody": "検出エンジンを表示するための必要なアクセス権がありません。ヘルプについては、管理者にお問い合わせください。", "xpack.securitySolution.detectionEngine.userUnauthenticatedTitle": "検出エンジンアクセス権が必要です", "xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errMin": "履歴ウィンドウサイズは0よりも大きい値でなければなりません。", - "xpack.securitySolution.detectionEngine.validations.stepDefineRule.newTermsFieldsMax": "フィールド数は3以下でなければなりません。", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityFieldFieldData.thresholdCardinalityFieldNotSuppliedMessage": "カーディナリティフィールドは必須です。", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityValueFieldData.numberGreaterThanOrEqualOneErrorMessage": "値は 1 以上でなければなりません。", "xpack.securitySolution.detectionEngine.validations.thresholdFieldFieldData.arrayLengthGreaterThanMaxErrorMessage": "フィールド数は3以下でなければなりません。", @@ -42240,7 +42164,6 @@ "xpack.securitySolution.timelines.components.templateFilter.elasticTitle": "Elasticテンプレート", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_error": "Discover検索の保存エラー", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_unknown_error": "Discover検索の保存中に不明なエラーが発生しました", - "xpack.securitySolution.timelines.discoverInTimeline.savedSearchTitle": "タイムラインの保存された検索 - {title}", "xpack.securitySolution.timelines.newTemplateTimelineButtonLabel": "新規タイムラインテンプレートを作成", "xpack.securitySolution.timelines.newTimelineButtonLabel": "新規タイムラインを作成", "xpack.securitySolution.timelines.pageTitle": "タイムライン", @@ -44234,7 +44157,6 @@ "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.disabledTitle": "既存のオブジェクトを確認", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledText": "このオプションを使用すると、同じ場所でオブジェクトの1つ以上のコピーを作成します。", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledTitle": "ランダムIDで新しいオブジェクトを作成", - "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.text": "このオブジェクトと関連するオブジェクトをコピーします。ダッシュボードでは、関連するビジュアライゼーション、インデックスパターン、および保存された検索もコピーされます。", "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.title": "関連オブジェクトを含める", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.disabledLabel": "競合時にアクションを要求", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.enabledLabel": "自動的に競合を上書き", @@ -47006,15 +46928,12 @@ "xpack.transform.newTransform.chooseSourceTitle": "ソースの選択", "xpack.transform.newTransform.newTransformTitle": "新規トランスフォーム", "xpack.transform.newTransform.searchSelection.createADataView": "データビューを作成", - "xpack.transform.newTransform.searchSelection.notFoundLabel": "一致インデックスまたは保存した検索が見つかりません。", "xpack.transform.newTransform.searchSelection.savedObjectType.dataView": "データビュー", - "xpack.transform.newTransform.searchSelection.savedObjectType.search": "保存検索", "xpack.transform.pivotPreview.copyClipboardTooltip": "トランスフォームプレビューの開発コンソールステートメントをクリップボードにコピーします。", "xpack.transform.pivotPreview.PivotPreviewIncompleteConfigCalloutBody": "group-by フィールドと集約を 1 つ以上選んでください。", "xpack.transform.pivotPreview.PivotPreviewNoDataCalloutBody": "プレビューリクエストはデータを返しませんでした。オプションのクエリがデータを返し、グループ分け基準により使用されるフィールドと集約フィールドに値が存在することを確認してください。", "xpack.transform.pivotPreview.transformPreviewTitle": "トランスフォームプレビュー", "xpack.transform.progress": "進捗", - "xpack.transform.searchItems.errorInitializationTitle": "Kibanaデータビューまたは保存された検索を初期化するときにエラーが発生しました。", "xpack.transform.statsBar.batchTransformsLabel": "バッチ", "xpack.transform.statsBar.continuousTransformsLabel": "実行中", "xpack.transform.statsBar.failedTransformsLabel": "失敗", @@ -47095,7 +47014,6 @@ "xpack.transform.stepDefineForm.runtimeEditorSwitchModalTitle": "編集内容は失われます", "xpack.transform.stepDefineForm.runtimeFieldsLabel": "ランタイムフィールド", "xpack.transform.stepDefineForm.runtimeFieldsListLabel": "{runtimeFields}", - "xpack.transform.stepDefineForm.savedSearchLabel": "保存検索", "xpack.transform.stepDefineForm.searchFilterLabel": "検索フィルター", "xpack.transform.stepDefineForm.sortFieldOptionsEmptyError": "並べ替えの条件にする日付フィールドがありません。別のフィールド型を使用するには、構成をクリップボードにコピーして、コンソールでトランスフォームを作成し続けます。", "xpack.transform.stepDefineForm.sortHelpText": "最新のドキュメントを特定するために使用する日付フィールドを選択してます。", @@ -47108,7 +47026,6 @@ "xpack.transform.stepDefineSummary.groupByLabel": "グループ分けの条件", "xpack.transform.stepDefineSummary.queryCodeBlockLabel": "クエリー", "xpack.transform.stepDefineSummary.queryLabel": "クエリー", - "xpack.transform.stepDefineSummary.savedSearchLabel": "保存検索", "xpack.transform.stepDefineSummary.timeRangeLabel": "時間範囲", "xpack.transform.stepDetailsForm.advancedSettingsAccordionButtonContent": "高度な設定", "xpack.transform.stepDetailsForm.continuousModeAriaLabel": "遅延を選択してください。", diff --git a/x-pack/platform/plugins/private/translations/translations/zh-CN.json b/x-pack/platform/plugins/private/translations/translations/zh-CN.json index 479e9acd6a26..1de620535824 100644 --- a/x-pack/platform/plugins/private/translations/translations/zh-CN.json +++ b/x-pack/platform/plugins/private/translations/translations/zh-CN.json @@ -1467,7 +1467,6 @@ "dashboard.emptyScreen.noPermissionsTitle": "此仪表板是空的。", "dashboard.emptyScreen.viewModeSubtitle": "进入编辑模式,然后开始添加可视化。", "dashboard.emptyScreen.viewModeTitle": "将可视化添加到仪表板", - "dashboard.featureCatalogue.dashboardDescription": "显示和共享可视化和已保存搜索的集合。", "dashboard.featureCatalogue.dashboardSubtitle": "在仪表板中分析数据。", "dashboard.featureCatalogue.dashboardTitle": "仪表板", "dashboard.labs.enableLabsDescription": "此标志决定查看者是否有权访问用于在仪表板中快速启用和禁用技术预览功能的'实验'按钮。", @@ -1593,7 +1592,6 @@ "data.advancedSettings.courier.requestPreferenceTitle": "请求首选项", "data.advancedSettings.defaultIndexText": "未设置数据视图时,供 Discover 和可视化使用。", "data.advancedSettings.defaultIndexTitle": "默认数据视图", - "data.advancedSettings.docTableHighlightText": "在 Discover 和已保存搜索仪表板中突出显示结果。处理大文档时,突出显示会使请求变慢。", "data.advancedSettings.docTableHighlightTitle": "突出显示结果", "data.advancedSettings.histogram.barTargetText": "在日期和数值直方图中使用'auto'时间间隔时尝试生成大约此数目的存储桶", "data.advancedSettings.histogram.barTargetTitle": "目标存储桶", @@ -2501,7 +2499,6 @@ "discover.advancedSettings.discover.showFieldStatisticsDescription": "启用 {fieldStatisticsDocs} 以显示详细信息,如数字字段的最小和最大值,或地理字段的地图。此功能为公测版,可能会进行更改。", "discover.advancedSettings.discover.showMultifields": "显示多字段", "discover.advancedSettings.discover.showMultifieldsDescription": "控制 {multiFields} 是否显示在展开的文档视图中。多数情况下,多字段与原始字段相同。此选项仅在 `searchFieldsFromSource` 关闭时可用。", - "discover.advancedSettings.docTableHideTimeColumnText": "在 Discover 中和仪表板上的所有已保存搜索中隐藏'时间'列。", "discover.advancedSettings.docTableHideTimeColumnTitle": "隐藏'时间'列", "discover.advancedSettings.fieldsPopularLimitText": "要显示的排名前 N 最常见字段", "discover.advancedSettings.fieldsPopularLimitTitle": "常见字段限制", @@ -2513,7 +2510,6 @@ "discover.advancedSettings.sampleRowsPerPageTitle": "每页行数", "discover.advancedSettings.sampleSizeText": "设置整个文档表的最大行数。", "discover.advancedSettings.sampleSizeTitle": "每个表的最大行数", - "discover.advancedSettings.searchOnPageLoadText": "控制在 Discover 首次加载时是否执行搜索。加载已保存搜索时,此设置无效。", "discover.advancedSettings.searchOnPageLoadTitle": "在页面加载时搜索", "discover.advancedSettings.sortDefaultOrderText": "在 Discover 应用中控制基于时间的数据视图的默认排序方向。", "discover.advancedSettings.sortDefaultOrderTitle": "默认排序方向", @@ -2523,7 +2519,6 @@ "discover.alerts.manageRulesAndConnectors": "管理规则和连接器", "discover.alerts.missedTimeFieldToolTip": "数据视图没有时间字段。", "discover.badge.readOnly.text": "只读", - "discover.badge.readOnly.tooltip": "无法保存搜索", "discover.context.breadcrumb": "周围文档", "discover.context.contextOfTitle": "#{anchorId} 周围的文档", "discover.context.failedToLoadAnchorDocumentDescription": "无法加载定位点文档", @@ -2571,7 +2566,6 @@ "discover.dropZoneTableLabel": "放置区域以将字段作为列添加到表中", "discover.embeddable.inspectorRequestDescription": "此请求将查询 Elasticsearch 以获取搜索的数据。", "discover.embeddable.search.dataViewError": "缺少数据视图 {indexPatternId}", - "discover.embeddable.search.displayName": "搜索", "discover.errorCalloutESQLReferenceButtonLabel": "打开 ES|QL 参考", "discover.errorCalloutShowErrorMessage": "查看详情", "discover.esqlMode.selectedColumnsCallout": "正在显示 {selectedColumnsNumber} 个字段,共 {esqlQueryColumnsNumber} 个。从可用字段列表中添加更多字段。", @@ -2580,7 +2574,6 @@ "discover.esqlToDataViewTransitionModal.feedbackLink": "提交 ES|QL 反馈", "discover.esqlToDataViewTransitionModal.saveButtonLabel": "保存并切换", "discover.esqlToDataViewTransitionModal.title": "未保存的更改", - "discover.esqlToDataviewTransitionModalBody": "切换数据视图会移除当前的 ES|QL 查询。保存此搜索以避免丢失工作。", "discover.fieldChooser.availableFieldsTooltip": "适用于在表中显示的字段。", "discover.fieldChooser.discoverField.addFieldTooltip": "将字段添加为列", "discover.fieldChooser.discoverField.removeFieldTooltip": "从表中移除字段", @@ -2608,19 +2601,10 @@ "discover.loadingDocuments": "正在加载文档", "discover.localMenu.alertsDescription": "告警", "discover.localMenu.esqlTooltipLabel": "ES|QL 是 Elastic 支持的功能强大的全新管道查询语言。", - "discover.localMenu.fallbackReportTitle": "未命名 Discover 搜索", "discover.localMenu.inspectTitle": "检查", "discover.localMenu.localMenu.alertsTitle": "告警", - "discover.localMenu.localMenu.newSearchTitle": "新建", - "discover.localMenu.mustCopyOnSave": "Elastic 将管理此已保存搜索。将任何更改保存到新的已保存搜索。", - "discover.localMenu.newSearchDescription": "新搜索", "discover.localMenu.openInspectorForSearchDescription": "打开 Inspector 以进行搜索", - "discover.localMenu.openSavedSearchDescription": "打开已保存搜索", - "discover.localMenu.openTitle": "打开", - "discover.localMenu.saveSaveSearchObjectType": "搜索", - "discover.localMenu.saveSearchDescription": "保存搜索", "discover.localMenu.saveTitle": "保存", - "discover.localMenu.shareSearchDescription": "共享搜索", "discover.localMenu.shareTitle": "共享", "discover.localMenu.switchToClassicTitle": "切换到经典模式", "discover.localMenu.switchToClassicTooltipLabel": "切换到 KQL 或 Lucene 语法。", @@ -2693,22 +2677,13 @@ "discover.panelsToggle.showSidebarButton": "显示侧边栏", "discover.rootBreadcrumb": "Discover", "discover.sampleData.viewLinkLabel": "Discover", - "discover.savedSearch.savedObjectName": "已保存搜索", - "discover.savedSearchAliasMatchRedirect.objectNoun": "{savedSearch} 搜索", "discover.savedSearchEmbeddable.action.viewSavedSearch.displayName": "在 Discover 中打开", - "discover.savedSearchURLConflictCallout.objectNoun": "{savedSearch} 搜索", "discover.searchingTitle": "正在搜索", "discover.serverLocatorExtension.titleFromLocatorUnknown": "未知搜索", - "discover.share.shareModal.title": "共享此搜索", "discover.singleDocRoute.errorMessage": "没有与 ID {dataViewId} 相匹配的数据视图", "discover.singleDocRoute.errorTitle": "发生错误", "discover.skipToBottomButtonLabel": "转到表尾", - "discover.topNav.managedContentLabel": "此已保存搜索由 Elastic 托管。此处的更改必须保存到新的已保存搜索。", - "discover.topNav.openSearchPanel.manageSearchesButtonLabel": "管理搜索", - "discover.topNav.openSearchPanel.noSearchesFoundDescription": "未找到匹配的搜索。", - "discover.topNav.openSearchPanel.openSearchTitle": "打开搜索", "discover.topNav.saveModal.storeTimeWithSearchToggleDescription": "在使用此搜索时更新时间筛选并将时间间隔刷新到当前选择。", - "discover.topNav.saveModal.storeTimeWithSearchToggleLabel": "将时间与已保存搜索一起存储", "discover.uninitializedRefreshButtonText": "刷新数据", "discover.uninitializedText": "编写查询,添加一些筛选,或只需单击'刷新'来检索当前查询的结果。", "discover.uninitializedTitle": "开始搜索", @@ -2784,7 +2759,6 @@ "embeddableApi.common.constants.grouping.annotations": "标注和导航", "embeddableApi.common.constants.grouping.legacy": "旧版", "embeddableApi.common.constants.grouping.other": "其他", - "embeddableApi.compatibility.defaultTypeDisplayName": "图表", "embeddableApi.contextMenuTrigger.description": "会将一个新操作添加到该面板的上下文菜单", "embeddableApi.contextMenuTrigger.title": "上下文菜单", "embeddableApi.errors.embeddableFactoryNotFound": "{type} 无法加载。请升级到具有适当许可的默认 Elasticsearch 和 Kibana 分发。", @@ -2829,7 +2803,6 @@ "embeddableExamples.unifiedFieldList.displayName": "字段列表", "embeddableExamples.unifiedFieldList.noDefaultDataViewErrorMessage": "字段列表必须至少与一个存在的数据视图搭配使用", "embeddableExamples.unifiedFieldList.selectDataViewMessage": "请选择数据视图", - "esql.advancedSettings.enableESQLDescription": "此设置将在 Kibana 中启用 ES|QL。通过将其关闭,您将从各种应用程序中隐藏 ES|QL 用户界面。但是,用户将能够访问现有 ES|QL 已保存的搜索及可视化等。", "esql.advancedSettings.enableESQLTitle": "启用 ES|QL", "esql.triggers.updateEsqlQueryTrigger": "更新 ES|QL 查询", "esql.triggers.updateEsqlQueryTriggerDescription": "使用新查询更新 ES|QL 查询", @@ -5033,7 +5006,6 @@ "indexPatternManagement.editIndexPattern.source.table.matchesHeader": "匹配", "indexPatternManagement.editIndexPattern.source.table.notMatchedLabel": "源筛选不匹配任何已知字段。", "indexPatternManagement.editIndexPattern.source.table.saveAria": "保存", - "indexPatternManagement.editIndexPattern.sourceLabel": "字段筛选可用于在提取文档时排除一个或多个字段。在 Discover 应用中查看文档时会使用字段筛选,表在 Dashboard 应用中显示已保存搜索的结果时也会使用字段筛选。如果您的文档含有较大或不重要的字段,则通过在此较低层级筛除这些字段可能会更好。", "indexPatternManagement.editIndexPattern.sourcePlaceholder": "字段筛选,接受通配符(例如'user*'用于筛选以'user'开头的字段)", "indexPatternManagement.editIndexPattern.tabs.fieldsHeader": "字段", "indexPatternManagement.editIndexPattern.tabs.relationshipsHeader": "关系 ({count})", @@ -6493,8 +6465,6 @@ "savedObjectsManagement.view.inspectCodeEditorAriaLabel": "检查 { title }", "savedObjectsManagement.view.inspectItemTitle": "检查 {title}", "savedObjectsManagement.view.savedObjectProblemErrorMessage": "此已保存对象有问题", - "savedObjectsManagement.view.savedSearchDoesNotExistErrorMessage": "与此对象关联的已保存搜索已不存在。", - "savedSearch.contentManagementType": "已保存搜索", "savedSearch.kibana_context.filters.help": "指定 Kibana 常规筛选", "savedSearch.kibana_context.help": "更新 kibana 全局上下文", "savedSearch.kibana_context.q.help": "指定 Kibana 自由格式文本查询", @@ -7052,6 +7022,14 @@ "securitySolutionPackages.alertSuppressionRuleDetails.upsell": "已配置告警阻止,但由于许可不足而无法应用", "securitySolutionPackages.alertSuppressionRuleForm.upsell": "告警阻止通过{requiredLicense}或更高级许可证启用", "securitySolutionPackages.beta.label": "公测版", + "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "失败", + "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "不可用", + "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "通过", + "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "搜索失败", + "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "云安全态势", + "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "结果", + "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "规则", + "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "云原生漏洞管理", "securitySolutionPackages.dataTable.ariaLabel": "告警", "securitySolutionPackages.dataTable.columnHeaders.flyout.pane.removeColumnButtonLabel": "移除列", "securitySolutionPackages.dataTable.eventRenderedView.eventSummary.column": "事件摘要", @@ -7381,6 +7359,7 @@ "share.urlService.redirect.RedirectManager.missingParamLocator": "未指定定位器 ID。在 URL 中指定'l'搜索参数,其应为现有定位器 ID。", "share.urlService.redirect.RedirectManager.missingParamParams": "定位器参数未指定。在 URL 中指定'p'搜索参数,其应为定位器参数的 JSON 序列化对象。", "share.urlService.redirect.RedirectManager.missingParamVersion": "定位器参数版本未指定。在 URL 中指定'v'搜索参数,其应为生成定位器参数时 Kibana 的版本。", + "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "未知错误", "sharedUXPackages.buttonToolbar.buttons.addFromLibrary.libraryButtonLabel": "从库中添加", "sharedUXPackages.buttonToolbar.toolbar.errorToolbarText": "有 120 多个附加按钮。请考虑限制按钮数量。", "sharedUXPackages.card.noData.description": "使用 Elastic 代理以简单统一的方式从您的计算机中收集数据。", @@ -7826,8 +7805,6 @@ "unifiedDataTable.rowHeight.single": "单个", "unifiedDataTable.rowHeightLabel": "单元格行高", "unifiedDataTable.sampleSizeSettings.sampleSizeLabel": "样例大小", - "unifiedDataTable.searchGenerationWithDescription": "搜索 {searchTitle} 生成的表", - "unifiedDataTable.searchGenerationWithDescriptionGrid": "搜索 {searchTitle} 生成的表({searchDescription})", "unifiedDataTable.selectAllDocs": "选择所有 {rowsCount} 行", "unifiedDataTable.selectAllRowsOnPageColumnHeader": "选择所有可见行", "unifiedDataTable.selectColumnHeader": "选择列", @@ -8381,11 +8358,6 @@ "visDefaultEditor.sidebar.errorButtonTooltip": "需要解决突出显示的字段中的错误。", "visDefaultEditor.sidebar.indexPatternAriaLabel": "索引模式:{title}", "visDefaultEditor.sidebar.savedSearch.goToDiscoverButtonText": "在 Discover 中查看此搜索", - "visDefaultEditor.sidebar.savedSearch.linkButtonAriaLabel": "链接到已保存搜索。单击以了解详情或断开链接。", - "visDefaultEditor.sidebar.savedSearch.popoverHelpText": "对此已保存搜索的后续修改将反映在可视化中。要禁用自动更新,请移除该链接。", - "visDefaultEditor.sidebar.savedSearch.popoverTitle": "已链接到已保存搜索", - "visDefaultEditor.sidebar.savedSearch.titleAriaLabel": "已保存搜索:{title}", - "visDefaultEditor.sidebar.savedSearch.unlinkSavedSearchButtonText": "移除已保存搜索的链接", "visDefaultEditor.sidebar.tabs.dataLabel": "数据", "visDefaultEditor.sidebar.tabs.optionsLabel": "选项", "visDefaultEditor.sidebar.updateChartButtonLabel": "更新", @@ -9399,9 +9371,7 @@ "visualizations.newVisWizard.learnMoreText": "希望了解详情?", "visualizations.newVisWizard.newVisTypeTitle": "新建{visTypeName}", "visualizations.newVisWizard.resultsFound": "{resultCount, plural, other {类型}}已找到", - "visualizations.newVisWizard.searchSelection.notFoundLabel": "未找到匹配的索引或已保存搜索。", "visualizations.newVisWizard.searchSelection.savedObjectType.dataView": "数据视图", - "visualizations.newVisWizard.searchSelection.savedObjectType.search": "已保存搜索", "visualizations.newVisWizard.title": "新建可视化", "visualizations.noDataView.label": "数据视图", "visualizations.noMatchRoute.bannerText": "Visualize 应用程序无法识别此路由:{route}。", @@ -9694,7 +9664,6 @@ "xpack.aiops.correlations.veryLowImpactText": "极低", "xpack.aiops.dataGrid.field.documentCountChart.seriesLabel": "文档计数", "xpack.aiops.dataGrid.field.documentCountChartSplit.seriesLabel": "其他文档计数", - "xpack.aiops.dataSourceContext.errorTitle": "无法提取数据视图或已保存搜索", "xpack.aiops.documentCountChart.baselineBadgeLabel": "基线", "xpack.aiops.documentCountChart.deviationBadgeLabel": "偏差", "xpack.aiops.embeddableChangePointChart.dataViewLabel": "数据视图", @@ -12328,7 +12297,6 @@ "xpack.canvas.functions.savedMap.args.titleHelpText": "地图的标题", "xpack.canvas.functions.savedMap.args.zoomHelpText": "地图的缩放级别", "xpack.canvas.functions.savedMapHelpText": "返回已保存地图对象的可嵌入对象。", - "xpack.canvas.functions.savedSearchHelpText": "为已保存搜索对象返回可嵌入对象", "xpack.canvas.functions.savedVisualization.args.colorsHelpText": "定义用于特定序列的颜色", "xpack.canvas.functions.savedVisualization.args.hideLegendHelpText": "指定用于隐藏图例的选项", "xpack.canvas.functions.savedVisualization.args.idHelpText": "已保存可视化对象的 ID", @@ -14234,7 +14202,6 @@ "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilities": "漏洞", "xpack.csp.cnvmDashboardTable.section.topVulnerableResources.column.vulnerabilityCount": "漏洞", "xpack.csp.common.component.multiSelectFilter.searchWord": "搜索", - "sharedPlatformPackages.csp.common.utils.helpers.unknownError": "未知错误", "xpack.csp.compactFormattedNumber.naTitle": "不可用", "xpack.csp.complianceScoreBar.tooltipTitle": "{failed} 个失败和 {passed} 个通过的结果", "xpack.csp.complianceScoreChart.counterButtonLink.failedFindingsTooltip": "失败的结果", @@ -14249,9 +14216,6 @@ "xpack.csp.createPackagePolicy.customAssetsTab.rulesViewLabel": "查看 CSP 规则", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityDashboardViewLabel": "查看 CNVM 仪表板", "xpack.csp.createPackagePolicy.customAssetsTab.vulnerabilityFindingsViewLabel": "查看漏洞结果", - "securitySolutionPackages.csp.cspEvaluationBadge.failLabel": "失败", - "securitySolutionPackages.csp.cspEvaluationBadge.naLabel": "不可用", - "securitySolutionPackages.csp.cspEvaluationBadge.passLabel": "通过", "xpack.csp.cspIntegration.gcpCloudCredentials.cloudFormationSupportedMessage": "当前集成版本不支持为自动化凭据启动 Cloud Shell。请升级到最新版本以启用为自动化凭据启动 Cloud Shell。", "xpack.csp.cspmIntegration.awsOption.benchmarkTitle": "CIS AWS", "xpack.csp.cspmIntegration.awsOption.nameTitle": "AWS", @@ -14335,7 +14299,6 @@ "xpack.csp.findings.distributionBar.totalPassedLabel": "通过的结果", "xpack.csp.findings.errorCallout.pageSearchErrorTitle": "检索搜索结果时遇到问题", "xpack.csp.findings.errorCallout.showErrorButtonLabel": "显示错误消息", - "securitySolutionPackages.csp.findings.findingsErrorToast.searchFailedTitle": "搜索失败", "xpack.csp.findings.findingsFlyout.calloutTitle": "{vendor} 未提供某些字段", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceId": "资源 ID", "xpack.csp.findings.findingsFlyout.flyoutDescriptionList.resourceName": "资源名称", @@ -14505,10 +14468,6 @@ "xpack.csp.kspmIntegration.integration.shortNameTitle": "KSPM", "xpack.csp.kspmIntegration.vanillaOption.benchmarkTitle": "CIS Kubernetes", "xpack.csp.kspmIntegration.vanillaOption.nameTitle": "自管型", - "securitySolutionPackages.csp.navigation.dashboardNavItemLabel": "云安全态势", - "securitySolutionPackages.csp.navigation.findingsNavItemLabel": "结果", - "securitySolutionPackages.csp.navigation.rulesNavItemLabel": "规则", - "securitySolutionPackages.csp.navigation.vulnerabilityDashboardNavItemLabel": "云原生漏洞管理", "xpack.csp.noFindingsStates.indexing.indexingButtonTitle": "正进行态势评估", "xpack.csp.noFindingsStates.indexing.indexingDescription": "正在等待要收集和索引的数据。请稍后返回检查以查看结果", "xpack.csp.noFindingsStates.indexTimeout.indexTimeoutDescription": "收集结果所需的时间长于预期。{docs}。", @@ -15164,7 +15123,6 @@ "xpack.dataVisualizer.index.lensChart.countLabel": "计数", "xpack.dataVisualizer.index.lensChart.maximumOfLabel": "{fieldName} 的最大值", "xpack.dataVisualizer.index.lensChart.topValuesLabel": "排名最前值", - "xpack.dataVisualizer.index.savedSearchErrorMessage": "检索已保存搜索 {savedSearchId} 时出错", "xpack.dataVisualizer.multiSelectPicker.NoFiltersFoundMessage": "未找到任何筛选", "xpack.dataVisualizer.noData": "无数据", "xpack.dataVisualizer.randomSamplerPreference.offLabel": "关闭", @@ -19325,7 +19283,6 @@ "xpack.features.ossFeatures.discoverSearchSessionsFeatureName": "存储搜索会话", "xpack.features.ossFeatures.discoverShortUrlSubFeatureName": "短 URL", "xpack.features.ossFeatures.discoverStoreSearchSessionsPrivilegeName": "存储搜索会话", - "xpack.features.ossFeatures.reporting.dashboardDownloadCSV": "从已保存搜索面板生成 CSV 报告", "xpack.features.ossFeatures.reporting.dashboardGenerateScreenshot": "生成 PDF 或 PNG 报告", "xpack.features.ossFeatures.reporting.discoverGenerateCSV": "生成 CSV 报告", "xpack.features.ossFeatures.reporting.reportingTitle": "Reporting", @@ -20295,7 +20252,6 @@ "xpack.fleet.epm.assetTitles.mlModules": "异常检测配置", "xpack.fleet.epm.assetTitles.osqueryPackAssets": "Osquery 包", "xpack.fleet.epm.assetTitles.osquerySavedQuery": "Osquery 已保存查询", - "xpack.fleet.epm.assetTitles.savedSearches": "已保存的搜索", "xpack.fleet.epm.assetTitles.securityRules": "安全规则", "xpack.fleet.epm.assetTitles.tag": "标签", "xpack.fleet.epm.assetTitles.transforms": "转换", @@ -21885,16 +21841,12 @@ "xpack.idxMgmt.goToDiscover.discoverIndexButtonLabel": "Discover 索引", "xpack.idxMgmt.goToDiscover.showIndexToolTip": "在 Discover 中显示 {indexName}", "xpack.idxMgmt.home.appTitle": "索引管理", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesDescription": "正在检查权限……", - "xpack.idxMgmt.home.componentTemplates.checkingPrivilegesErrorMessage": "从服务器获取用户权限时出错。", "xpack.idxMgmt.home.componentTemplates.confirmButtonLabel": "删除{numComponentTemplatesToDelete, plural, other {组件模板} }", "xpack.idxMgmt.home.componentTemplates.deleteModal.cancelButtonLabel": "取消", "xpack.idxMgmt.home.componentTemplates.deleteModal.deleteDescription": "您即将删除{numComponentTemplatesToDelete, plural, other {以下组件模板} }:", "xpack.idxMgmt.home.componentTemplates.deleteModal.modalTitleText": "删除{numComponentTemplatesToDelete, plural, one {组件模板} other { # 个组件模板}}", "xpack.idxMgmt.home.componentTemplates.deleteModal.multipleErrorsNotificationMessageText": "删除 {count} 个组件模板时出错", "xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteMultipleNotificationMessageText": "已删除 {numSuccesses, plural, other {# 个组件模板}}", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeDescription": "要使用'组件模板',必须具有{privilegesCount, plural, other {以下集群权限}}:{missingPrivileges}。", - "xpack.idxMgmt.home.componentTemplates.deniedPrivilegeTitle": "需要集群权限", "xpack.idxMgmt.home.componentTemplates.emptyPromptButtonLabel": "创建组件模板", "xpack.idxMgmt.home.componentTemplates.emptyPromptDescription": "例如,您可以为可在多个索引模板上重复使用的索引设置创建组件模板。", "xpack.idxMgmt.home.componentTemplates.emptyPromptDocumentionLink": "了解详情。", @@ -23808,8 +23760,6 @@ "xpack.infra.logsPage.toolbar.logFilterErrorToastTitle": "日志筛选错误", "xpack.infra.logsSettingsPage.loadingButtonLabel": "正在加载", "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription": "将不再维护日志流面板。尝试将 {savedSearchDocsLink} 用于类似可视化。", - "xpack.infra.logsStreamEmbeddable.deprecationWarningDescription.savedSearchesLinkLabel": "已保存的搜索", - "xpack.infra.logStreamEmbeddable.description": "添加实时流式传输日志的表。为了获得更高效的体验,建议使用 Discover 页面创建已保存搜索,而不是使用日志流。", "xpack.infra.logStreamEmbeddable.displayName": "日志流(已过时)", "xpack.infra.logStreamEmbeddable.title": "日志流", "xpack.infra.logStreamPageTemplate.backtoLogsStream": "返回到日志流", @@ -28501,14 +28451,10 @@ "xpack.ml.dataframe.analytics.create.resultsFieldHelpText": "定义用于存储分析结果的字段的名称。默认为 ml。", "xpack.ml.dataframe.analytics.create.resultsFieldInputAriaLabel": "用于存储分析结果的字段的名称。", "xpack.ml.dataframe.analytics.create.resultsFieldLabel": "结果字段", - "xpack.ml.dataframe.analytics.create.savedSearchLabel": "已保存搜索", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabel": "散点图矩阵", "xpack.ml.dataframe.analytics.create.scatterplotMatrixLabelHelpText": "可视化选定包括字段对之间的关系。", "xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutTitle": "不支持使用跨集群搜索的数据视图。", - "xpack.ml.dataFrame.analytics.create.searchSelection.errorGettingDataViewTitle": "加载已保存搜索所使用的数据视图时出错", - "xpack.ml.dataFrame.analytics.create.searchSelection.notFoundLabel": "未找到匹配的索引或已保存搜索。", "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.dataView": "数据视图", - "xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.search": "已保存搜索", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitInputAriaLabel": "超过此深度的决策树将在损失计算中被罚分。", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitLabel": "软性树深度限制", "xpack.ml.dataframe.analytics.create.softTreeDepthLimitText": "超过此深度的决策树将在损失计算中被罚分。必须大于或等于 0。", @@ -28797,7 +28743,6 @@ "xpack.ml.dataGridChart.notEnoughData": "0 个文档包含字段。", "xpack.ml.dataGridChart.singleCategoryLegend": "{cardinality, plural, other {# 个类别}}", "xpack.ml.dataGridChart.topCategoriesLegend": "{cardinality} 个类别中的排名前 {maxChartColumns} 个", - "xpack.ml.dataSourceContext.errorTitle": "无法提取数据视图或已保存搜索", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationDescription": "仅针对基于时间的索引运行异常检测", "xpack.ml.dataViewNotBasedOnTimeSeriesNotificationTitle": "数据视图 {dataViewIndexPattern} 并非基于时间序列", "xpack.ml.dataViewUtils.createDataViewSwitchLabel": "创建数据视图", @@ -29040,7 +28985,6 @@ "xpack.ml.feature.reserved.description": "要向用户授予访问权限,还应分配 machine_learning_user 或 machine_learning_admin 角色。", "xpack.ml.featureFeedbackButton.tellUsWhatYouThinkLink": "告诉我们您的看法!", "xpack.ml.featureRegistry.mlFeatureName": "Machine Learning", - "xpack.ml.featureRegistry.privilegesTooltip": "为 Machine Learning 授予所有或读取功能权限还会向某些类型的 Kibana 已保存对象(即索引模式、仪表板、已保存搜索和可视化,以及 Machine Learning 作业、已训练模型和模块已保存对象)授予对等功能权限。", "xpack.ml.fieldTypeIcon.booleanTypeAriaLabel": "布尔类型", "xpack.ml.fieldTypeIcon.dateTypeAriaLabel": "日期类型", "xpack.ml.fieldTypeIcon.geoPointTypeAriaLabel": "{geoPointParam} 类型", @@ -29842,7 +29786,6 @@ "xpack.ml.newJob.recognize.running.startedAriaLabel": "已启动", "xpack.ml.newJob.recognize.running.startFailedAriaLabel": "启动失败", "xpack.ml.newJob.recognize.runningLabel": "正在运行", - "xpack.ml.newJob.recognize.savedSearchPageTitle": "已保存搜索 {savedSearchTitle}", "xpack.ml.newJob.recognize.saveJobOverrideLabel": "保存", "xpack.ml.newJob.recognize.searchesLabel": "搜索", "xpack.ml.newJob.recognize.searchWillBeOverwrittenLabel": "搜索将被覆盖", @@ -29851,7 +29794,6 @@ "xpack.ml.newJob.recognize.startDatafeedAfterSaveLabel": "保存后启动数据馈送", "xpack.ml.newJob.recognize.useDedicatedIndexLabel": "使用专用索引", "xpack.ml.newJob.recognize.useFullDataLabel": "使用完整的 {dataViewIndexPattern} 数据", - "xpack.ml.newJob.recognize.usingSavedSearchDescription": "使用已保存搜索意味着在数据馈送中使用的查询会与我们在 {moduleId} 模块中提供的默认查询不同。", "xpack.ml.newJob.recognize.viewResultsAriaLabel": "查看结果", "xpack.ml.newJob.recognize.viewResultsLinkText": "查看结果", "xpack.ml.newJob.recognize.visualizationsLabel": "可视化", @@ -29871,7 +29813,6 @@ "xpack.ml.newJob.wizard.datafeedStep.dataView.description": "当前用于此作业的数据视图。", "xpack.ml.newJob.wizard.datafeedStep.dataView.step0.title": "更改数据视图", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.dataView": "数据视图", - "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.noMatchingError": "未找到匹配的索引或已保存搜索。", "xpack.ml.newJob.wizard.datafeedStep.dataView.step1.title": "为该作业选择新数据视图", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.ApplyButton": "应用", "xpack.ml.newJob.wizard.datafeedStep.dataView.step2.backButton": "返回", @@ -29981,8 +29922,6 @@ "xpack.ml.newJob.wizard.jobType.rareAriaLabel": "罕见作业", "xpack.ml.newJob.wizard.jobType.rareDescription": "检测时间序列数据中的罕见值。", "xpack.ml.newJob.wizard.jobType.rareTitle": "极少", - "xpack.ml.newJob.wizard.jobType.savedSearchPageTitleLabel": "已保存搜索 {savedSearchTitle}", - "xpack.ml.newJob.wizard.jobType.selectDifferentIndexLinkText": "选择不同数据视图或已保存搜索", "xpack.ml.newJob.wizard.jobType.singleMetricAriaLabel": "单一指标作业", "xpack.ml.newJob.wizard.jobType.singleMetricDescription": "检测单个时序中的异常。", "xpack.ml.newJob.wizard.jobType.singleMetricTitle": "单一指标", @@ -29992,7 +29931,6 @@ "xpack.ml.newJob.wizard.jsonFlyout.autoSetJobCreatorTimeRange.error": "检索索引的开始和结束时间时出错", "xpack.ml.newJob.wizard.jsonFlyout.closeButton": "关闭", "xpack.ml.newJob.wizard.jsonFlyout.datafeed.title": "数据馈送配置 JSON", - "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutText": "在此处无法更改数据馈送正在使用的索引。要选择不同数据视图或已保存搜索,请前往向导的第 1 步,然后选择更改数据视图选项。", "xpack.ml.newJob.wizard.jsonFlyout.indicesChange.calloutTitle": "索引已更改", "xpack.ml.newJob.wizard.jsonFlyout.job.title": "作业配置 JSON", "xpack.ml.newJob.wizard.jsonFlyout.saveButton": "保存", @@ -30123,10 +30061,7 @@ "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.title": "恢复到模型快照 {ssId}", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.contents": "将删除 {date} 后的所有异常检测结果。", "xpack.ml.newJob.wizard.revertModelSnapshotFlyout.warningCallout.title": "将删除异常数据", - "xpack.ml.newJob.wizard.searchSelection.notFoundLabel": "未找到匹配的数据视图或已保存搜索。", "xpack.ml.newJob.wizard.searchSelection.savedObjectType.dataView": "数据视图", - "xpack.ml.newJob.wizard.searchSelection.savedObjectType.search": "已保存搜索", - "xpack.ml.newJob.wizard.selectDataViewOrSavedSearch": "选择数据视图或已保存搜索", "xpack.ml.newJob.wizard.shopValidationButton": "跳过验证", "xpack.ml.newJob.wizard.step.configureDatafeedTitle": "配置数据馈送", "xpack.ml.newJob.wizard.step.jobDetailsTitle": "作业详情", @@ -30138,7 +30073,6 @@ "xpack.ml.newJob.wizard.stepComponentWrapper.jobDetailsTitle": "作业详情", "xpack.ml.newJob.wizard.stepComponentWrapper.pickFieldsTitle": "选择字段", "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleDataView": "从数据视图 {dataViewName} 新建作业", - "xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleSavedSearch": "从已保存搜索 {title} 新建作业", "xpack.ml.newJob.wizard.stepComponentWrapper.timeRangeTitle": "时间范围", "xpack.ml.newJob.wizard.stepComponentWrapper.validationTitle": "验证", "xpack.ml.newJob.wizard.summaryStep.convertToAdvancedButton": "转换成高级作业", @@ -36878,7 +36812,6 @@ "xpack.securitySolution.detectionEngine.body.summary.message": "规则 {ruleName} 生成了 {signalsCount} 个告警", "xpack.securitySolution.detectionEngine.buttonManageRules": "管理规则", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkActionConfirmationCloseButtonLabel": "关闭", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmation.confirmButtonLabel": "编辑 {customRulesCount, plural, other {# 个定制规则}}", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmationCancelButtonLabel": "取消", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxHelpText": "输入要添加的 Elasticsearch 索引的模式。默认情况下,下拉列表将包括 Security Solution 高级设置中定义的索引模式。", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.addIndexPatternsComboboxLabel": "为选定规则添加索引模式", @@ -36912,8 +36845,6 @@ "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setInvestigationFieldsWarningCallout": "您即将覆盖选定的 {rulesCount, plural, other {# 个规则}}的突出显示的定制字段。要应用并保存更改,请单击'保存'。", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.setTagsWarningCallout": "您即将覆盖 {rulesCount, plural, other {# 个选定规则}}的标签,按'保存'可应用更改。", "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditFlyoutForm.tagsComoboxRequiredErrorMessage": "至少需要一个标签。", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkExportConfirmation.confirmButtonLabel": "导出 {customRulesCount, plural, other {# 个定制规则}}", - "xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkManualRuleRunConfirmation.confirmButtonLabel": "计划 {customRulesCount, plural, other {# 个定制规则}}", "xpack.securitySolution.detectionEngine.components.allRules.bulkDeleteConfirmationTitle": "确认批量删除", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationCancel": "取消", "xpack.securitySolution.detectionEngine.components.allRules.deleteConfirmationConfirm": "删除", @@ -37061,7 +36992,6 @@ "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.multiSelectFields.placeholderText": "选择字段", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.placeholderText": "选择字段", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsLabel": "字段", - "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsMin": "至少需要一个字段。", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.referencesUrlInvalidError": "URL 的格式无效", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.resetDefaultIndicesButton": "重置为默认索引模式", "xpack.securitySolution.detectionEngine.createRule.stepDefineRule.rulePreviewTitle": "规则预览", @@ -38131,7 +38061,6 @@ "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addRuleActionsTitle": "添加规则操作", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.addTagsTitle": "添加标签", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.applyTimelineTemplateTitle": "应用时间线模板", - "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkActionConfirmationPartlyTitle": "只能对 {customRulesCount, plural, other {# 个定制规则}}应用此操作", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditConfirmationDeniedTitle": "无法编辑 {rulesCount, plural, other {# 个规则}}", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastDescription": "{rulesCount, plural, other {# 个规则}}正在更新。", "xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkEditWarningToastNotifyButtonLabel": "在完成时通知我", @@ -38361,7 +38290,6 @@ "xpack.securitySolution.detectionEngine.userUnauthenticatedMsgBody": "您没有所需的权限,无法查看检测引擎。若需要更多帮助,请联系您的管理员。", "xpack.securitySolution.detectionEngine.userUnauthenticatedTitle": "需要检测引擎权限", "xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errMin": "历史记录窗口大小必须大于 0。", - "xpack.securitySolution.detectionEngine.validations.stepDefineRule.newTermsFieldsMax": "字段数目不得超过 3 个。", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityFieldFieldData.thresholdCardinalityFieldNotSuppliedMessage": "基数字段必填。", "xpack.securitySolution.detectionEngine.validations.thresholdCardinalityValueFieldData.numberGreaterThanOrEqualOneErrorMessage": "值必须大于或等于 1。", "xpack.securitySolution.detectionEngine.validations.thresholdFieldFieldData.arrayLengthGreaterThanMaxErrorMessage": "字段数目不得超过 3 个。", @@ -41627,7 +41555,6 @@ "xpack.securitySolution.timelines.components.templateFilter.elasticTitle": "Elastic 模板", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_error": "保存 Discover 搜索时出错", "xpack.securitySolution.timelines.discoverInTimeline.save_saved_search_unknown_error": "保存 Discover 搜索时出现未知错误", - "xpack.securitySolution.timelines.discoverInTimeline.savedSearchTitle": "时间线的已保存搜索 - {title}", "xpack.securitySolution.timelines.newTemplateTimelineButtonLabel": "创建新时间线模板", "xpack.securitySolution.timelines.newTimelineButtonLabel": "创建新时间线", "xpack.securitySolution.timelines.pageTitle": "时间线", @@ -43587,7 +43514,6 @@ "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.disabledTitle": "检查现有对象", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledText": "使用此选项可在相同的工作区中创建该对象的一个或多个副本。", "xpack.spaces.management.copyToSpace.copyModeControl.createNewCopies.enabledTitle": "使用随机 ID 创建新对象", - "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.text": "复制此对象及其相关对象。对于仪表板,还将复制相关可视化、索引模式和已保存的搜索。", "xpack.spaces.management.copyToSpace.copyModeControl.includeRelated.title": "包括相关对象", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.disabledLabel": "冲突时请求操作", "xpack.spaces.management.copyToSpace.copyModeControl.overwrite.enabledLabel": "自动覆盖冲突", @@ -46315,15 +46241,12 @@ "xpack.transform.newTransform.chooseSourceTitle": "选择源", "xpack.transform.newTransform.newTransformTitle": "新转换", "xpack.transform.newTransform.searchSelection.createADataView": "创建数据视图", - "xpack.transform.newTransform.searchSelection.notFoundLabel": "未找到匹配的索引或已保存搜索。", "xpack.transform.newTransform.searchSelection.savedObjectType.dataView": "数据视图", - "xpack.transform.newTransform.searchSelection.savedObjectType.search": "已保存搜索", "xpack.transform.pivotPreview.copyClipboardTooltip": "将转换预览的开发控制台语句复制到剪贴板。", "xpack.transform.pivotPreview.PivotPreviewIncompleteConfigCalloutBody": "请至少选择一个分组依据字段和聚合。", "xpack.transform.pivotPreview.PivotPreviewNoDataCalloutBody": "预览请求未返回任何数据。请确保可选查询返回数据且分组依据和聚合字段使用的字段的值存在。", "xpack.transform.pivotPreview.transformPreviewTitle": "转换预览", "xpack.transform.progress": "进度", - "xpack.transform.searchItems.errorInitializationTitle": "初始化 Kibana 数据视图或已保存搜索时发生错误。", "xpack.transform.statsBar.batchTransformsLabel": "批量", "xpack.transform.statsBar.continuousTransformsLabel": "连续", "xpack.transform.statsBar.failedTransformsLabel": "失败", @@ -46400,7 +46323,6 @@ "xpack.transform.stepDefineForm.runtimeEditorSwitchModalTitle": "编辑将会丢失", "xpack.transform.stepDefineForm.runtimeFieldsLabel": "运行时字段", "xpack.transform.stepDefineForm.runtimeFieldsListLabel": "{runtimeFields}", - "xpack.transform.stepDefineForm.savedSearchLabel": "已保存搜索", "xpack.transform.stepDefineForm.searchFilterLabel": "搜索筛选", "xpack.transform.stepDefineForm.sortFieldOptionsEmptyError": "没有日期字段可用于排序。要使用其他字段类型,请将配置复制到剪贴板,然后继续在控制台中创建转换。", "xpack.transform.stepDefineForm.sortHelpText": "选择要用于标识最新文档的日期字段。", @@ -46413,7 +46335,6 @@ "xpack.transform.stepDefineSummary.groupByLabel": "分组依据", "xpack.transform.stepDefineSummary.queryCodeBlockLabel": "查询", "xpack.transform.stepDefineSummary.queryLabel": "查询", - "xpack.transform.stepDefineSummary.savedSearchLabel": "已保存搜索", "xpack.transform.stepDefineSummary.timeRangeLabel": "时间范围", "xpack.transform.stepDetailsForm.advancedSettingsAccordionButtonContent": "高级设置", "xpack.transform.stepDetailsForm.continuousModeAriaLabel": "选择延迟。", diff --git a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/fields_config.tsx b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/fields_config.tsx index 90d356809acf..fb1a51c31166 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/fields_config.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/fields_config.tsx @@ -638,7 +638,7 @@ export const FieldsControls: FC> = ({ }) => { const { splitFieldsOptions, combinedQuery } = useChangePointDetectionContext(); const { dataView } = useDataSource(); - const { data, uiSettings, fieldFormats, charts, fieldStats, theme } = useAiopsAppContext(); + const { data, uiSettings, fieldFormats, charts, fieldStats } = useAiopsAppContext(); const timefilter = useTimefilter(); // required in order to trigger state updates useTimeRangeUpdates(); @@ -677,7 +677,6 @@ export const FieldsControls: FC> = ({ } : undefined } - theme={theme} > diff --git a/x-pack/platform/plugins/shared/aiops/public/components/field_stats_popover/field_stats_popover.tsx b/x-pack/platform/plugins/shared/aiops/public/components/field_stats_popover/field_stats_popover.tsx index 342485f68441..fe18686e93d1 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/field_stats_popover/field_stats_popover.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/field_stats_popover/field_stats_popover.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { EuiButtonIcon, EuiToolTip } from '@elastic/eui'; +import { useEuiTheme, EuiButtonIcon, EuiToolTip } from '@elastic/eui'; import React, { useCallback, useMemo, useState } from 'react'; import { i18n } from '@kbn/i18n'; import { isDefined } from '@kbn/ml-is-defined'; @@ -19,7 +19,6 @@ import { } from '@kbn/unified-field-list/src/components/field_popover'; import type { DataView } from '@kbn/data-views-plugin/common'; import type { TimeRange as TimeRangeMs } from '@kbn/ml-date-picker'; -import { useEuiTheme } from '../../hooks/use_eui_theme'; import { FieldStatsContent } from './field_stats_content'; export function FieldStatsPopover({ @@ -38,7 +37,7 @@ export function FieldStatsPopover({ timeRangeMs?: TimeRangeMs; }) { const [infoIsOpen, setInfoOpen] = useState(false); - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const closePopover = useCallback(() => setInfoOpen(false), []); @@ -62,7 +61,7 @@ export function FieldStatsPopover({ defaultMessage: 'Show top field values', })} data-test-subj={'aiopsContextPopoverButton'} - css={{ marginLeft: euiTheme.euiSizeXS }} + css={{ marginLeft: euiTheme.size.xs }} /> ); diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/category_table.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/category_table.tsx index 2a9591bb415a..06ba0d128a9b 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/category_table.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/category_table.tsx @@ -10,6 +10,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { EuiBasicTableColumn, EuiTableSelectionType } from '@elastic/eui'; import { + useEuiTheme, useEuiBackgroundColor, EuiInMemoryTable, EuiButtonIcon, @@ -24,8 +25,6 @@ import type { UseTableState } from '@kbn/ml-in-memory-table'; import { css } from '@emotion/react'; import type { Category } from '@kbn/aiops-log-pattern-analysis/types'; -import { useEuiTheme } from '../../../hooks/use_eui_theme'; - import { MiniHistogram } from '../../mini_histogram'; import type { EventRate } from '../use_categorize_request'; @@ -63,7 +62,7 @@ export const CategoryTable: FC = ({ selectable = true, onRenderComplete, }) => { - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const primaryBackgroundColor = useEuiBackgroundColor('primary'); const { onTableChange, pagination, sorting } = tableState; @@ -221,12 +220,12 @@ export const CategoryTable: FC = ({ if (mouseOver.highlightedCategory && mouseOver.highlightedCategory.key === category.key) { return { - backgroundColor: euiTheme.euiColorLightestShade, + backgroundColor: euiTheme.colors.lightestShade, }; } return { - backgroundColor: euiTheme.euiColorEmptyShade, + backgroundColor: euiTheme.colors.emptyShade, }; }; @@ -235,8 +234,8 @@ export const CategoryTable: FC = ({ position: 'sticky', insetBlockStart: 0, zIndex: 1, - backgroundColor: euiTheme.euiColorEmptyShade, - boxShadow: `inset 0 0px 0, inset 0 -1px 0 ${euiTheme.euiBorderColor}`, + backgroundColor: euiTheme.colors.emptyShade, + boxShadow: `inset 0 0px 0, inset 0 -1px 0 ${euiTheme.border.color}`, }, }); diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/table_header.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/table_header.tsx index 9157b4994adb..82a8d99f7337 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/table_header.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/category_table/table_header.tsx @@ -7,10 +7,16 @@ import type { FC, PropsWithChildren } from 'react'; import React from 'react'; -import { EuiFlexGroup, EuiFlexItem, EuiText, EuiButtonEmpty, EuiToolTip } from '@elastic/eui'; +import { + useEuiTheme, + EuiFlexGroup, + EuiFlexItem, + EuiText, + EuiButtonEmpty, + EuiToolTip, +} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { QUERY_MODE } from '@kbn/aiops-log-pattern-analysis/get_category_query'; -import { useEuiTheme } from '../../../hooks/use_eui_theme'; import type { OpenInDiscover } from './use_open_in_discover'; interface Props { @@ -24,9 +30,9 @@ export const TableHeader: FC = ({ selectedCategoriesCount, openInDiscover, }) => { - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); return ( - + ({ +jest.mock('../../hooks/use_is_dark_theme', () => ({ useIsDarkTheme: () => false, })); diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/format_category.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/format_category.tsx index 5af947834964..bd8c16f8f8f7 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/format_category.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/format_category.tsx @@ -11,7 +11,7 @@ import { EuiText, EuiHorizontalRule } from '@elastic/eui'; import type { SerializedStyles } from '@emotion/react'; import { css } from '@emotion/react'; import type { Category } from '@kbn/aiops-log-pattern-analysis/types'; -import { useIsDarkTheme } from '../../hooks/use_eui_theme'; +import { useIsDarkTheme } from '../../hooks/use_is_dark_theme'; interface Props { category: Category; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx index fb3c17634fd3..37b3d796f489 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx @@ -17,7 +17,7 @@ import { getWindowParametersForTrigger, getSnappedTimestamps, getSnappedWindowParameters, - LOG_RATE_ANALYSIS_HIGHLIGHT_COLOR, + useLogRateAnalysisBarColors, LOG_RATE_ANALYSIS_TYPE, type WindowParameters, } from '@kbn/aiops-log-rate-analysis'; @@ -130,7 +130,7 @@ export const LogRateAnalysisContent: FC = ({ const barStyle = { rect: { opacity: 1, - fill: LOG_RATE_ANALYSIS_HIGHLIGHT_COLOR, + fill: useLogRateAnalysisBarColors().barHighlightColor, }, }; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_info_popover.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_info_popover.tsx index afa1fd27ac99..ec11caa24a72 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_info_popover.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_info_popover.tsx @@ -7,14 +7,12 @@ import React, { useState, type FC } from 'react'; -import { EuiBadge, EuiPopover, EuiPopoverTitle, EuiText } from '@elastic/eui'; +import { useEuiTheme, EuiBadge, EuiPopover, EuiPopoverTitle, EuiText } from '@elastic/eui'; import { LOG_RATE_ANALYSIS_TYPE } from '@kbn/aiops-log-rate-analysis'; import { useAppSelector } from '@kbn/aiops-log-rate-analysis/state'; import { i18n } from '@kbn/i18n'; -import { useEuiTheme } from '../../hooks/use_eui_theme'; - export const LogRateAnalysisInfoPopoverButton: FC<{ onClick: React.MouseEventHandler; label: string; @@ -37,7 +35,7 @@ export const LogRateAnalysisInfoPopoverButton: FC<{ }; export const LogRateAnalysisInfoPopover: FC = () => { - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const showInfoPopover = useAppSelector( (s) => s.logRateAnalysisResults.significantItems.length > 0 @@ -117,7 +115,7 @@ export const LogRateAnalysisInfoPopover: FC = () => { )} - +

{infoContent} {fieldSelectionMessage && ` ${fieldSelectionMessage}`} diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx index ded175a89dfb..816d7654444e 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx @@ -11,7 +11,7 @@ import { orderBy, isEqual } from 'lodash'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { Criteria, EuiTableSortingType } from '@elastic/eui'; -import { useEuiBackgroundColor, EuiBasicTable } from '@elastic/eui'; +import { useEuiTheme, useEuiBackgroundColor, EuiBasicTable } from '@elastic/eui'; import type { SignificantItem } from '@kbn/ml-agg-utils'; import { @@ -22,7 +22,6 @@ import { } from '@kbn/aiops-log-rate-analysis/state'; import type { GroupTableItemGroup } from '@kbn/aiops-log-rate-analysis/state'; -import { useEuiTheme } from '../../hooks/use_eui_theme'; import { useColumns, LOG_RATE_ANALYSIS_RESULTS_TABLE_TYPE } from './use_columns'; const PAGINATION_SIZE_OPTIONS = [5, 10, 20, 50]; @@ -48,7 +47,7 @@ export const LogRateAnalysisResultsTable: FC = barHighlightColorOverride, skippedColumns, }) => { - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const primaryBackgroundColor = useEuiBackgroundColor('primary'); const allItems = useAppSelector((s) => s.logRateAnalysisResults.significantItems); @@ -227,12 +226,12 @@ export const LogRateAnalysisResultsTable: FC = selectedSignificantItem.fieldValue === significantItem.fieldValue ) { return { - backgroundColor: euiTheme.euiColorLightestShade, + backgroundColor: euiTheme.colors.lightestShade, }; } return { - backgroundColor: euiTheme.euiColorEmptyShade, + backgroundColor: euiTheme.colors.emptyShade, }; }; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx index c5b7a83e3364..a9657c907f93 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx @@ -7,6 +7,7 @@ import React, { useMemo, useCallback } from 'react'; import { + useEuiTheme, type EuiBasicTableColumn, EuiBadge, EuiCode, @@ -35,7 +36,6 @@ import { getFailedTransactionsCorrelationImpactLabel } from './get_failed_transa import { FieldStatsPopover } from '../field_stats_popover'; import { useAiopsAppContext } from '../../hooks/use_aiops_app_context'; import { useDataSource } from '../../hooks/use_data_source'; -import { useEuiTheme } from '../../hooks/use_eui_theme'; import { useViewInDiscoverAction } from './use_view_in_discover_action'; import { useViewInLogPatternAnalysisAction } from './use_view_in_log_pattern_analysis_action'; import { useCopyToClipboardAction } from './use_copy_to_clipboard_action'; @@ -159,7 +159,7 @@ export const useColumns = ( ): Array> => { const { data, uiSettings, fieldFormats, charts } = useAiopsAppContext(); const { dataView } = useDataSource(); - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const viewInDiscoverAction = useViewInDiscoverAction(dataView.id); const viewInLogPatternAnalysisAction = useViewInLogPatternAnalysisAction(dataView.id); const copyToClipBoardAction = useCopyToClipboardAction(); @@ -265,8 +265,8 @@ export const useColumns = ( = ({ }) => { const { charts } = useAiopsAppContext(); - const euiTheme = useEuiTheme(); + const { euiTheme } = useEuiTheme(); const chartBaseTheme = charts.theme.useChartsBaseTheme(); + const barColors = useLogRateAnalysisBarColors(); const miniHistogramChartTheme: PartialTheme = { chartMargins: { @@ -66,7 +66,7 @@ export const MiniHistogram: FC = ({ const cssChartSize = css({ width: '80px', - height: euiTheme.euiSizeL, + height: euiTheme.size.l, margin: '0px', }); @@ -94,10 +94,10 @@ export const MiniHistogram: FC = ({ ); } - const barColor = barColorOverride ? [barColorOverride] : undefined; + const barColor = barColorOverride ? [barColorOverride] : barColors.barColor; const barHighlightColor = barHighlightColorOverride ? [barHighlightColorOverride] - : [LOG_RATE_ANALYSIS_HIGHLIGHT_COLOR]; + : [barColors.barHighlightColor]; return (

diff --git a/x-pack/platform/plugins/shared/aiops/public/embeddables/change_point_chart/change_point_chart_initializer.tsx b/x-pack/platform/plugins/shared/aiops/public/embeddables/change_point_chart/change_point_chart_initializer.tsx index e69511fe45f9..f98714d6338a 100644 --- a/x-pack/platform/plugins/shared/aiops/public/embeddables/change_point_chart/change_point_chart_initializer.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/embeddables/change_point_chart/change_point_chart_initializer.tsx @@ -211,7 +211,7 @@ export const FormControls: FC<{ onChange: (update: FormControlsProps) => void; onValidationChange: (isValid: boolean) => void; }> = ({ formInput, onChange, onValidationChange }) => { - const { charts, data, fieldFormats, theme, uiSettings } = useAiopsAppContext(); + const { charts, data, fieldFormats, uiSettings } = useAiopsAppContext(); const { dataView } = useDataSource(); const { combinedQuery } = useChangePointDetectionContext(); const { metricFieldOptions, splitFieldsOptions } = useChangePointDetectionControlsContext(); @@ -290,7 +290,6 @@ export const FormControls: FC<{ } : undefined } - theme={theme} > { + const { euiTheme } = useEuiTheme(); const isMounted = useMountedState(); const [formInput, setFormInput] = useState( @@ -136,7 +137,7 @@ export const LogRateAnalysisEmbeddableInitializer: FC< hasBorder={true} css={{ pointerEvents: 'auto', - backgroundColor: euiThemeVars.euiColorEmptyShade, + backgroundColor: euiTheme.colors.emptyShade, }} > diff --git a/x-pack/platform/plugins/shared/aiops/public/embeddables/pattern_analysis/pattern_analysis_initializer.tsx b/x-pack/platform/plugins/shared/aiops/public/embeddables/pattern_analysis/pattern_analysis_initializer.tsx index ef185518638b..684ab9b988ed 100644 --- a/x-pack/platform/plugins/shared/aiops/public/embeddables/pattern_analysis/pattern_analysis_initializer.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/embeddables/pattern_analysis/pattern_analysis_initializer.tsx @@ -6,6 +6,7 @@ */ import { + useEuiTheme, EuiFlyoutHeader, EuiTitle, EuiFlyoutBody, @@ -19,7 +20,6 @@ import { EuiFlyoutFooter, EuiCallOut, } from '@elastic/eui'; -import { euiThemeVars } from '@kbn/ui-theme'; import { i18n } from '@kbn/i18n'; import type { FC } from 'react'; import React, { useEffect, useMemo, useState, useCallback } from 'react'; @@ -62,6 +62,7 @@ export const PatternAnalysisEmbeddableInitializer: FC { + const { euiTheme } = useEuiTheme(); const { data: { dataViews }, unifiedSearch: { @@ -128,7 +129,7 @@ export const PatternAnalysisEmbeddableInitializer: FC diff --git a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data_source.tsx b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data_source.tsx index ef574a348b92..7acdc24e069f 100644 --- a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data_source.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data_source.tsx @@ -100,7 +100,7 @@ export const DataSourceContextProvider: FC } diff --git a/x-pack/platform/plugins/shared/aiops/public/hooks/use_eui_theme.ts b/x-pack/platform/plugins/shared/aiops/public/hooks/use_eui_theme.ts deleted file mode 100644 index 7da2bd6be954..000000000000 --- a/x-pack/platform/plugins/shared/aiops/public/hooks/use_eui_theme.ts +++ /dev/null @@ -1,19 +0,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 { useCurrentEuiThemeVars, useIsDarkTheme as useIsDarkThemeMl } from '@kbn/ml-kibana-theme'; -import { useAiopsAppContext } from './use_aiops_app_context'; - -export function useEuiTheme() { - const { theme } = useAiopsAppContext(); - return useCurrentEuiThemeVars(theme).euiTheme; -} - -export function useIsDarkTheme() { - const { theme } = useAiopsAppContext(); - return useIsDarkThemeMl(theme); -} diff --git a/x-pack/platform/plugins/shared/aiops/public/hooks/use_is_dark_theme.ts b/x-pack/platform/plugins/shared/aiops/public/hooks/use_is_dark_theme.ts new file mode 100644 index 000000000000..6dc15ffa9e25 --- /dev/null +++ b/x-pack/platform/plugins/shared/aiops/public/hooks/use_is_dark_theme.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useIsDarkTheme as useIsDarkThemeMl } from '@kbn/ml-kibana-theme'; +import { useAiopsAppContext } from './use_aiops_app_context'; + +export function useIsDarkTheme() { + const { theme } = useAiopsAppContext(); + return useIsDarkThemeMl(theme); +} diff --git a/x-pack/platform/plugins/shared/aiops/tsconfig.json b/x-pack/platform/plugins/shared/aiops/tsconfig.json index afee86051b7a..1069dfde9622 100644 --- a/x-pack/platform/plugins/shared/aiops/tsconfig.json +++ b/x-pack/platform/plugins/shared/aiops/tsconfig.json @@ -75,7 +75,6 @@ "@kbn/usage-collection-plugin", "@kbn/utility-types", "@kbn/observability-ai-assistant-plugin", - "@kbn/ui-theme", "@kbn/apm-utils", "@kbn/ml-field-stats-flyout", ], diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx b/x-pack/platform/plugins/shared/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx index 4d4e244ac25a..31dec6ab573d 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx +++ b/x-pack/platform/plugins/shared/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx @@ -481,7 +481,7 @@ export const mapProcessorTypeToDescriptor: MapProcessorTypeToDescriptor = { ip_location: { category: processorCategories.DATA_ENRICHMENT, FieldsComponent: IpLocation, - docLinkPath: '/geoip-processor.html', + docLinkPath: '/ip-location-processor.html', label: i18n.translate('xpack.ingestPipelines.processors.label.ipLocation', { defaultMessage: 'IP Location', }), diff --git a/x-pack/platform/plugins/shared/ml/common/util/group_color_utils.ts b/x-pack/platform/plugins/shared/ml/common/util/group_color_utils.ts index 77d16b8aaad5..1e58ce6e67ea 100644 --- a/x-pack/platform/plugins/shared/ml/common/util/group_color_utils.ts +++ b/x-pack/platform/plugins/shared/ml/common/util/group_color_utils.ts @@ -5,28 +5,29 @@ * 2.0. */ -import { euiDarkVars as euiVars } from '@kbn/ui-theme'; +import type { EuiThemeComputed } from '@elastic/eui'; import { stringHash } from '@kbn/ml-string-hash'; -const COLORS = [ - euiVars.euiColorVis0, - euiVars.euiColorVis1, - euiVars.euiColorVis2, - euiVars.euiColorVis3, - euiVars.euiColorVis4, - euiVars.euiColorVis5, - euiVars.euiColorVis6, - euiVars.euiColorVis7, - euiVars.euiColorVis8, - euiVars.euiColorVis9, - euiVars.euiColorDarkShade, - euiVars.euiColorPrimary, -]; - const colorMap: Record = Object.create(null); -export function tabColor(name: string): string { +export function tabColor(name: string, euiTheme: EuiThemeComputed): string { + const COLORS = [ + // Amsterdam + Borealis + euiTheme.colors.vis.euiColorVis0, + euiTheme.colors.vis.euiColorVis1, + euiTheme.colors.vis.euiColorVis2, + euiTheme.colors.vis.euiColorVis3, + euiTheme.colors.vis.euiColorVis4, + euiTheme.colors.vis.euiColorVis5, + euiTheme.colors.vis.euiColorVis6, + euiTheme.colors.vis.euiColorVis7, + euiTheme.colors.vis.euiColorVis8, + euiTheme.colors.vis.euiColorVis9, + euiTheme.colors.darkShade, + euiTheme.colors.primary, + ]; + if (colorMap[name] === undefined) { const n = stringHash(name); const color = COLORS[n % COLORS.length]; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/anomalies_table/links_menu.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/anomalies_table/links_menu.tsx index 1f81a9422761..dd963136f29c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/anomalies_table/links_menu.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/anomalies_table/links_menu.tsx @@ -13,6 +13,7 @@ import React, { useEffect, useMemo, useState } from 'react'; import useMountedState from 'react-use/lib/useMountedState'; import { + useEuiTheme, EuiButtonIcon, EuiContextMenuItem, EuiContextMenuPanel, @@ -80,6 +81,7 @@ interface LinksMenuProps { } export const LinksMenuUI = (props: LinksMenuProps) => { + const { euiTheme } = useEuiTheme(); const isMounted = useMountedState(); const [dataViewId, setDataViewId] = useState(null); @@ -195,7 +197,8 @@ export const LinksMenuUI = (props: LinksMenuProps) => { ) => { // Create a layer for each of the geoFields const initialLayers = getInitialSourceIndexFieldLayers( - sourceIndicesWithGeoFields[anomaly.jobId] + sourceIndicesWithGeoFields[anomaly.jobId], + euiTheme ); // Widen the timerange by one bucket span on start/end to increase chances of always having data on the map const anomalyBucketStartMoment = moment(anomaly.source.timestamp).tz( diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/chart_tooltip/chart_tooltip_styles.ts b/x-pack/platform/plugins/shared/ml/public/application/components/chart_tooltip/chart_tooltip_styles.ts index c53bdb5242f3..be4735abb214 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/chart_tooltip/chart_tooltip_styles.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/chart_tooltip/chart_tooltip_styles.ts @@ -7,29 +7,23 @@ import { css } from '@emotion/react'; -import { mathWithUnits, transparentize, useEuiTheme } from '@elastic/eui'; +import { mathWithUnits, transparentize, useEuiFontSize, useEuiTheme } from '@elastic/eui'; // @ts-expect-error style types not defined import { euiToolTipStyles } from '@elastic/eui/lib/components/tool_tip/tool_tip.styles'; -import { useCurrentEuiThemeVars } from '@kbn/ml-kibana-theme'; - -import { useMlKibana } from '../../contexts/kibana'; - export const useChartTooltipStyles = () => { - const euiThemeContext = useEuiTheme(); - const { - services: { theme }, - } = useMlKibana(); - const { euiTheme } = useCurrentEuiThemeVars(theme); - const euiStyles = euiToolTipStyles(euiThemeContext); + const theme = useEuiTheme(); + const { euiTheme } = theme; + const euiStyles = euiToolTipStyles(theme); + const euiFontSizeXS = useEuiFontSize('xs').fontSize; return { mlChartTooltip: css([ euiStyles.euiToolTip, { - fontSize: euiTheme.euiFontSizeXS, + fontSize: euiFontSizeXS, padding: 0, - transition: `opacity ${euiTheme.euiAnimSpeedNormal}`, + transition: `opacity ${euiTheme.animation.normal}`, pointerEvents: 'none', userSelect: 'none', maxWidth: '512px', @@ -37,26 +31,26 @@ export const useChartTooltipStyles = () => { }, ]), mlChartTooltipList: css({ - margin: euiTheme.euiSizeXS, - paddingBottom: euiTheme.euiSizeXS, + margin: euiTheme.size.xs, + paddingBottom: euiTheme.size.xs, }), mlChartTooltipHeader: css({ - fontWeight: euiTheme.euiFontWeightBold, - padding: `${euiTheme.euiSizeXS} ${mathWithUnits(euiTheme.euiSizeS, (x) => x * 2)}`, - marginBottom: euiTheme.euiSizeXS, - borderBottom: `1px solid ${transparentize(euiTheme.euiBorderColor, 0.8)}`, + fontWeight: euiTheme.font.weight.bold, + padding: `${euiTheme.size.xs} ${mathWithUnits(euiTheme.size.xs, (x) => x * 2)}`, + marginBottom: euiTheme.size.xs, + borderBottom: `1px solid ${transparentize(euiTheme.border.color, 0.8)}`, }), mlChartTooltipItem: css({ display: 'flex', padding: '3px', boxSizing: 'border-box', - borderLeft: `${euiTheme.euiSizeXS} solid transparent`, + borderLeft: `${euiTheme.size.xs} solid transparent`, }), mlChartTooltipLabel: css({ minWidth: '1px', }), mlChartTooltipValue: css({ - fontWeight: euiTheme.euiFontWeightBold, + fontWeight: euiTheme.font.weight.bold, textAlign: 'right', fontFeatureSettings: 'tnum', marginLeft: '8px', diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/collapsible_panel.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/collapsible_panel.tsx index b33d056467d1..8d91d6eae009 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/collapsible_panel.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/collapsible_panel.tsx @@ -6,6 +6,7 @@ */ import { + useEuiTheme, EuiBadge, EuiButtonIcon, EuiFlexGroup, @@ -18,7 +19,6 @@ import type { PropsWithChildren } from 'react'; import React, { type FC } from 'react'; import { i18n } from '@kbn/i18n'; import { PanelHeaderItems } from './panel_header_items'; -import { useCurrentThemeVars } from '../../contexts/kibana'; export interface CollapsiblePanelProps { isOpen: boolean; @@ -36,15 +36,15 @@ export const CollapsiblePanel: FC> = ({ headerItems, ariaLabel, }) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); return ( @@ -88,7 +88,7 @@ export const CollapsiblePanel: FC> = ({ {isOpen ? ( {children} diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/panel_header_items.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/panel_header_items.tsx index 75d43e6ebe6f..bd657a6a5828 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/panel_header_items.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/collapsible_panel/panel_header_items.tsx @@ -6,9 +6,8 @@ */ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { css } from '@emotion/react'; import React, { type FC } from 'react'; -import { useCurrentThemeVars } from '../../contexts/kibana'; +import { useEuiTheme } from '@elastic/eui'; export interface PanelHeaderItems { headerItems: React.ReactElement[]; @@ -16,7 +15,7 @@ export interface PanelHeaderItems { } export const PanelHeaderItems: FC = ({ headerItems, compressed = false }) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); return ( @@ -26,12 +25,10 @@ export const PanelHeaderItems: FC = ({ headerItems, compressed
diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/color_range_legend.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/color_range_legend.tsx index 9c121853cf6b..4051b0632c2c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/color_range_legend.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/color_range_legend.tsx @@ -6,36 +6,43 @@ */ import type { FC } from 'react'; -import React, { useEffect, useRef } from 'react'; +import React, { useEffect, useMemo, useRef } from 'react'; import { css } from '@emotion/react'; import d3 from 'd3'; -import { EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; - -import { euiThemeVars } from '@kbn/ui-theme'; +import { useEuiFontSize, useEuiTheme, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; const COLOR_RANGE_RESOLUTION = 10; // Overrides for d3/svg default styles -const cssOverride = css({ - // Override default font size and color for axis - text: { - fontSize: `calc(${euiThemeVars.euiFontSizeXS} - 2px)`, - fill: euiThemeVars.euiColorDarkShade, - }, - // Override default styles for axis lines - '.axis': { - path: { - fill: 'none', - stroke: 'none', - }, - line: { - fill: 'none', - stroke: euiThemeVars.euiColorMediumShade, - shapeRendering: 'crispEdges', - }, - }, -}); +const useCssOverride = () => { + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; + + return useMemo( + () => + css({ + // Override default font size and color for axis + text: { + fontSize: `calc(${euiFontSizeXS} - 2px)`, + fill: euiTheme.colors.darkShade, + }, + // Override default styles for axis lines + '.axis': { + path: { + fill: 'none', + stroke: 'none', + }, + line: { + fill: 'none', + stroke: euiTheme.colors.mediumShade, + shapeRendering: 'crispEdges', + }, + }, + }), + [euiFontSizeXS, euiTheme] + ); +}; interface ColorRangeLegendProps { colorRange: (d: number) => string; @@ -60,6 +67,7 @@ export const ColorRangeLegend: FC = ({ title, width = 250, }) => { + const cssOverride = useCssOverride(); const d3Container = useRef(null); const scale = d3.range(COLOR_RANGE_RESOLUTION + 1).map((d) => ({ diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/index.ts b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/index.ts index 8e0549fb522f..f614b5ae4ac4 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/index.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/index.ts @@ -6,7 +6,6 @@ */ export { ColorRangeLegend } from './color_range_legend'; -export type { EuiThemeType } from './use_color_range'; export { colorRangeOptions, colorRangeScaleOptions, diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/use_color_range.ts b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/use_color_range.ts index 4e4e92b5352f..49662ab00e51 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/use_color_range.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/color_range_legend/use_color_range.ts @@ -6,10 +6,10 @@ */ import d3 from 'd3'; -import type { euiDarkVars as euiThemeDark, euiLightVars as euiThemeLight } from '@kbn/ui-theme'; + +import { useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { useCurrentThemeVars } from '../../contexts/kibana'; /** * Custom color scale factory that takes the amount of feature influencers @@ -148,16 +148,24 @@ export const useColorRange = ( colorRangeScale = COLOR_RANGE_SCALE.LINEAR, featureCount = 1 ) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const colorRanges: Record = { [COLOR_RANGE.BLUE]: [ - d3.rgb(euiTheme.euiColorEmptyShade).toString(), - d3.rgb(euiTheme.euiColorVis1).toString(), + d3.rgb(euiTheme.colors.emptyShade).toString(), + d3 + .rgb( + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2 + ) + .toString(), ], [COLOR_RANGE.RED]: [ - d3.rgb(euiTheme.euiColorEmptyShade).toString(), - d3.rgb(euiTheme.euiColorDanger).toString(), + d3.rgb(euiTheme.colors.emptyShade).toString(), + d3.rgb(euiTheme.colors.danger).toString(), ], [COLOR_RANGE.RED_GREEN]: ['red', 'green'], [COLOR_RANGE.GREEN_RED]: ['green', 'red'], @@ -184,5 +192,3 @@ export const useColorRange = ( return scaleTypes[colorRangeScale]; }; - -export type EuiThemeType = typeof euiThemeLight | typeof euiThemeDark; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/influencers_list/influencers_list_styles.ts b/x-pack/platform/plugins/shared/ml/public/application/components/influencers_list/influencers_list_styles.ts index 5a0732ceb8d7..d54eb495a0a3 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/influencers_list/influencers_list_styles.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/influencers_list/influencers_list_styles.ts @@ -6,24 +6,24 @@ */ import { css } from '@emotion/react'; -import { useCurrentEuiThemeVars } from '@kbn/ml-kibana-theme'; + +import { useEuiFontSize, useEuiTheme } from '@elastic/eui'; + import { mlColors } from '../../styles'; -import { useMlKibana } from '../../contexts/kibana'; export const useInfluencersListStyles = () => { - const { - services: { theme }, - } = useMlKibana(); - const { euiTheme } = useCurrentEuiThemeVars(theme); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs').fontSize; + const euiFontSizeS = useEuiFontSize('s').fontSize; return { influencersList: css({ lineHeight: 1.45, }), fieldLabel: css({ - fontSize: euiTheme.euiFontSizeXS, + fontSize: euiFontSizeXS, textAlign: 'left', - maxHeight: euiTheme.euiFontSizeS, + maxHeight: euiFontSizeS, maxWidth: 'calc(100% - 102px)', }), progress: css({ @@ -32,7 +32,7 @@ export const useInfluencersListStyles = () => { height: '22px', minWidth: '70px', marginBottom: 0, - color: euiTheme.euiColorDarkShade, + color: euiTheme.colors.darkShade, backgroundColor: 'transparent', }), progressBarHolder: css({ @@ -40,9 +40,9 @@ export const useInfluencersListStyles = () => { }), progressBar: (severity: string, barScore: number) => css({ - height: `calc(${euiTheme.euiSizeXS} / 2)`, + height: `calc(${euiTheme.size.xs} / 2)`, float: 'left', - marginTop: euiTheme.euiSizeM, + marginTop: euiTheme.size.m, textAlign: 'right', lineHeight: '18px', display: 'inline-block', @@ -62,8 +62,8 @@ export const useInfluencersListStyles = () => { textAlign: 'center', lineHeight: '14px', whiteSpace: 'nowrap', - fontSize: euiTheme.euiFontSizeXS, - marginLeft: euiTheme.euiSizeXS, + fontSize: euiFontSizeXS, + marginLeft: euiTheme.size.xs, display: 'inline', borderColor: severity === 'critical' @@ -75,16 +75,16 @@ export const useInfluencersListStyles = () => { : mlColors.warning, }), totalScoreLabel: css({ - width: euiTheme.euiSizeXL, + width: euiTheme.size.xl, verticalAlign: 'top', textAlign: 'center', - color: euiTheme.euiColorDarkShade, + color: euiTheme.colors.darkShade, fontSize: '11px', lineHeight: '14px', - borderRadius: euiTheme.euiBorderRadius, - padding: `calc(${euiTheme.euiSizeXS} / 2)`, + borderRadius: euiTheme.border.radius.small, + padding: `calc(${euiTheme.size.xs} / 2)`, display: 'inline-block', - border: euiTheme.euiBorderThin, + border: euiTheme.border.thin, }), }; }; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/job_selector/job_selector_badge/job_selector_badge.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/job_selector/job_selector_badge/job_selector_badge.tsx index 8b277b84fac2..f3561944e684 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/job_selector/job_selector_badge/job_selector_badge.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/job_selector/job_selector_badge/job_selector_badge.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React from 'react'; import type { EuiBadgeProps } from '@elastic/eui'; -import { EuiBadge } from '@elastic/eui'; +import { useEuiTheme, EuiBadge } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { tabColor } from '../../../../../common/util/group_color_utils'; @@ -27,7 +27,8 @@ export const JobSelectorBadge: FC = ({ numJobs, removeId, }) => { - const color = isGroup ? tabColor(id) : 'hollow'; + const { euiTheme } = useEuiTheme(); + const color = isGroup ? tabColor(id, euiTheme) : 'hollow'; let props = { color } as EuiBadgeProps; let jobCount; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx index 10b02310b39d..b2b46d5d59ac 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx @@ -8,10 +8,10 @@ import type { FC } from 'react'; import React, { memo, useEffect, useCallback, useMemo, useState } from 'react'; import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { + useEuiTheme, EuiAccordion, EuiButton, EuiButtonEmpty, @@ -58,6 +58,7 @@ interface Props { } export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { + const { euiTheme } = useEuiTheme(); const [simulatePipelineResult, setSimulatePipelineResult] = useState< undefined | estypes.IngestSimulateResponse >(); @@ -391,7 +392,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { {(EuiResizablePanel, EuiResizableButton) => ( diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/create_calendar.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/create_calendar.tsx index e4f87e7fa4ac..3c3abdc4d995 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/create_calendar.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/create_calendar.tsx @@ -12,6 +12,7 @@ import { FormattedMessage } from '@kbn/i18n-react'; import moment from 'moment'; import type { BrushEndListener, XYBrushEvent } from '@elastic/charts'; import { + useEuiTheme, EuiButtonIcon, EuiDatePicker, EuiFieldText, @@ -21,7 +22,6 @@ import { EuiPanel, EuiSpacer, } from '@elastic/eui'; -import { useCurrentThemeVars } from '../../../contexts/kibana'; import { EventRateChart } from '../../../jobs/new_job/pages/components/charts/event_rate_chart/event_rate_chart'; import type { Anomaly } from '../../../jobs/new_job/common/results_loader/results_loader'; import type { LineChartPoint } from '../../../jobs/new_job/common/chart_loader/chart_loader'; @@ -54,7 +54,7 @@ export const CreateCalendar: FC = ({ const maxSelectableTimeMoment = moment(maxSelectableTimeStamp); const minSelectableTimeMoment = moment(minSelectableTimeStamp); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const onBrushEnd = useCallback( ({ x }: XYBrushEvent) => { @@ -155,7 +155,7 @@ export const CreateCalendar: FC = ({ end: c.end!.valueOf(), }))} onBrushEnd={onBrushEnd} - overlayColor={euiTheme.euiColorPrimary} + overlayColor={euiTheme.colors.primary} /> @@ -226,7 +226,7 @@ export const CreateCalendar: FC = ({ diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx index 3fd25534134a..2388920a178f 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx @@ -10,8 +10,6 @@ import { render, waitFor, screen } from '@testing-library/react'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; -import { euiLightVars as euiThemeLight } from '@kbn/ui-theme'; - import { createFilterManagerMock } from '@kbn/data-plugin/public/query/filter_manager/filter_manager.mock'; import { ScatterplotMatrix } from './scatterplot_matrix'; @@ -22,8 +20,6 @@ const mockEsSearch = jest.fn((body) => ({ hits: { hits: [{ fields: { x: [1], y: [2] } }, { fields: { x: [2], y: [3] } }] }, })); -const mockEuiTheme = euiThemeLight; - jest.mock('../../contexts/kibana', () => ({ useMlApi: () => ({ esSearch: mockEsSearch, @@ -48,9 +44,6 @@ jest.mock('../../contexts/kibana', () => ({ }, }, }), - useCurrentThemeVars: () => ({ - euiTheme: mockEuiTheme, - }), })); // Mocking VegaChart to avoid a jest/canvas related error diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx index 763addd4aaa8..bd79731f22e0 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx @@ -12,6 +12,8 @@ import { css } from '@emotion/react'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { + useEuiFontSize, + useEuiTheme, EuiCallOut, EuiComboBox, EuiFlexGroup, @@ -36,9 +38,8 @@ import { type RuntimeMappings, } from '@kbn/ml-runtime-field-utils'; import { getProcessedFields } from '@kbn/ml-data-grid'; -import { euiThemeVars } from '@kbn/ui-theme'; -import { useCurrentThemeVars, useMlApi, useMlKibana } from '../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../contexts/kibana'; // Separate imports for lazy loadable VegaChart and related code import { VegaChart } from '../vega_chart'; @@ -50,17 +51,22 @@ import { OUTLIER_SCORE_FIELD, } from './scatterplot_matrix_vega_lite_spec'; -const cssOverrides = css({ - // Prevent the chart from overflowing the container - overflowX: 'auto', - // Overrides for the outlier threshold slider - '.vega-bind': { - span: { - fontSize: euiThemeVars.euiFontSizeXS, - padding: `0 ${euiThemeVars.euiSizeXS}`, +const useCssOverrides = () => { + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs').fontSize; + + return css({ + // Prevent the chart from overflowing the container + overflowX: 'auto', + // Overrides for the outlier threshold slider + '.vega-bind': { + span: { + fontSize: euiFontSizeXS, + padding: `0 ${euiTheme.size.xs}`, + }, }, - }, -}); + }); +}; const SCATTERPLOT_MATRIX_DEFAULT_FIELDS = 4; const SCATTERPLOT_MATRIX_DEFAULT_FETCH_SIZE = 1000; @@ -161,7 +167,7 @@ export const ScatterplotMatrix: FC = ({ { items: any[]; backgroundItems: any[]; columns: string[]; messages: string[] } | undefined >(); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); // formats the array of field names for EuiComboBox const fieldOptions = useMemo( @@ -418,6 +424,8 @@ export const ScatterplotMatrix: FC = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [resultsField, splom, color, legendType, dynamicSize]); + const cssOverrides = useCssOverrides(); + return ( <> {splom === undefined || vegaSpec === undefined ? ( diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.test.ts b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.test.ts index e2322ff7dd2b..0ed09b2c9489 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.test.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.test.ts @@ -10,7 +10,7 @@ import 'jest-canvas-mock'; // @ts-ignore import { compile } from 'vega-lite/build/vega-lite'; -import { euiLightVars as euiThemeLight } from '@kbn/ui-theme'; +import type { EuiThemeComputed } from '@elastic/eui'; import { LEGEND_TYPES } from '../vega_chart/common'; @@ -25,9 +25,17 @@ import { SINGLE_POINT_CLICK, } from './scatterplot_matrix_vega_lite_spec'; +const euiThemeMock = { + colors: { + lighestShade: '#f0f0f0', + lightShade: '#d3dae6', + textSubdued: '#6a7170', + }, +} as unknown as EuiThemeComputed; + describe('getColorSpec()', () => { it('should return only user selection conditions and the default color for non-outlier specs', () => { - const colorSpec = getColorSpec(false, euiThemeLight); + const colorSpec = getColorSpec(false); expect(colorSpec).toEqual({ condition: [{ selection: USER_SELECTION }, { selection: SINGLE_POINT_CLICK }], @@ -36,7 +44,7 @@ describe('getColorSpec()', () => { }); it('should return user selection condition and conditional spec for outliers', () => { - const colorSpec = getColorSpec(false, euiThemeLight, 'outlier_score'); + const colorSpec = getColorSpec(false, 'outlier_score'); expect(colorSpec).toEqual({ condition: { @@ -54,13 +62,7 @@ describe('getColorSpec()', () => { it('should return user selection condition and a field based spec for non-outlier specs with legendType supplied', () => { const colorName = 'the-color-field'; - const colorSpec = getColorSpec( - false, - euiThemeLight, - undefined, - colorName, - LEGEND_TYPES.NOMINAL - ); + const colorSpec = getColorSpec(false, undefined, colorName, LEGEND_TYPES.NOMINAL); expect(colorSpec).toEqual({ condition: { @@ -137,7 +139,7 @@ describe('getScatterplotMatrixVegaLiteSpec()', () => { data, [], ['x', 'y'], - euiThemeLight + euiThemeMock ); const specForegroundLayer = vegaLiteSpec.spec.layer[0]; @@ -172,7 +174,7 @@ describe('getScatterplotMatrixVegaLiteSpec()', () => { data, [], ['x', 'y'], - euiThemeLight, + euiThemeMock, 'ml' ); const specForegroundLayer = vegaLiteSpec.spec.layer[0]; @@ -221,7 +223,7 @@ describe('getScatterplotMatrixVegaLiteSpec()', () => { data, [], ['x', 'y'], - euiThemeLight, + euiThemeMock, undefined, 'the-color-field', LEGEND_TYPES.NOMINAL @@ -267,7 +269,7 @@ describe('getScatterplotMatrixVegaLiteSpec()', () => { data, [], ['x.a', 'y[a]'], - euiThemeLight, + euiThemeMock, undefined, 'the-color-field', LEGEND_TYPES.NOMINAL diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.ts b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.ts index e7d706633984..95ede4edcc9e 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix_vega_lite_spec.ts @@ -9,9 +9,12 @@ // @ts-ignore import type { TopLevelSpec } from 'vega-lite/build/vega-lite'; -import type { euiLightVars as euiThemeLight } from '@kbn/ui-theme'; - -import { euiPaletteColorBlind, euiPaletteRed, euiPaletteGreen } from '@elastic/eui'; +import { + euiPaletteColorBlind, + euiPaletteRed, + euiPaletteGreen, + type EuiThemeComputed, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -34,7 +37,6 @@ const CUSTOM_VIS_FIELDS_PATH = 'fields'; export const getColorSpec = ( forCustomVisLink: boolean, - euiTheme: typeof euiThemeLight, escapedOutlierScoreField?: string, color?: string, legendType?: LegendType @@ -280,7 +282,7 @@ export const getScatterplotMatrixVegaLiteSpec = ( values: VegaValue[], backgroundValues: VegaValue[], columns: string[], - euiTheme: typeof euiThemeLight, + euiTheme: EuiThemeComputed, resultsField?: string, color?: string, legendType?: LegendType, @@ -296,7 +298,6 @@ export const getScatterplotMatrixVegaLiteSpec = ( const colorSpec = getColorSpec( forCustomVisLink, - euiTheme, resultsField && escapedOutlierScoreField, color, legendType @@ -309,20 +310,20 @@ export const getScatterplotMatrixVegaLiteSpec = ( // for repeated charts, it seems to be fixed for facets but not repeat. // This causes #ddd lines to stand out in dark mode. // See: https://github.com/vega/vega-lite/issues/5908 - view: { fill: 'transparent', stroke: euiTheme.euiColorLightestShade }, + view: { fill: 'transparent', stroke: euiTheme.colors.lightestShade }, padding: 10, config: { axis: { - domainColor: euiTheme.euiColorLightShade, - gridColor: euiTheme.euiColorLightestShade, - tickColor: euiTheme.euiColorLightestShade, - labelColor: euiTheme.euiTextSubduedColor, - titleColor: euiTheme.euiTextSubduedColor, + domainColor: euiTheme.colors.lightShade, + gridColor: euiTheme.colors.lightestShade, + tickColor: euiTheme.colors.lightestShade, + labelColor: euiTheme.colors.textSubdued, + titleColor: euiTheme.colors.textSubdued, }, legend: { orient: 'right', - labelColor: euiTheme.euiTextSubduedColor, - titleColor: euiTheme.euiTextSubduedColor, + labelColor: euiTheme.colors.textSubdued, + titleColor: euiTheme.colors.textSubdued, }, }, repeat: { diff --git a/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/index.ts b/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/index.ts index 47836e6495c0..e8c6c081d6e1 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/index.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/index.ts @@ -14,5 +14,4 @@ export { useNotifications } from './use_notifications_context'; export { useMlLocator, useMlLink } from './use_create_url'; export { useMlApi } from './use_ml_api_context'; export { useFieldFormatter } from './use_field_formatter'; -export { useCurrentThemeVars } from './use_current_theme'; export { useMlLicenseInfo } from './use_ml_license'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/use_current_theme.ts b/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/use_current_theme.ts deleted file mode 100644 index 906fd599af75..000000000000 --- a/x-pack/platform/plugins/shared/ml/public/application/contexts/kibana/use_current_theme.ts +++ /dev/null @@ -1,16 +0,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 { useCurrentEuiThemeVars } from '@kbn/ml-kibana-theme'; -import { useMlKibana } from './kibana_context'; - -export function useCurrentThemeVars() { - const { - services: { theme }, - } = useMlKibana(); - return useCurrentEuiThemeVars(theme); -} diff --git a/x-pack/platform/plugins/shared/ml/public/application/contexts/ml/data_source_context.tsx b/x-pack/platform/plugins/shared/ml/public/application/contexts/ml/data_source_context.tsx index 1c94200794a8..5855325f5918 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/contexts/ml/data_source_context.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/contexts/ml/data_source_context.tsx @@ -120,7 +120,7 @@ export const DataSourceContextProvider: FC> = ({ chil

} diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx index 7fd678e98f6f..3e8933a5330a 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx @@ -576,7 +576,6 @@ export const ConfigurationStepForm: FC = ({ fieldStatsServices={fieldStatsServices} timeRangeMs={indexData.timeRangeMs} dslQuery={jobConfigQuery} - theme={services.theme} > @@ -603,8 +602,8 @@ export const ConfigurationStepForm: FC = ({ {savedSearchQuery !== null && ( - {i18n.translate('xpack.ml.dataframe.analytics.create.savedSearchLabel', { - defaultMessage: 'Saved search', + {i18n.translate('xpack.ml.dataframe.analytics.create.discoverSessionLabel', { + defaultMessage: 'Discover session', })} )} diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/evaluate_panel.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/evaluate_panel.tsx index 0d30b0371a02..2b0002896e1c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/evaluate_panel.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/evaluate_panel.tsx @@ -10,6 +10,7 @@ import React, { useEffect, useState } from 'react'; import type { EuiDataGridCellValueElementProps } from '@elastic/eui'; import { + useEuiTheme, EuiButtonEmpty, EuiDataGrid, EuiFlexGroup, @@ -27,7 +28,7 @@ import { type DataFrameTaskStateType, } from '@kbn/ml-data-frame-analytics-utils'; -import { useCurrentThemeVars, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlKibana } from '../../../../../contexts/kibana'; // Separate imports for lazy loadable VegaChart and related code import { VegaChart } from '../../../../../components/vega_chart'; @@ -111,7 +112,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, se const { services: { docLinks }, } = useMlKibana(); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const [columns, setColumns] = useState([]); const [columnsData, setColumnsData] = useState([]); diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/get_roc_curve_chart_vega_lite_spec.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/get_roc_curve_chart_vega_lite_spec.tsx index 3bfdfa03a302..1d148daac9e5 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/get_roc_curve_chart_vega_lite_spec.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/get_roc_curve_chart_vega_lite_spec.tsx @@ -9,9 +9,8 @@ // @ts-ignore import type { TopLevelSpec } from 'vega-lite/build/vega-lite'; -import { euiPaletteColorBlind, euiPaletteGray } from '@elastic/eui'; +import { euiPaletteColorBlind, euiPaletteGray, type EuiThemeComputed } from '@elastic/eui'; -import type { euiLightVars as euiThemeLight } from '@kbn/ui-theme'; import { i18n } from '@kbn/i18n'; import type { RocCurveItem } from '@kbn/ml-data-frame-analytics-utils'; @@ -44,7 +43,7 @@ export const getRocCurveChartVegaLiteSpec = ( classificationClasses: string[], data: RocCurveDataRow[], legendTitle: string, - euiTheme: typeof euiThemeLight + euiTheme: EuiThemeComputed ): TopLevelSpec => { // we append two rows which make up the data for the diagonal baseline data.push({ tpr: 0, fpr: 0, threshold: 1, class_name: BASELINE }); @@ -60,8 +59,8 @@ export const getRocCurveChartVegaLiteSpec = ( config: { legend: { orient: 'right', - labelColor: euiTheme.euiTextSubduedColor, - titleColor: euiTheme.euiTextSubduedColor, + labelColor: euiTheme.colors.textSubdued, + titleColor: euiTheme.colors.textSubdued, }, view: { continuousHeight: SIZE, @@ -104,9 +103,9 @@ export const getRocCurveChartVegaLiteSpec = ( type: 'quantitative', axis: { tickColor: GRAY, - labelColor: euiTheme.euiTextSubduedColor, + labelColor: euiTheme.colors.textSubdued, domainColor: GRAY, - titleColor: euiTheme.euiTextSubduedColor, + titleColor: euiTheme.colors.textSubdued, }, }, y: { @@ -117,9 +116,9 @@ export const getRocCurveChartVegaLiteSpec = ( type: 'quantitative', axis: { tickColor: GRAY, - labelColor: euiTheme.euiTextSubduedColor, + labelColor: euiTheme.colors.textSubdued, domainColor: GRAY, - titleColor: euiTheme.euiTextSubduedColor, + titleColor: euiTheme.colors.textSubdued, }, }, tooltip: [ diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/feature_importance/decision_path_chart.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/feature_importance/decision_path_chart.tsx index b2532b225db2..d6e64b6e8acd 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/feature_importance/decision_path_chart.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/feature_importance/decision_path_chart.tsx @@ -23,51 +23,16 @@ import { Settings, LEGACY_LIGHT_THEME, } from '@elastic/charts'; -import { EuiIcon } from '@elastic/eui'; +import { useEuiTheme, EuiIcon } from '@elastic/eui'; import React, { useCallback, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; -import { euiLightVars as euiVars } from '@kbn/ui-theme'; import { type FeatureImportanceBaseline, isRegressionFeatureImportanceBaseline, } from '@kbn/ml-data-frame-analytics-utils'; import type { DecisionPathPlotData } from './use_classification_path_data'; import { formatSingleValue } from '../../../../../formatters/format_value'; -const { euiColorFullShade, euiColorMediumShade } = euiVars; -const axisColor = euiColorMediumShade; - -const baselineStyle: LineAnnotationStyle = { - line: { - strokeWidth: 1, - stroke: euiColorFullShade, - opacity: 0.75, - }, -}; - -const axes: RecursivePartial = { - axisLine: { - stroke: axisColor, - }, - tickLabel: { - fontSize: 10, - fill: axisColor, - }, - tickLine: { - stroke: axisColor, - }, - gridLine: { - horizontal: { - dash: [1, 2], - }, - vertical: { - strokeWidth: 0, - }, - }, -}; -const theme: PartialTheme = { - axes, -}; interface DecisionPathChartProps { decisionPathData: DecisionPathPlotData; @@ -88,6 +53,49 @@ export const DecisionPathChart = ({ maxDomain, baseline, }: DecisionPathChartProps) => { + const { euiTheme } = useEuiTheme(); + + const { baselineStyle, theme } = useMemo<{ + baselineStyle: LineAnnotationStyle; + theme: PartialTheme; + }>(() => { + const euiColorFullShade = euiTheme.colors.fullShade; + const euiColorMediumShade = euiTheme.colors.mediumShade; + const axisColor = euiColorMediumShade; + + const axes: RecursivePartial = { + axisLine: { + stroke: axisColor, + }, + tickLabel: { + fontSize: 10, + fill: axisColor, + }, + tickLine: { + stroke: axisColor, + }, + gridLine: { + horizontal: { + dash: [1, 2], + }, + vertical: { + strokeWidth: 0, + }, + }, + }; + + return { + baselineStyle: { + line: { + strokeWidth: 1, + stroke: euiColorFullShade, + opacity: 0.75, + }, + }, + theme: { axes }, + }; + }, [euiTheme]); + const regressionBaselineData: LineAnnotationDatum[] | undefined = useMemo( () => baseline && isRegressionFeatureImportanceBaseline(baseline) diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/total_feature_importance_summary/feature_importance_summary.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/total_feature_importance_summary/feature_importance_summary.tsx index 9e7371580b12..8a3ac185ef0e 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/total_feature_importance_summary/feature_importance_summary.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/total_feature_importance_summary/feature_importance_summary.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useCallback, useMemo } from 'react'; -import { EuiButtonEmpty, EuiSpacer, EuiText, EuiCallOut } from '@elastic/eui'; +import { useEuiTheme, EuiButtonEmpty, EuiSpacer, EuiText, EuiCallOut } from '@elastic/eui'; import type { RecursivePartial, AxisStyle, PartialTheme, BarSeriesProps } from '@elastic/charts'; import { Chart, @@ -22,7 +22,6 @@ import { import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; -import { euiLightVars as euiVars } from '@kbn/ui-theme'; import { getAnalysisType, isClassificationAnalysis, @@ -40,40 +39,6 @@ import { useMlKibana } from '../../../../../contexts/kibana'; import { ExpandableSection } from '../expandable_section'; -const { euiColorMediumShade } = euiVars; -const axisColor = euiColorMediumShade; - -const axes: RecursivePartial = { - axisLine: { - stroke: axisColor, - }, - tickLabel: { - fontSize: 12, - fill: axisColor, - }, - tickLine: { - stroke: axisColor, - }, - gridLine: { - horizontal: { - dash: [1, 2], - }, - vertical: { - strokeWidth: 0, - }, - }, -}; -const theme: PartialTheme = { - axes, - legend: { - /** - * Added buffer between label and value. - * Smaller values render a more compact legend - */ - spacingBuffer: 100, - }, -}; - export interface FeatureImportanceSummaryPanelProps { totalFeatureImportance: TotalFeatureImportance[]; jobConfig: DataFrameAnalyticsConfig; @@ -94,21 +59,60 @@ const calculateTotalMeanImportance = (featureClass: ClassificationTotalFeatureIm ); }; +interface Datum { + featureName: string; + meanImportance: number; + className?: FeatureImportanceClassName; +} +type PlotData = Datum[]; +type SeriesProps = Omit; + export const FeatureImportanceSummaryPanel: FC = ({ totalFeatureImportance, jobConfig, }) => { + const { euiTheme } = useEuiTheme(); const { services: { docLinks }, } = useMlKibana(); - interface Datum { - featureName: string; - meanImportance: number; - className?: FeatureImportanceClassName; - } - type PlotData = Datum[]; - type SeriesProps = Omit; + const theme: PartialTheme = useMemo(() => { + const euiColorMediumShade = euiTheme.colors.mediumShade; + const axisColor = euiColorMediumShade; + + const axes: RecursivePartial = { + axisLine: { + stroke: axisColor, + }, + tickLabel: { + fontSize: 12, + fill: axisColor, + }, + tickLine: { + stroke: axisColor, + }, + gridLine: { + horizontal: { + dash: [1, 2], + }, + vertical: { + strokeWidth: 0, + }, + }, + }; + + return { + axes, + legend: { + /** + * Added buffer between label and value. + * Smaller values render a more compact legend + */ + spacingBuffer: 100, + }, + }; + }, [euiTheme]); + const [plotData, barSeriesSpec, showLegend, chartHeight] = useMemo< [plotData: PlotData, barSeriesSpec: SeriesProps, showLegend?: boolean, chartHeight?: number] >(() => { diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.test.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.test.tsx index c17490f4506d..6c3508db1db3 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.test.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.test.tsx @@ -203,7 +203,7 @@ describe('Data Frame Analytics: ', () => { ).toBeInTheDocument(); expect( screen.queryByText( - `The saved search 'the-remote-saved-search-title' uses the data view 'my_remote_cluster:index-pattern-title'.` + `The saved Discover session 'the-remote-saved-search-title' uses the data view 'my_remote_cluster:index-pattern-title'.` ) ).toBeInTheDocument(); expect(mockNavigateToPath).toHaveBeenCalledTimes(0); diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.tsx index ff173c47a532..86245a73f89f 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/components/source_selection/source_selection.tsx @@ -67,7 +67,7 @@ export const SourceSelection: FC = () => { i18n.translate( 'xpack.ml.dataFrame.analytics.create.searchSelection.errorGettingDataViewTitle', { - defaultMessage: 'Error loading data view used by the saved search', + defaultMessage: 'Error loading data view used by the saved Discover session', } ) ); @@ -82,7 +82,7 @@ export const SourceSelection: FC = () => { i18n.translate( 'xpack.ml.dataFrame.analytics.create.searchSelection.CcsErrorCallOutBody', { - defaultMessage: `The saved search ''{savedSearchTitle}'' uses the data view ''{dataViewName}''.`, + defaultMessage: `The saved Discover session ''{savedSearchTitle}'' uses the data view ''{dataViewName}''.`, values: { savedSearchTitle: getNestedProperty(savedObject, 'attributes.title'), dataViewName, @@ -132,17 +132,17 @@ export const SourceSelection: FC = () => { noItemsMessage={i18n.translate( 'xpack.ml.dataFrame.analytics.create.searchSelection.notFoundLabel', { - defaultMessage: 'No matching indices or saved searches found.', + defaultMessage: 'No matching indices or saved Discover sessions found.', } )} savedObjectMetaData={[ { type: 'search', - getIconForSavedObject: () => 'search', + getIconForSavedObject: () => 'discoverApp', name: i18n.translate( - 'xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.search', + 'xpack.ml.dataFrame.analytics.create.searchSelection.savedObjectType.discoverSession', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', } ), showSavedObject: (savedObject: SavedObject) => diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape.tsx index 16811a8429d1..de890ad9f9f9 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape.tsx @@ -11,8 +11,7 @@ import { css } from '@emotion/react'; import cytoscape, { type Stylesheet } from 'cytoscape'; // @ts-ignore no declaration file import dagre from 'cytoscape-dagre'; -import { getCytoscapeOptions } from './cytoscape_options'; -import type { EuiThemeType } from '../../../../components/color_range_legend'; +import { useCytoscapeOptions } from './cytoscape_options'; cytoscape.use(dagre); @@ -20,7 +19,6 @@ export const CytoscapeContext = createContext(undefi interface CytoscapeProps { elements: cytoscape.ElementDefinition[]; - theme: EuiThemeType; height: number; itemsDeleted: boolean; resetCy: boolean; @@ -70,21 +68,21 @@ function getLayoutOptions(width: number, height: number) { export function Cytoscape({ children, elements, - theme, height, itemsDeleted, resetCy, style, width, }: PropsWithChildren) { - const cytoscapeOptions = useMemo(() => { + const cytoscapeOptions = useCytoscapeOptions(); + const cytoscapeOptionsWithElements = useMemo(() => { return { - ...getCytoscapeOptions(theme), + ...cytoscapeOptions, elements, }; - }, [theme, elements]); + }, [cytoscapeOptions, elements]); - const [ref, cy] = useCytoscape(cytoscapeOptions); + const [ref, cy] = useCytoscape(cytoscapeOptionsWithElements); // Add the height to the div style. The height is a separate prop because it // is required and can trigger rendering when changed. diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx index 687776790759..9eca6585ac2b 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx @@ -5,9 +5,13 @@ * 2.0. */ +import { useMemo } from 'react'; import type cytoscape from 'cytoscape'; + +import { useEuiFontSize, useEuiTheme, type EuiThemeComputed } from '@elastic/eui'; + import { ANALYSIS_CONFIG_TYPE, JOB_MAP_NODE_TYPES } from '@kbn/ml-data-frame-analytics-utils'; -import type { EuiThemeType } from '../../../../components/color_range_legend'; + import classificationJobIcon from './icons/ml_classification_job.svg'; import outlierDetectionJobIcon from './icons/ml_outlier_detection_job.svg'; import regressionJobIcon from './icons/ml_regression_job.svg'; @@ -57,85 +61,106 @@ function iconForNode(el: cytoscape.NodeSingular) { } } -function borderColorForNode(el: cytoscape.NodeSingular, theme: EuiThemeType) { +function borderColorForNode(el: cytoscape.NodeSingular, euiTheme: EuiThemeComputed) { if (el.selected()) { - return theme.euiColorPrimary; + return euiTheme.colors.primary; } const type = el.data('type'); switch (type) { case JOB_MAP_NODE_TYPES.ANALYTICS_JOB_MISSING: - return theme.euiColorFullShade; + return euiTheme.colors.fullShade; case JOB_MAP_NODE_TYPES.ANALYTICS: - return theme.euiColorVis0; + // Amsterdam + Borealis + return euiTheme.colors.vis.euiColorVis0; case JOB_MAP_NODE_TYPES.TRANSFORM: - return theme.euiColorVis1; + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + return euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2; case JOB_MAP_NODE_TYPES.INDEX: - return theme.euiColorVis2; + // Amsterdam: euiTheme.colors.vis.euiColorVis2 + // Borealis: euiTheme.colors.vis.euiColorVis4 + return euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis2 + : euiTheme.colors.vis.euiColorVis4; case JOB_MAP_NODE_TYPES.TRAINED_MODEL: - return theme.euiColorVis3; + // Amsterdam: euiTheme.colors.vis.euiColorVis3 + // Borealis: euiTheme.colors.vis.euiColorVis5 + return euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis3 + : euiTheme.colors.vis.euiColorVis5; case JOB_MAP_NODE_TYPES.INGEST_PIPELINE: - return theme.euiColorVis7; + // Amsterdam: euiTheme.colors.vis.euiColorVis7 + // Borealis: euiTheme.colors.vis.euiColorVis8 + return euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis7 + : euiTheme.colors.vis.euiColorVis8; default: - return theme.euiColorMediumShade; + return euiTheme.colors.mediumShade; } } -export const getCytoscapeOptions = (theme: EuiThemeType): cytoscape.CytoscapeOptions => { - const lineColor = theme.euiColorLightShade; +export const useCytoscapeOptions = (): cytoscape.CytoscapeOptions => { + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; - return { - autoungrabify: true, - boxSelectionEnabled: false, - maxZoom: 3, - minZoom: 0.2, - style: [ - { - selector: 'node', - style: { - 'background-color': (el: cytoscape.NodeSingular) => - el.data('isRoot') ? theme.euiColorWarning : theme.euiColorGhost, - 'background-height': '60%', - 'background-width': '60%', - 'border-color': (el: cytoscape.NodeSingular) => borderColorForNode(el, theme), - 'border-style': 'solid', - // @ts-ignore - 'background-image': (el: cytoscape.NodeSingular) => iconForNode(el), - 'border-width': (el: cytoscape.NodeSingular) => (el.selected() ? 4 : 3), - color: theme.euiTextColor, - 'font-family': 'Inter UI, Segoe UI, Helvetica, Arial, sans-serif', - 'font-size': theme.euiFontSizeXS, - 'min-zoomed-font-size': parseInt(theme.euiSizeL, 10), - label: 'data(label)', - shape: (el: cytoscape.NodeSingular) => shapeForNode(el), - 'text-background-color': theme.euiColorLightestShade, - 'text-background-opacity': 0, - 'text-background-padding': theme.euiSizeXS, - 'text-background-shape': 'roundrectangle', - 'text-margin-y': parseInt(theme.euiSizeS, 10), - 'text-max-width': '200px', - 'text-valign': 'bottom', - 'text-wrap': 'wrap', + return useMemo( + () => ({ + autoungrabify: true, + boxSelectionEnabled: false, + maxZoom: 3, + minZoom: 0.2, + style: [ + { + selector: 'node', + style: { + 'background-color': (el: cytoscape.NodeSingular) => + el.data('isRoot') ? euiTheme.colors.warning : euiTheme.colors.ghost, + 'background-height': '60%', + 'background-width': '60%', + 'border-color': (el: cytoscape.NodeSingular) => borderColorForNode(el, euiTheme), + 'border-style': 'solid', + // @ts-ignore + 'background-image': (el: cytoscape.NodeSingular) => iconForNode(el), + 'border-width': (el: cytoscape.NodeSingular) => (el.selected() ? 4 : 3), + color: euiTheme.colors.textParagraph, + 'font-family': 'Inter UI, Segoe UI, Helvetica, Arial, sans-serif', + 'font-size': euiFontSizeXS, + 'min-zoomed-font-size': parseInt(euiTheme.size.l, 10), + label: 'data(label)', + shape: (el: cytoscape.NodeSingular) => shapeForNode(el), + 'text-background-color': euiTheme.colors.lightestShade, + 'text-background-opacity': 0, + 'text-background-padding': euiTheme.size.xs, + 'text-background-shape': 'roundrectangle', + 'text-margin-y': parseInt(euiTheme.size.s, 10), + 'text-max-width': '200px', + 'text-valign': 'bottom', + 'text-wrap': 'wrap', + }, }, - }, - { - selector: 'edge', - style: { - 'curve-style': 'taxi', - // @ts-ignore - 'taxi-direction': 'rightward', - 'line-color': lineColor, - 'overlay-opacity': 0, - 'target-arrow-color': lineColor, - 'target-arrow-shape': 'triangle', - // @ts-ignore - 'target-distance-from-node': theme.euiSizeXS, - width: 1, - 'source-arrow-shape': 'none', + { + selector: 'edge', + style: { + 'curve-style': 'taxi', + // @ts-ignore + 'taxi-direction': 'rightward', + 'line-color': euiTheme.colors.lightShade, + 'overlay-opacity': 0, + 'target-arrow-color': euiTheme.colors.lightShade, + 'target-arrow-shape': 'triangle', + // @ts-ignore + 'target-distance-from-node': euiTheme.size.xs, + width: 1, + 'source-arrow-shape': 'none', + }, }, - }, - ], - }; + ], + }), + [euiFontSizeXS, euiTheme] + ); }; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/legend.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/legend.tsx index cf22e9a3f275..0a706aa7a82b 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/legend.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/components/legend.tsx @@ -9,6 +9,7 @@ import type { FC } from 'react'; import React, { useState, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; import { + useEuiTheme, EuiButtonIcon, EuiFlexGroup, EuiFlexItem, @@ -19,7 +20,6 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { JOB_MAP_NODE_TYPES } from '@kbn/ml-data-frame-analytics-utils'; -import type { EuiThemeType } from '../../../../components/color_range_legend'; const getJobTypeList = () => ( <> @@ -33,21 +33,48 @@ const getJobTypeList = () => ( ); -export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType }> = ({ - hasMissingJobNode, - theme, -}) => { +export const JobMapLegend: FC<{ hasMissingJobNode: boolean }> = ({ hasMissingJobNode }) => { + const { euiTheme } = useEuiTheme(); + const [showJobTypes, setShowJobTypes] = useState(false); - const { - euiSizeM, - euiSizeS, - euiColorGhost, - euiColorWarning, - euiBorderThin, - euiBorderRadius, - euiBorderRadiusSmall, - euiBorderWidthThick, - } = theme; + + const euiSizeM = euiTheme.size.m; + const euiSizeS = euiTheme.size.s; + const euiColorFullShade = euiTheme.colors.fullShade; + const euiColorGhost = euiTheme.colors.ghost; + const euiColorWarning = euiTheme.colors.warning; + const euiBorderThin = euiTheme.border.thin; + const euiBorderRadius = euiTheme.border.radius.medium; + const euiBorderRadiusSmall = euiTheme.border.radius.small; + const euiBorderWidthThick = euiTheme.border.width.thick; + const euiPageBackgroundColor = euiTheme.colors.backgroundBasePlain; + + // Amsterdam: euiTheme.colors.vis.euiColorVis2 + // Borealis: euiTheme.colors.vis.euiColorVis4 + const borderColorIndexPattern = euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis2 + : euiTheme.colors.vis.euiColorVis4; + + // Amsterdam: euiTheme.colors.vis.euiColorVis7 + // Borealis: euiTheme.colors.vis.euiColorVis8 + const borderColorIngestPipeline = euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis7 + : euiTheme.colors.vis.euiColorVis8; + + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + const borderColorTransform = euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2; + + // Amsterdam: euiTheme.colors.vis.euiColorVis3 + // Borealis: euiTheme.colors.vis.euiColorVis5 + const borderBottomColorTrainedModel = euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis3 + : euiTheme.colors.vis.euiColorVis5; + + // Amsterdam + Borealis + const borderColorAnalytics = euiTheme.colors.vis.euiColorVis0; const cssOverrideBase = useMemo( () => ({ @@ -91,7 +118,7 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType data-test-subj="mlJobMapLegend__indexPattern" css={{ ...cssOverrideBase, - border: `${euiBorderWidthThick} solid ${theme.euiColorVis2}`, + border: `${euiBorderWidthThick} solid ${borderColorIndexPattern}`, transform: 'rotate(45deg)', }} /> @@ -113,7 +140,7 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType data-test-subj="mlJobMapLegend__ingestPipeline" css={{ ...cssOverrideBase, - border: `${euiBorderWidthThick} solid ${theme.euiColorVis7}`, + border: `${euiBorderWidthThick} solid ${borderColorIngestPipeline}`, borderRadius: euiBorderRadiusSmall, }} /> @@ -135,7 +162,7 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType data-test-subj="mlJobMapLegend__transform" css={{ ...cssOverrideBase, - border: `${euiBorderWidthThick} solid ${theme.euiColorVis1}`, + border: `${euiBorderWidthThick} solid ${borderColorTransform}`, }} />
@@ -154,9 +181,9 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType display: 'inline-block', width: '0px', height: '0px', - borderLeft: `${euiSizeS} solid ${theme.euiPageBackgroundColor}`, - borderRight: `${euiSizeS} solid ${theme.euiPageBackgroundColor}`, - borderBottom: `${euiSizeM} solid ${theme.euiColorVis3}`, + borderLeft: `${euiSizeS} solid ${euiPageBackgroundColor}`, + borderRight: `${euiSizeS} solid ${euiPageBackgroundColor}`, + borderBottom: `${euiSizeM} solid ${borderBottomColorTrainedModel}`, }} /> @@ -178,7 +205,7 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType data-test-subj="mlJobMapLegend__analyticsMissing" css={{ ...cssOverrideBase, - border: `${euiBorderWidthThick} solid ${theme.euiColorFullShade}`, + border: `${euiBorderWidthThick} solid ${euiColorFullShade}`, borderRadius: '50%', }} /> @@ -201,7 +228,7 @@ export const JobMapLegend: FC<{ hasMissingJobNode: boolean; theme: EuiThemeType data-test-subj="mlJobMapLegend__analytics" css={{ ...cssOverrideBase, - border: `${euiBorderWidthThick} solid ${theme.euiColorVis0}`, + border: `${euiBorderWidthThick} solid ${borderColorAnalytics}`, borderRadius: '50%', }} /> diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/job_map.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/job_map.tsx index d03b62bf934a..49a64f7dd5fa 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/job_map.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/job_map/job_map.tsx @@ -9,32 +9,38 @@ import type { FC } from 'react'; import React, { useEffect, useMemo, useState } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; +import { + useEuiTheme, + EuiButtonEmpty, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + type EuiThemeComputed, +} from '@elastic/eui'; import { JOB_MAP_NODE_TYPES } from '@kbn/ml-data-frame-analytics-utils'; -import { useCurrentThemeVars, useMlKibana, useMlLocator } from '../../../contexts/kibana'; +import { useMlKibana, useMlLocator } from '../../../contexts/kibana'; import { Controls, Cytoscape, JobMapLegend } from './components'; import { ML_PAGES } from '../../../../../common/constants/locator'; -import type { EuiThemeType } from '../../../components/color_range_legend'; import { useRefresh } from '../../../routing/use_refresh'; import { useRefDimensions } from './components/use_ref_dimensions'; import { useFetchAnalyticsMapData } from './use_fetch_analytics_map_data'; -const getCytoscapeDivStyle = (theme: EuiThemeType) => ({ +const getCytoscapeDivStyle = (theme: EuiThemeComputed) => ({ background: `linear-gradient( 90deg, - ${theme.euiPageBackgroundColor} - calc(${theme.euiSizeL} - calc(${theme.euiSizeXS} / 2)), + ${theme.colors.backgroundBasePlain} + calc(${theme.size.l} - calc(${theme.size.xs} / 2)), transparent 1% ) center, linear-gradient( - ${theme.euiPageBackgroundColor} - calc(${theme.euiSizeL} - calc(${theme.euiSizeXS} / 2)), + ${theme.colors.backgroundBasePlain} + calc(${theme.size.l} - calc(${theme.size.xs} / 2)), transparent 1% ) center, -${theme.euiColorLightShade}`, - backgroundSize: `${theme.euiSizeL} ${theme.euiSizeL}`, +${theme.colors.lightShade}`, + backgroundSize: `${theme.size.l} ${theme.size.l}`, marginTop: 0, }); @@ -67,7 +73,7 @@ export const JobMap: FC = ({ defaultHeight, analyticsId, modelId, forceRe }, } = useMlKibana(); const locator = useMlLocator()!; - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const refresh = useRefresh(); const redirectToAnalyticsManagementPage = async () => { @@ -162,7 +168,7 @@ export const JobMap: FC = ({ defaultHeight, analyticsId, modelId, forceRe - + = ({ defaultHeight, analyticsId, modelId, forceRe -
+
{ @@ -58,16 +58,16 @@ export const DataDriftIndexOrSearchRedirect: FC = () => { onChoose={onObjectSelection} showFilter noItemsMessage={i18n.translate('xpack.ml.newJob.wizard.searchSelection.notFoundLabel', { - defaultMessage: 'No matching data views or saved searches found.', + defaultMessage: 'No matching data views or saved Discover sessions found.', })} savedObjectMetaData={[ { type: 'search', - getIconForSavedObject: () => 'search', + getIconForSavedObject: () => 'discoverApp', name: i18n.translate( - 'xpack.ml.newJob.wizard.searchSelection.savedObjectType.search', + 'xpack.ml.newJob.wizard.searchSelection.savedObjectType.discoverSession', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', } ), showSavedObject: (savedObject: SavedObject) => diff --git a/x-pack/platform/plugins/shared/ml/public/application/explorer/annotation_timeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/explorer/annotation_timeline.tsx index 3d12c55e05e1..5ab414fd8c31 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/explorer/annotation_timeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/explorer/annotation_timeline.tsx @@ -8,8 +8,11 @@ import React, { type FC, type PropsWithChildren, useEffect } from 'react'; import d3 from 'd3'; import { scaleTime } from 'd3-scale'; + +import { useEuiFontSize, useEuiTheme } from '@elastic/eui'; + import { type ChartTooltipService, type TooltipData } from '../components/chart_tooltip'; -import { useCurrentThemeVars } from '../contexts/kibana'; + import { Y_AXIS_LABEL_PADDING, Y_AXIS_LABEL_WIDTH } from './constants'; export interface AnnotationTimelineProps { @@ -39,7 +42,8 @@ export const AnnotationTimeline = >): ReturnType => { const canvasRef = React.useRef(null); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; useEffect( function renderChart() { @@ -69,8 +73,8 @@ export const AnnotationTimeline = tooltipService.hide()); }); }, - [ - chartWidth, - domain, - data, - tooltipService, - label, - euiTheme.euiTextSubduedColor, - euiTheme.euiFontSizeXS, - euiTheme.euiBorderColor, - getTooltipContent, - ] + [chartWidth, domain, data, tooltipService, label, euiTheme, euiFontSizeXS, getTooltipContent] ); return
; diff --git a/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_annotation_container.tsx b/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_annotation_container.tsx index ce506e03dae3..ec480da71767 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_annotation_container.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_annotation_container.tsx @@ -9,13 +9,18 @@ import type { FC } from 'react'; import React, { useEffect } from 'react'; import d3 from 'd3'; import { scaleTime } from 'd3-scale'; -import { i18n } from '@kbn/i18n'; import moment from 'moment'; -import { useCurrentThemeVars } from '../contexts/kibana'; + +import { useEuiFontSize, useEuiTheme } from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; + import type { Annotation, AnnotationsTable } from '../../../common/types/annotations'; + import type { ChartTooltipService } from '../components/chart_tooltip'; +import { useAnnotationStyles } from '../timeseriesexplorer/styles'; + import { Y_AXIS_LABEL_PADDING, Y_AXIS_LABEL_WIDTH } from './constants'; -import { getAnnotationStyles } from '../timeseriesexplorer/styles'; const ANNOTATION_CONTAINER_HEIGHT = 12; const ANNOTATION_MIN_WIDTH = 8; @@ -30,16 +35,16 @@ interface SwimlaneAnnotationContainerProps { tooltipService: ChartTooltipService; } -const annotationStyles = getAnnotationStyles(); - export const SwimlaneAnnotationContainer: FC = ({ chartWidth, domain, annotationsData, tooltipService, }) => { + const annotationStyles = useAnnotationStyles(); const canvasRef = React.useRef(null); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; useEffect(() => { if (canvasRef.current !== null && Array.isArray(annotationsData)) { @@ -71,8 +76,8 @@ export const SwimlaneAnnotationContainer: FC = .attr('x', Y_AXIS_LABEL_WIDTH - Y_AXIS_LABEL_PADDING) .attr('y', ANNOTATION_CONTAINER_HEIGHT / 2) .attr('dominant-baseline', 'middle') - .style('fill', euiTheme.euiTextSubduedColor) - .style('font-size', euiTheme.euiFontSizeXS); + .style('fill', euiTheme.colors.textSubdued) + .style('font-size', euiFontSizeXS); // Add border svg @@ -81,7 +86,7 @@ export const SwimlaneAnnotationContainer: FC = .attr('y', 0) .attr('height', ANNOTATION_CONTAINER_HEIGHT) .attr('width', endingXPos - startingXPos) - .style('stroke', euiTheme.euiBorderColor) + .style('stroke', euiTheme.border.color) .style('fill', 'none') .style('stroke-width', 1); diff --git a/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_container.tsx b/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_container.tsx index 5dd1440d7d81..7c1118b33cb6 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_container.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/explorer/swimlane_container.tsx @@ -7,13 +7,17 @@ import type { FC } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; + import { + useEuiFontSize, + useEuiTheme, EuiFlexGroup, EuiFlexItem, EuiLoadingChart, EuiResizeObserver, EuiText, } from '@elastic/eui'; + import { throttle } from 'lodash'; import type { BrushEndListener, @@ -62,7 +66,7 @@ import { FormattedTooltip } from '../components/chart_tooltip/chart_tooltip'; import './_explorer.scss'; import { EMPTY_FIELD_VALUE_LABEL } from '../timeseriesexplorer/components/entity_control/entity_control'; import { SWIM_LANE_LABEL_WIDTH, Y_AXIS_LABEL_PADDING } from './constants'; -import { useCurrentThemeVars, useMlKibana } from '../contexts/kibana'; +import { useMlKibana } from '../contexts/kibana'; declare global { interface Window { @@ -205,7 +209,7 @@ export const SwimlaneContainer: FC = ({ } = useMlKibana(); const isDarkTheme = useIsDarkTheme(themeService); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); // Holds the container height for previously fetched data const containerHeightRef = useRef(); @@ -297,18 +301,20 @@ export const SwimlaneContainer: FC = ({ const showBrush = !!onCellsSelection; + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; + const themeOverrides = useMemo(() => { if (!showSwimlane) return {}; const theme: PartialTheme = { background: { - color: euiTheme.euiPanelBackgroundColorModifiers.plain, + color: euiTheme.colors.backgroundBasePlain, }, heatmap: { grid: { stroke: { width: BORDER_WIDTH, - color: euiTheme.euiBorderColor, + color: euiTheme.border.color, }, }, cell: { @@ -318,21 +324,21 @@ export const SwimlaneContainer: FC = ({ visible: false, }, border: { - stroke: euiTheme.euiBorderColor, + stroke: euiTheme.colors.borderBasePlain, strokeWidth: 0, }, }, yAxisLabel: { visible: showYAxis, width: yAxisWidth, - textColor: euiTheme.euiTextSubduedColor, + textColor: euiTheme.colors.textSubdued, padding: Y_AXIS_LABEL_PADDING, - fontSize: parseInt(euiTheme.euiFontSizeXS, 10), + fontSize: parseInt(euiFontSizeXS, 10), }, xAxisLabel: { visible: showTimeline, - textColor: euiTheme.euiTextSubduedColor, - fontSize: parseInt(euiTheme.euiFontSizeXS, 10), + textColor: euiTheme.colors.textSubdued, + fontSize: parseInt(euiFontSizeXS, 10), }, brushMask: { visible: showBrush, diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx index a2f271f243b1..bc7b4b4d3a2f 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx @@ -11,6 +11,7 @@ import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import moment from 'moment'; import { + useEuiTheme, EuiButtonEmpty, EuiCheckbox, EuiDatePicker, @@ -60,7 +61,7 @@ import type { import type { JobMessage } from '../../../../../../common/types/audit_message'; import type { LineAnnotationDatumWithModelSnapshot } from '../../../../../../common/types/results'; import { useToastNotificationService } from '../../../../services/toast_notification_service'; -import { useCurrentThemeVars, useMlApi } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import { RevertModelSnapshotFlyout } from '../../../../components/model_snapshots/revert_model_snapshot_flyout'; import { JobMessagesPane } from '../job_details/job_messages_pane'; import { EditQueryDelay } from './edit_query_delay'; @@ -146,7 +147,7 @@ export const DatafeedChartFlyout: FC = ({ results: { getDatafeedResultChartData }, } = useMlApi(); const { displayErrorToast } = useToastNotificationService(); - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const handleChange = (date: moment.Moment) => setEndDate(date); const handleEndDateChange = (direction: ChartDirectionType) => { if (data.bucketSpan === undefined) return; @@ -479,7 +480,7 @@ export const DatafeedChartFlyout: FC = ({ style={{ line: { strokeWidth: 3, - stroke: euiTheme.euiColorDangerText, + stroke: euiTheme.colors.textDanger, opacity: 0.5, }, }} @@ -494,7 +495,7 @@ export const DatafeedChartFlyout: FC = ({ defaultMessage: 'Annotations rectangle result', } )} - style={{ fill: euiTheme.euiColorDangerText }} + style={{ fill: euiTheme.colors.textDanger }} /> ) : null} @@ -514,7 +515,11 @@ export const DatafeedChartFlyout: FC = ({ style={{ line: { strokeWidth: 3, - stroke: euiTheme.euiColorVis1, + // Amsterdam: euiTheme.colors.vis.euiColorVis1 + // Borealis: euiTheme.colors.vis.euiColorVis2 + stroke: euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis1 + : euiTheme.colors.vis.euiColorVis2, opacity: 0.5, }, }} @@ -537,7 +542,7 @@ export const DatafeedChartFlyout: FC = ({ style={{ line: { strokeWidth: 3, - stroke: euiTheme.euiColorAccent, + stroke: euiTheme.colors.accent, opacity: 0.5, }, }} @@ -546,7 +551,7 @@ export const DatafeedChartFlyout: FC = ({ ) : null} = ({ /> { - this.setDatafeed({ datafeedQuery: query }); - }; - - onQueryDelayChange = (e) => { - this.setDatafeed({ datafeedQueryDelay: e.target.value }); - }; - - onFrequencyChange = (e) => { - this.setDatafeed({ datafeedFrequency: e.target.value }); - }; - - onScrollSizeChange = (e) => { - this.setDatafeed({ datafeedScrollSize: +e.target.value }); - }; - - render() { - const { query, queryDelay, frequency, scrollSize, defaults } = this.state; - const { datafeedRunning } = this.props; - return ( - - - {datafeedRunning && ( - <> - - - - - - )} - - - } - style={{ maxWidth: 'inherit' }} - > - - - - } - > - - - - } - > - - - - } - > - - - - - ); - } -} -Datafeed.propTypes = { - datafeedRunning: PropTypes.bool.isRequired, - datafeedQuery: PropTypes.string.isRequired, - datafeedQueryDelay: PropTypes.string.isRequired, - datafeedFrequency: PropTypes.string.isRequired, - datafeedScrollSize: PropTypes.number.isRequired, - jobBucketSpan: PropTypes.string.isRequired, - setDatafeed: PropTypes.func.isRequired, -}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js deleted file mode 100644 index 0dcc57d30fb0..000000000000 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import PropTypes from 'prop-types'; -import React, { Component } from 'react'; - -import { EuiFieldText, EuiForm, EuiFormRow, EuiSpacer, EuiTitle } from '@elastic/eui'; - -import { FormattedMessage } from '@kbn/i18n-react'; -import { context } from '@kbn/kibana-react-plugin/public'; - -import { detectorToString } from '../../../../../util/string_utils'; - -export class Detectors extends Component { - static contextType = context; - - constructor(props, constructorContext) { - super(props, constructorContext); - - this.state = { - detectors: [], - detectorDescriptions: [], - }; - - this.setDetectorDescriptions = props.setDetectorDescriptions; - } - - static getDerivedStateFromProps(props) { - return { - detectors: props.jobDetectors, - detectorDescriptions: props.jobDetectorDescriptions, - }; - } - - onDescriptionChange = (e, i) => { - const jobDetectorDescriptions = this.state.detectorDescriptions; - jobDetectorDescriptions[i] = e.target.value; - this.setDetectorDescriptions({ jobDetectorDescriptions }); - }; - - render() { - const { detectors, detectorDescriptions } = this.state; - return ( - <> - - -

- -

-
- - - {detectorDescriptions.map((d, i) => ( - - this.onDescriptionChange(e, i)} /> - - ))} - - - ); - } -} -Detectors.propTypes = { - jobDetectors: PropTypes.array.isRequired, - jobDetectorDescriptions: PropTypes.array.isRequired, - setDetectorDescriptions: PropTypes.func.isRequired, -}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_datafeed_tab.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_datafeed_tab.js new file mode 100644 index 000000000000..7c779f57710f --- /dev/null +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_datafeed_tab.js @@ -0,0 +1,175 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; + +import { + EuiFieldText, + EuiForm, + EuiFormRow, + EuiSpacer, + EuiFieldNumber, + EuiCallOut, +} from '@elastic/eui'; + +import { FormattedMessage } from '@kbn/i18n-react'; +import { parseInterval } from '@kbn/ml-parse-interval'; + +import { calculateDatafeedFrequencyDefaultSeconds } from '../../../../../../../common/util/job_utils'; +import { getNewJobDefaults } from '../../../../../services/ml_server_info'; +import { MLJobEditor, ML_EDITOR_MODE } from '../../ml_job_editor'; + +function getDefaults(bucketSpan, jobDefaults) { + const bucketSpanSeconds = bucketSpan !== undefined ? parseInterval(bucketSpan).asSeconds() : ''; + return { + queryDelay: '60s', + frequency: calculateDatafeedFrequencyDefaultSeconds(bucketSpanSeconds) + 's', + scrollSize: jobDefaults.datafeeds.scroll_size, + }; +} + +export class EditDatafeedTab extends Component { + constructor(props) { + super(props); + + this.state = { + query: '', + queryDelay: '', + frequency: '', + scrollSize: '', + defaults: { + queryDelay: '', + frequency: '', + scrollSize: 0, + }, + jobDefaults: getNewJobDefaults(), + }; + + this.setDatafeed = props.setDatafeed; + } + + static getDerivedStateFromProps(props, state) { + return { + query: props.datafeedQuery, + queryDelay: props.datafeedQueryDelay, + frequency: props.datafeedFrequency, + scrollSize: props.datafeedScrollSize, + defaults: getDefaults(props.jobBucketSpan, state.jobDefaults), + }; + } + + onQueryChange = (query) => { + this.setDatafeed({ datafeedQuery: query }); + }; + + onQueryDelayChange = (e) => { + this.setDatafeed({ datafeedQueryDelay: e.target.value }); + }; + + onFrequencyChange = (e) => { + this.setDatafeed({ datafeedFrequency: e.target.value }); + }; + + onScrollSizeChange = (e) => { + this.setDatafeed({ datafeedScrollSize: +e.target.value }); + }; + + render() { + const { query, queryDelay, frequency, scrollSize, defaults } = this.state; + const { datafeedRunning } = this.props; + return ( + + + {datafeedRunning && ( + <> + + + + + + )} + + + } + style={{ maxWidth: 'inherit' }} + > + + + + } + > + + + + } + > + + + + } + > + + + + + ); + } +} +EditDatafeedTab.propTypes = { + datafeedRunning: PropTypes.bool.isRequired, + datafeedQuery: PropTypes.string.isRequired, + datafeedQueryDelay: PropTypes.string.isRequired, + datafeedFrequency: PropTypes.string.isRequired, + datafeedScrollSize: PropTypes.number.isRequired, + jobBucketSpan: PropTypes.string.isRequired, + setDatafeed: PropTypes.func.isRequired, +}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_detectors_tab.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_detectors_tab.js new file mode 100644 index 000000000000..149b94ca9beb --- /dev/null +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_detectors_tab.js @@ -0,0 +1,74 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; + +import { EuiFieldText, EuiForm, EuiFormRow, EuiSpacer, EuiTitle } from '@elastic/eui'; + +import { FormattedMessage } from '@kbn/i18n-react'; +import { context } from '@kbn/kibana-react-plugin/public'; + +import { detectorToString } from '../../../../../util/string_utils'; + +export class EditDetectorsTab extends Component { + static contextType = context; + + constructor(props, constructorContext) { + super(props, constructorContext); + + this.state = { + detectors: [], + detectorDescriptions: [], + }; + + this.setDetectorDescriptions = props.setDetectorDescriptions; + } + + static getDerivedStateFromProps(props) { + return { + detectors: props.jobDetectors, + detectorDescriptions: props.jobDetectorDescriptions, + }; + } + + onDescriptionChange = (e, i) => { + const jobDetectorDescriptions = this.state.detectorDescriptions; + jobDetectorDescriptions[i] = e.target.value; + this.setDetectorDescriptions({ jobDetectorDescriptions }); + }; + + render() { + const { detectors, detectorDescriptions } = this.state; + return ( + <> + + +

+ +

+
+ + + {detectorDescriptions.map((d, i) => ( + + this.onDescriptionChange(e, i)} /> + + ))} + + + ); + } +} +EditDetectorsTab.propTypes = { + jobDetectors: PropTypes.array.isRequired, + jobDetectorDescriptions: PropTypes.array.isRequired, + setDetectorDescriptions: PropTypes.func.isRequired, +}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_job_details_tab.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_job_details_tab.js new file mode 100644 index 000000000000..a56868f8b022 --- /dev/null +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/edit_job_details_tab.js @@ -0,0 +1,274 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; + +import { + EuiFieldText, + EuiForm, + EuiFormRow, + EuiSpacer, + EuiComboBox, + EuiFieldNumber, +} from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { withKibana } from '@kbn/kibana-react-plugin/public'; + +import { tabColor } from '../../../../../../../common/util/group_color_utils'; + +export class EditJobDetailsTabUI extends Component { + constructor(props) { + super(props); + + this.state = { + description: '', + groups: [], + selectedGroups: [], + mml: '', + mmlValidationError: '', + groupsValidationError: '', + modelSnapshotRetentionDays: 1, + dailyModelSnapshotRetentionAfterDays: 1, + }; + + this.setJobDetails = props.setJobDetails; + } + + componentDidMount() { + const euiTheme = this.props.euiTheme; + const mlApi = this.props.kibana.services.mlServices.mlApi; + // load groups to populate the select options + mlApi.jobs + .groups() + .then((resp) => { + const groups = resp.map((g) => ({ label: g.id, color: tabColor(g.id, euiTheme) })); + this.setState({ groups }); + }) + .catch((error) => { + console.error('Could not load groups', error); + }); + } + + static getDerivedStateFromProps(props) { + const selectedGroups = + props.jobGroups !== undefined + ? props.jobGroups.map((g) => ({ label: g, color: tabColor(g, props.euiTheme) })) + : []; + + const { datafeedRunning, jobClosed } = props; + + let mmlHelpText = null; + if (!jobClosed) { + mmlHelpText = ( + + ); + } + + if (datafeedRunning) { + mmlHelpText = ( + + ); + } + + return { + description: props.jobDescription, + selectedGroups, + mml: props.jobModelMemoryLimit, + mmlHelpText, + mmlValidationError: props.jobModelMemoryLimitValidationError, + groupsValidationError: props.jobGroupsValidationError, + modelSnapshotRetentionDays: props.jobModelSnapshotRetentionDays, + dailyModelSnapshotRetentionAfterDays: props.jobDailyModelSnapshotRetentionAfterDays, + }; + } + + onDescriptionChange = (e) => { + this.setJobDetails({ jobDescription: e.target.value }); + }; + + onMmlChange = (e) => { + this.setJobDetails({ jobModelMemoryLimit: e.target.value }); + }; + + onModelSnapshotRetentionDaysChange = (e) => { + const jobModelSnapshotRetentionDays = Math.floor(+e.target.value); + + this.setJobDetails({ + jobModelSnapshotRetentionDays, + ...(this.state.dailyModelSnapshotRetentionAfterDays > jobModelSnapshotRetentionDays + ? { jobDailyModelSnapshotRetentionAfterDays: jobModelSnapshotRetentionDays } + : {}), + }); + }; + + onDailyModelSnapshotRetentionAfterDaysChange = (e) => { + const jobDailyModelSnapshotRetentionAfterDays = Math.floor(+e.target.value); + if (jobDailyModelSnapshotRetentionAfterDays <= this.state.modelSnapshotRetentionDays) { + this.setJobDetails({ jobDailyModelSnapshotRetentionAfterDays }); + } + }; + + onGroupsChange = (selectedGroups) => { + this.setJobDetails({ jobGroups: selectedGroups.map((g) => g.label) }); + }; + + onCreateGroup = (input, flattenedOptions) => { + const normalizedSearchValue = input.trim().toLowerCase(); + + if (!normalizedSearchValue) { + return; + } + + const newGroup = { + label: input, + }; + + const groups = this.state.groups; + // Create the option if it doesn't exist. + if ( + flattenedOptions.findIndex( + (option) => option.label.trim().toLowerCase() === normalizedSearchValue + ) === -1 + ) { + groups.push(newGroup); + } + + const selectedGroups = this.state.selectedGroups.concat(newGroup); + + // update the groups in local state and call onGroupsChange to + // update the selected groups in the component above which manages this + // component's state + this.setState({ groups }, () => this.onGroupsChange(selectedGroups)); + }; + + render() { + const { + description, + selectedGroups, + mml, + groups, + mmlValidationError, + groupsValidationError, + modelSnapshotRetentionDays, + dailyModelSnapshotRetentionAfterDays, + mmlHelpText, + } = this.state; + + const { datafeedRunning, jobClosed } = this.props; + + return ( + + + + + } + > + + + + } + isInvalid={groupsValidationError !== ''} + error={groupsValidationError} + > + + + + } + helpText={mmlHelpText} + isInvalid={mmlValidationError !== ''} + error={mmlValidationError} + > + + + + } + > + + + + } + > + + + + + ); + } +} +EditJobDetailsTabUI.propTypes = { + datafeedRunning: PropTypes.bool.isRequired, + euiTheme: PropTypes.object.isRequired, + jobDescription: PropTypes.string.isRequired, + jobGroups: PropTypes.array.isRequired, + jobModelMemoryLimit: PropTypes.string.isRequired, + setJobDetails: PropTypes.func.isRequired, +}; + +export const EditJobDetailsTab = withKibana(EditJobDetailsTabUI); diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/index.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/index.js index 9ea9b3448541..3b99a6ca59f5 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/index.js +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/index.js @@ -5,6 +5,6 @@ * 2.0. */ -export { JobDetails } from './job_details'; -export { Detectors } from './detectors'; -export { Datafeed } from './datafeed'; +export { EditJobDetailsTab } from './edit_job_details_tab'; +export { EditDetectorsTab } from './edit_detectors_tab'; +export { EditDatafeedTab } from './edit_datafeed_tab'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js deleted file mode 100644 index 322221045b65..000000000000 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js +++ /dev/null @@ -1,272 +0,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 PropTypes from 'prop-types'; -import React, { Component } from 'react'; - -import { - EuiFieldText, - EuiForm, - EuiFormRow, - EuiSpacer, - EuiComboBox, - EuiFieldNumber, -} from '@elastic/eui'; - -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n-react'; -import { withKibana } from '@kbn/kibana-react-plugin/public'; - -import { tabColor } from '../../../../../../../common/util/group_color_utils'; - -export class JobDetailsUI extends Component { - constructor(props) { - super(props); - - this.state = { - description: '', - groups: [], - selectedGroups: [], - mml: '', - mmlValidationError: '', - groupsValidationError: '', - modelSnapshotRetentionDays: 1, - dailyModelSnapshotRetentionAfterDays: 1, - }; - - this.setJobDetails = props.setJobDetails; - } - - componentDidMount() { - const mlApi = this.props.kibana.services.mlServices.mlApi; - // load groups to populate the select options - mlApi.jobs - .groups() - .then((resp) => { - const groups = resp.map((g) => ({ label: g.id, color: tabColor(g.id) })); - this.setState({ groups }); - }) - .catch((error) => { - console.error('Could not load groups', error); - }); - } - - static getDerivedStateFromProps(props) { - const selectedGroups = - props.jobGroups !== undefined - ? props.jobGroups.map((g) => ({ label: g, color: tabColor(g) })) - : []; - - const { datafeedRunning, jobClosed } = props; - - let mmlHelpText = null; - if (!jobClosed) { - mmlHelpText = ( - - ); - } - - if (datafeedRunning) { - mmlHelpText = ( - - ); - } - - return { - description: props.jobDescription, - selectedGroups, - mml: props.jobModelMemoryLimit, - mmlHelpText, - mmlValidationError: props.jobModelMemoryLimitValidationError, - groupsValidationError: props.jobGroupsValidationError, - modelSnapshotRetentionDays: props.jobModelSnapshotRetentionDays, - dailyModelSnapshotRetentionAfterDays: props.jobDailyModelSnapshotRetentionAfterDays, - }; - } - - onDescriptionChange = (e) => { - this.setJobDetails({ jobDescription: e.target.value }); - }; - - onMmlChange = (e) => { - this.setJobDetails({ jobModelMemoryLimit: e.target.value }); - }; - - onModelSnapshotRetentionDaysChange = (e) => { - const jobModelSnapshotRetentionDays = Math.floor(+e.target.value); - - this.setJobDetails({ - jobModelSnapshotRetentionDays, - ...(this.state.dailyModelSnapshotRetentionAfterDays > jobModelSnapshotRetentionDays - ? { jobDailyModelSnapshotRetentionAfterDays: jobModelSnapshotRetentionDays } - : {}), - }); - }; - - onDailyModelSnapshotRetentionAfterDaysChange = (e) => { - const jobDailyModelSnapshotRetentionAfterDays = Math.floor(+e.target.value); - if (jobDailyModelSnapshotRetentionAfterDays <= this.state.modelSnapshotRetentionDays) { - this.setJobDetails({ jobDailyModelSnapshotRetentionAfterDays }); - } - }; - - onGroupsChange = (selectedGroups) => { - this.setJobDetails({ jobGroups: selectedGroups.map((g) => g.label) }); - }; - - onCreateGroup = (input, flattenedOptions) => { - const normalizedSearchValue = input.trim().toLowerCase(); - - if (!normalizedSearchValue) { - return; - } - - const newGroup = { - label: input, - }; - - const groups = this.state.groups; - // Create the option if it doesn't exist. - if ( - flattenedOptions.findIndex( - (option) => option.label.trim().toLowerCase() === normalizedSearchValue - ) === -1 - ) { - groups.push(newGroup); - } - - const selectedGroups = this.state.selectedGroups.concat(newGroup); - - // update the groups in local state and call onGroupsChange to - // update the selected groups in the component above which manages this - // component's state - this.setState({ groups }, () => this.onGroupsChange(selectedGroups)); - }; - - render() { - const { - description, - selectedGroups, - mml, - groups, - mmlValidationError, - groupsValidationError, - modelSnapshotRetentionDays, - dailyModelSnapshotRetentionAfterDays, - mmlHelpText, - } = this.state; - - const { datafeedRunning, jobClosed } = this.props; - - return ( - - - - - } - > - - - - } - isInvalid={groupsValidationError !== ''} - error={groupsValidationError} - > - - - - } - helpText={mmlHelpText} - isInvalid={mmlValidationError !== ''} - error={mmlValidationError} - > - - - - } - > - - - - } - > - - - - - ); - } -} -JobDetailsUI.propTypes = { - datafeedRunning: PropTypes.bool.isRequired, - jobDescription: PropTypes.string.isRequired, - jobGroups: PropTypes.array.isRequired, - jobModelMemoryLimit: PropTypes.string.isRequired, - setJobDetails: PropTypes.func.isRequired, -}; - -export const JobDetails = withKibana(JobDetailsUI); diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/job_group/job_group.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/job_group/job_group.tsx index 562d0c9bc440..5989c35230e8 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/job_group/job_group.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/job_group/job_group.tsx @@ -7,11 +7,17 @@ import type { FC } from 'react'; import React from 'react'; -import { EuiBadge } from '@elastic/eui'; + +import { useEuiTheme, EuiBadge } from '@elastic/eui'; + import { tabColor } from '../../../../../../common/util/group_color_utils'; -export const JobGroup: FC<{ name: string }> = ({ name }) => ( - - {name} - -); +export const JobGroup: FC<{ name: string }> = ({ name }) => { + const { euiTheme } = useEuiTheme(); + + return ( + + {name} + + ); +}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js index b80ad9bcc0e5..9748d8889959 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js @@ -5,6 +5,7 @@ * 2.0. */ +import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; @@ -505,6 +506,7 @@ export class JobsListViewUI extends Component { ) : null} this.refreshJobSummaryList()} @@ -557,4 +559,8 @@ export class JobsListViewUI extends Component { } } +JobsListViewUI.propTypes = { + euiTheme: PropTypes.object.isRequired, +}; + export const JobsListView = withKibana(JobsListViewUI); diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/jobs.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/jobs.tsx index 0516fa1b7986..650748055770 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/jobs.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/jobs_list/jobs.tsx @@ -7,6 +7,7 @@ import type { FC } from 'react'; import React from 'react'; +import { useEuiTheme } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { usePageUrlState } from '@kbn/ml-url-state'; import type { ListingPageUrlState } from '@kbn/ml-url-state'; @@ -44,6 +45,7 @@ export const JobsPage: FC = ({ isMlEnabledInSpace, lastRefresh }) const { services: { docLinks }, } = useMlKibana(); + const { euiTheme } = useEuiTheme(); const { showNodeInfo } = useEnabledFeatures(); const helpLink = docLinks.links.ml.anomalyDetection; @@ -56,6 +58,7 @@ export const JobsPage: FC = ({ isMlEnabledInSpace, lastRefresh }) = memo( ({ existingGroups, selectedGroups, onChange, validation }) => { + const { euiTheme } = useEuiTheme(); + const options = existingGroups.map((g) => ({ label: g, - color: tabColor(g), + color: tabColor(g, euiTheme), })); const selectedOptions = selectedGroups.map((g) => ({ label: g, - color: tabColor(g), + color: tabColor(g, euiTheme), })); function onChangeCallback(optionsIn: EuiComboBoxOptionOption[]) { @@ -46,7 +48,7 @@ export const JobGroupsInput: FC = memo( const newGroup: EuiComboBoxOptionOption = { label: input, - color: tabColor(input), + color: tabColor(input, euiTheme), }; if ( diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/common/settings.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/common/settings.ts index 6f46aabef8aa..38b25b33e002 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/common/settings.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/common/settings.ts @@ -8,18 +8,18 @@ import type { IUiSettingsClient } from '@kbn/core/public'; import type { TimeBuckets } from '@kbn/ml-time-buckets'; import type { AreaSeriesStyle, LineSeriesStyle, RecursivePartial } from '@elastic/charts'; -import { useCurrentThemeVars } from '../../../../../../contexts/kibana'; +import { useEuiTheme } from '@elastic/eui'; import type { JobCreatorType } from '../../../../common/job_creator'; import { isMultiMetricJobCreator, isPopulationJobCreator } from '../../../../common/job_creator'; import { getTimeBucketsFromCache } from '../../../../../../util/get_time_buckets_from_cache'; export function useChartColors() { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); return { - LINE_COLOR: euiTheme.euiColorPrimary, - MODEL_COLOR: euiTheme.euiColorPrimary, - EVENT_RATE_COLOR: euiTheme.euiColorPrimary, - EVENT_RATE_COLOR_WITH_ANOMALIES: euiTheme.euiColorLightShade, + LINE_COLOR: euiTheme.colors.primary, + MODEL_COLOR: euiTheme.colors.primary, + EVENT_RATE_COLOR: euiTheme.colors.primary, + EVENT_RATE_COLOR_WITH_ANOMALIES: euiTheme.colors.lightShade, }; } diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx index f9351ac78352..40d495b76290 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx @@ -7,10 +7,9 @@ import type { FC } from 'react'; import React from 'react'; -import { EuiIcon } from '@elastic/eui'; +import { useEuiTheme, EuiIcon } from '@elastic/eui'; import { timeFormatter } from '@kbn/ml-date-utils'; import { AnnotationDomainType, LineAnnotation, Position, RectAnnotation } from '@elastic/charts'; -import { useCurrentThemeVars } from '../../../../../../contexts/kibana'; interface Props { overlayKey: number; @@ -21,7 +20,7 @@ interface Props { } export const OverlayRange: FC = ({ overlayKey, start, end, color, showMarker = true }) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); return ( <> @@ -57,7 +56,7 @@ export const OverlayRange: FC = ({ overlayKey, start, end, color, showMar marker={showMarker ? : undefined} markerBody={ showMarker ? ( -
+
{timeFormatter(start)}
) : undefined diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/common/json_editor_flyout/json_editor_flyout.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/common/json_editor_flyout/json_editor_flyout.tsx index 6c128bcef12a..467a8e1e66b8 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/common/json_editor_flyout/json_editor_flyout.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/common/json_editor_flyout/json_editor_flyout.tsx @@ -230,7 +230,7 @@ export const JsonEditorFlyout: FC = ({ isDisabled, jobEditorMode, datafee > diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx index eaad9b8ceeac..95755b86de93 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx @@ -153,7 +153,7 @@ export const ChangeDataViewModal: FC = ({ onClose }) => { noItemsMessage={i18n.translate( 'xpack.ml.newJob.wizard.datafeedStep.dataView.step1.noMatchingError', { - defaultMessage: 'No matching indices or saved searches found.', + defaultMessage: 'No matching data views found.', } )} savedObjectMetaData={[ diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx index 601ce327a031..f3946b825cec 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx @@ -7,7 +7,7 @@ import type { FC } from 'react'; import React, { useState, useContext, useEffect, useMemo } from 'react'; -import type { EuiComboBoxOptionOption } from '@elastic/eui'; +import { useEuiTheme, type EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiComboBox } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { JobCreatorContext } from '../../../job_creator_context'; @@ -15,6 +15,8 @@ import { tabColor } from '../../../../../../../../../common/util/group_color_uti import { Description } from './description'; export const GroupsInput: FC = () => { + const { euiTheme } = useEuiTheme(); + const { jobCreator, jobCreatorUpdate, jobValidator, jobValidatorUpdated } = useContext(JobCreatorContext); const { existingJobsAndGroups } = useContext(JobCreatorContext); @@ -42,12 +44,12 @@ export const GroupsInput: FC = () => { const options: EuiComboBoxOptionOption[] = existingJobsAndGroups.groupIds.map((g: string) => ({ label: g, - color: tabColor(g), + color: tabColor(g, euiTheme), })); const selectedOptions: EuiComboBoxOptionOption[] = selectedGroups.map((g: string) => ({ label: g, - color: tabColor(g), + color: tabColor(g, euiTheme), })); function onChange(optionsIn: EuiComboBoxOptionOption[]) { @@ -63,7 +65,7 @@ export const GroupsInput: FC = () => { const newGroup: EuiComboBoxOptionOption = { label: input, - color: tabColor(input), + color: tabColor(input, euiTheme), }; if ( diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/index_or_search/page.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/index_or_search/page.tsx index e0c3e39182af..5423c443dabc 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/index_or_search/page.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/index_or_search/page.tsx @@ -51,7 +51,7 @@ export const Page: FC = ({ @@ -61,16 +61,16 @@ export const Page: FC = ({ onChoose={onObjectSelection} showFilter noItemsMessage={i18n.translate('xpack.ml.newJob.wizard.searchSelection.notFoundLabel', { - defaultMessage: 'No matching data views or saved searches found.', + defaultMessage: 'No matching data views or saved Discover sessions found.', })} savedObjectMetaData={[ { type: 'search', - getIconForSavedObject: () => 'search', + getIconForSavedObject: () => 'discoverApp', name: i18n.translate( - 'xpack.ml.newJob.wizard.searchSelection.savedObjectType.search', + 'xpack.ml.newJob.wizard.searchSelection.savedObjectType.discoverSession', { - defaultMessage: 'Saved search', + defaultMessage: 'Discover session', } ), showSavedObject: (savedObject: SavedObject) => diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/job_type/page.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/job_type/page.tsx index 2d49f1f17727..42b5623605ec 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/job_type/page.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/job_type/page.tsx @@ -95,7 +95,7 @@ export const Page: FC = () => { const pageTitleLabel = selectedSavedSearch ? i18n.translate('xpack.ml.newJob.wizard.jobType.savedSearchPageTitleLabel', { - defaultMessage: 'saved search {savedSearchTitle}', + defaultMessage: 'Discover session {savedSearchTitle}', values: { savedSearchTitle: selectedSavedSearch.title ?? '' }, }) : i18n.translate('xpack.ml.newJob.wizard.jobType.dataViewPageTitleLabel', { @@ -285,7 +285,7 @@ export const Page: FC = () => { diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/new_job/wizard_steps.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/new_job/wizard_steps.tsx index b44c523bc57c..5a00613afa82 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/new_job/wizard_steps.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/new_job/wizard_steps.tsx @@ -74,7 +74,7 @@ export const WizardSteps: FC = ({ currentStep, setCurrentStep }) => { function getSummaryStepTitle() { if (dataSourceContext.selectedSavedSearch) { return i18n.translate('xpack.ml.newJob.wizard.stepComponentWrapper.summaryTitleSavedSearch', { - defaultMessage: 'New job from saved search {title}', + defaultMessage: 'New job from saved Discover session {title}', values: { title: dataSourceContext.selectedSavedSearch.title ?? '' }, }); } else if (dataSourceContext.selectedDataView.id !== undefined) { @@ -123,7 +123,6 @@ export const WizardSteps: FC = ({ currentStep, setCurrentStep }) => { fieldStatsServices={fieldStatsServices} timeRangeMs={timeRangeMs} dslQuery={jobCreator.query} - theme={services.theme} > <> diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index a60fa07fdee8..3e706f0e231d 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -8,6 +8,7 @@ import type { FC } from 'react'; import React, { memo } from 'react'; import { + useEuiTheme, EuiBadge, EuiButtonIcon, EuiFlexGroup, @@ -35,6 +36,8 @@ interface JobItemProps { export const JobItem: FC = memo( ({ job, jobOverride, isSaving, jobPrefix, onEditRequest }) => { + const { euiTheme } = useEuiTheme(); + const { id, config: { description, groups }, @@ -90,7 +93,7 @@ export const JobItem: FC = memo( {(jobGroups ?? []).map((group) => ( - {group} + {group} ))} diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/page.tsx index c65f9b83f859..c2ea2999eee4 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/recognize/page.tsx @@ -94,7 +94,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { const { selectedSavedSearch, selectedDataView: dataView, combinedQuery } = useDataSource(); const pageTitle = selectedSavedSearch ? i18n.translate('xpack.ml.newJob.recognize.savedSearchPageTitle', { - defaultMessage: 'saved search {savedSearchTitle}', + defaultMessage: 'Discover session {savedSearchTitle}', values: { savedSearchTitle: selectedSavedSearch.title ?? '' }, }) : i18n.translate('xpack.ml.newJob.recognize.dataViewPageTitle', { @@ -310,7 +310,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.test.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.test.tsx new file mode 100644 index 000000000000..772fe5996513 --- /dev/null +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.test.tsx @@ -0,0 +1,76 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getClassColor, getClassLabel, getClassIcon } from './ner_output'; + +describe('NER output', () => { + describe('getClassIcon', () => { + test('returns the correct icon for class PER', () => { + expect(getClassIcon('PER')).toBe('user'); + }); + + test('returns the correct icon for class LOC', () => { + expect(getClassIcon('LOC')).toBe('visMapCoordinate'); + }); + + test('returns the correct icon for class ORG', () => { + expect(getClassIcon('ORG')).toBe('home'); + }); + + test('returns the correct icon for class MISC', () => { + expect(getClassIcon('MISC')).toBe('questionInCircle'); + }); + + test('returns the default icon for an unknown class', () => { + expect(getClassIcon('UNKNOWN')).toBe('questionInCircle'); + }); + }); + + describe('getClassLabel', () => { + test('returns the correct label for class PER', () => { + expect(getClassLabel('PER')).toBe('Person'); + }); + + test('returns the correct label for class LOC', () => { + expect(getClassLabel('LOC')).toBe('Location'); + }); + + test('returns the correct label for class ORG', () => { + expect(getClassLabel('ORG')).toBe('Organization'); + }); + + test('returns the correct label for class MISC', () => { + expect(getClassLabel('MISC')).toBe('Miscellaneous'); + }); + + test('returns the class name for an unknown class', () => { + expect(getClassLabel('UNKNOWN')).toBe('UNKNOWN'); + }); + }); + + describe('getClassColor', () => { + test('returns the correct color for class PER', () => { + expect(getClassColor('PER', true)).toBe('#f1d86f'); + }); + + test('returns the correct color for class LOC', () => { + expect(getClassColor('LOC', true)).toBe('#79aad9'); + }); + + test('returns the correct color for class ORG', () => { + expect(getClassColor('ORG', true)).toBe('#6dccb1'); + }); + + test('returns the correct color for class MISC', () => { + expect(getClassColor('MISC', true)).toBe('#f5a35c'); + }); + + test('returns the default color for an unknown class', () => { + expect(getClassColor('UNKNOWN', true)).toBe('#f1d86f'); + }); + }); +}); diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx index 5582a383fe71..aa79f40dac7c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx @@ -11,6 +11,10 @@ import React from 'react'; import useObservable from 'react-use/lib/useObservable'; import { FormattedMessage } from '@kbn/i18n-react'; import { + euiPaletteColorBlind, + euiPaletteColorBlindBehindText, + useEuiFontSize, + useEuiTheme, EuiBadge, EuiFlexGroup, EuiFlexItem, @@ -18,48 +22,71 @@ import { EuiIcon, EuiToolTip, } from '@elastic/eui'; -import { useCurrentThemeVars } from '../../../../contexts/kibana'; -import type { EuiThemeType } from '../../../../components/color_range_legend/use_color_range'; import type { NerInference, NerResponse } from './ner_inference'; import { INPUT_TYPE } from '../inference_base'; +const badgeColorPaletteBorder = euiPaletteColorBlind(); +const badgeColorPaletteBehindText = euiPaletteColorBlindBehindText(); + const ICON_PADDING = '2px'; const PROBABILITY_SIG_FIGS = 3; -const ENTITY_TYPES = { +interface EntityType { + label: string; + icon: string; + colorIndex: number; +} + +const ENTITY_TYPE_NAMES = ['PER', 'LOC', 'ORG', 'MISC'] as const; +const isEntityTypeName = (name: string): name is EntityTypeName => + ENTITY_TYPE_NAMES.includes(name as EntityTypeName); +type EntityTypeName = (typeof ENTITY_TYPE_NAMES)[number]; + +const ENTITY_TYPES: Record = { PER: { label: 'Person', icon: 'user', - color: 'euiColorVis5_behindText', - borderColor: 'euiColorVis5', + // Amsterdam color + colorIndex: 5, }, LOC: { label: 'Location', icon: 'visMapCoordinate', - color: 'euiColorVis1_behindText', - borderColor: 'euiColorVis1', + // Amsterdam color + colorIndex: 1, }, ORG: { label: 'Organization', icon: 'home', - color: 'euiColorVis0_behindText', - borderColor: 'euiColorVis0', + // Amsterdam color + colorIndex: 0, }, MISC: { label: 'Miscellaneous', icon: 'questionInCircle', - color: 'euiColorVis7_behindText', - borderColor: 'euiColorVis7', + // Amsterdam color + colorIndex: 7, }, }; -const UNKNOWN_ENTITY_TYPE = { +const UNKNOWN_ENTITY_TYPE: EntityType = { label: '', icon: 'questionInCircle', - color: 'euiColorVis5_behindText', - borderColor: 'euiColorVis5', + // Amsterdam color + colorIndex: 5, }; +// Amsterdam +// ['#6dccb1', '#79aad9', '#ee789d', '#a987d1', '#e4a6c7', '#f1d86f', '#d2c0a0', '#f5a35c', '#c47c6c', '#ff7e62'] +// Borealis +// ['#00BEB8', '#98E6E2', '#599DFF', '#B4D5FF', '#ED6BA2', '#FFBED5', '#F66D64', '#FFC0B8', '#E6AB01', '#FCD279'] +const amsterdam2BorealisColorMap = new Map([ + [0, 0], + [1, 2], + [5, 9], + [7, 8], +]); + export const getNerOutputComponent = (inferrer: NerInference) => ; const NerOutput: FC<{ inferrer: NerInference }> = ({ inferrer }) => { @@ -86,7 +113,7 @@ const NerOutput: FC<{ inferrer: NerInference }> = ({ inferrer }) => { }; const Lines: FC<{ result: NerResponse }> = ({ result }) => { - const { euiTheme } = useCurrentThemeVars(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; const lineSplit: JSX.Element[] = []; result.response.forEach(({ value, entity }) => { if (entity === null) { @@ -110,7 +137,7 @@ const Lines: FC<{ result: NerResponse }> = ({ result }) => { {value}
-
+
) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs').fontSize; + return ( > = ({ children }) => { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs').fontSize; + + // For Amsterdam, use a `_behindText` variant. Borealis doesn't need it because of updated contrasts. + const badgeColor = euiTheme.flags.hasVisColorAdjustment + ? // @ts-expect-error _behindText is not defined in EuiThemeComputed after Borealis update + euiTheme.colors.vis.euiColorVis5_behindText + : euiTheme.colors.vis.euiColorVis9; + return ( { - const { - euiTheme: { euiColorMediumShade, euiTextSubduedColor, euiTextColor }, - } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); if (response.score >= 5) { return { color: 'success', - textColor: euiTextColor, + textColor: euiTheme.colors.textParagraph, icon: 'check', text: i18n.translate( 'xpack.ml.trainedModels.testModelsFlyout.textExpansion.output.goodMatch', @@ -216,16 +214,16 @@ const useResultStatFormatting = ( if (response.score > 0) { return { - color: euiTextSubduedColor, - textColor: euiTextColor, + color: euiTheme.colors.textSubdued, + textColor: euiTheme.colors.textParagraph, text: null, icon: null, }; } return { - color: euiColorMediumShade, - textColor: euiColorMediumShade, + color: euiTheme.colors.mediumShade, + textColor: euiTheme.colors.mediumShade, text: null, icon: null, }; diff --git a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js index 52ce2b201dd8..349b7406d9d7 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js +++ b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js @@ -12,12 +12,11 @@ import PropTypes from 'prop-types'; import React from 'react'; -import { EuiButtonIcon, EuiIconTip, EuiInMemoryTable, EuiText } from '@elastic/eui'; +import { useEuiTheme, EuiButtonIcon, EuiIconTip, EuiInMemoryTable, EuiText } from '@elastic/eui'; import { formatHumanReadableDateTimeSeconds } from '@kbn/ml-date-utils'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { useCurrentThemeVars } from '../../../contexts/kibana'; function getColumns(viewForecast) { return [ @@ -77,7 +76,7 @@ function getColumns(viewForecast) { } export function ForecastsList({ forecasts, viewForecast, selectedForecastId }) { - const { euiTheme } = useCurrentThemeVars(); + const { euiTheme } = useEuiTheme(); const getRowProps = (item) => { return { @@ -85,7 +84,7 @@ export function ForecastsList({ forecasts, viewForecast, selectedForecastId }) { ...(item.forecast_id === selectedForecastId ? { style: { - backgroundColor: `${euiTheme.euiPanelBackgroundColorModifiers.primary}`, + backgroundColor: `${euiTheme.colors.backgroundBasePrimary}`, }, } : {}), diff --git a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/styles.ts b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/styles.ts index 74ddf0850380..7c4315e01688 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/styles.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/styles.ts @@ -5,9 +5,11 @@ * 2.0. */ +import { useMemo } from 'react'; import { css } from '@emotion/react'; -import { euiThemeVars } from '@kbn/ui-theme'; -import { transparentize } from '@elastic/eui'; + +import { useEuiFontSize, useEuiTheme, transparentize } from '@elastic/eui'; + import { mlColors } from '../styles'; // Annotations constants @@ -15,318 +17,341 @@ const mlAnnotationBorderWidth = '2px'; const mlAnnotationRectDefaultStrokeOpacity = 0.2; const mlAnnotationRectDefaultFillOpacity = 0.05; -export const getTimeseriesExplorerStyles = () => - css({ - color: euiThemeVars.euiColorDarkShade, - - '.ml-timeseries-chart': { - svg: { - fontSize: euiThemeVars.euiFontSizeXS, - fontFamily: euiThemeVars.euiFontFamily, - }, - - '.axis': { - 'path, line': { - fill: 'none', - stroke: euiThemeVars.euiBorderColor, - shapeRendering: 'crispEdges', - pointerEvents: 'none', - }, +export const useTimeseriesExplorerStyles = () => { + const { euiTheme } = useEuiTheme(); + const { fontSize: euiFontSizeXS } = useEuiFontSize('xs', { unit: 'px' }); + const { fontSize: euiFontSizeS } = useEuiFontSize('s', { unit: 'px' }); + + // Amsterdam: euiTheme.colors.vis.euiColorVis5 + // Borealis: euiTheme.colors.vis.euiColorVis9 + const forecastColor = euiTheme.flags.hasVisColorAdjustment + ? euiTheme.colors.vis.euiColorVis5 + : euiTheme.colors.vis.euiColorVis9; + + return useMemo( + () => + css({ + color: euiTheme.colors.darkShade, + + '.ml-timeseries-chart': { + svg: { + fontSize: euiFontSizeXS, + fontFamily: euiTheme.font.family, + }, - text: { - fill: euiThemeVars.euiTextColor, - }, + '.axis': { + 'path, line': { + fill: 'none', + stroke: euiTheme.colors.borderBasePlain, + shapeRendering: 'crispEdges', + pointerEvents: 'none', + }, - '.tick line': { - stroke: euiThemeVars.euiColorLightShade, - }, - }, + text: { + fill: euiTheme.colors.textParagraph, + }, - '.chart-border': { - stroke: euiThemeVars.euiBorderColor, - fill: 'none', - strokeWidth: 1, - shapeRendering: 'crispEdges', - }, + '.tick line': { + stroke: euiTheme.colors.lightShade, + }, + }, - '.chart-border-highlight': { - stroke: euiThemeVars.euiColorDarkShade, - strokeWidth: 2, + '.chart-border': { + stroke: euiTheme.colors.borderBasePlain, + fill: 'none', + strokeWidth: 1, + shapeRendering: 'crispEdges', + }, - '&:hover': { - opacity: 1, - }, - }, + '.chart-border-highlight': { + stroke: euiTheme.colors.darkShade, + strokeWidth: 2, - '.area': { - strokeWidth: 1, + '&:hover': { + opacity: 1, + }, + }, - '&.bounds': { - fill: transparentize(euiThemeVars.euiColorPrimary, 0.2), - pointerEvents: 'none', - }, + '.area': { + strokeWidth: 1, - '&.forecast': { - fill: transparentize(euiThemeVars.euiColorVis5, 0.3), - pointerEvents: 'none', - }, - }, + '&.bounds': { + fill: transparentize(euiTheme.colors.primary, 0.2), + pointerEvents: 'none', + }, - '.values-line': { - fill: 'none', - stroke: euiThemeVars.euiColorPrimary, - strokeWidth: 2, - pointerEvents: 'none', + '&.forecast': { + fill: transparentize(forecastColor, 0.3), + pointerEvents: 'none', + }, + }, - '&.forecast': { - stroke: euiThemeVars.euiColorVis5, - pointerEvents: 'none', - }, - }, - - '.hidden': { - visibility: 'hidden', - }, - - '.values-dots circle': { - fill: euiThemeVars.euiColorPrimary, - strokeWidth: 0, - }, - - '.metric-value': { - opacity: 1, - fill: 'transparent', - stroke: euiThemeVars.euiColorPrimary, - strokeWidth: 0, - }, - - '.anomaly-marker': { - strokeWidth: 1, - stroke: euiThemeVars.euiColorMediumShade, - - '&.critical': { - fill: mlColors.critical, - }, + '.values-line': { + fill: 'none', + stroke: euiTheme.colors.primary, + strokeWidth: 2, + pointerEvents: 'none', - '&.major': { - fill: mlColors.major, - }, + '&.forecast': { + stroke: forecastColor, + pointerEvents: 'none', + }, + }, - '&.minor': { - fill: mlColors.minor, - }, + '.hidden': { + visibility: 'hidden', + }, - '&.warning': { - fill: mlColors.warning, - }, + '.values-dots circle': { + fill: euiTheme.colors.primary, + strokeWidth: 0, + }, - '&.low': { - fill: mlColors.lowWarning, - }, - }, - - '.metric-value:hover, .anomaly-marker:hover, .anomaly-marker.highlighted': { - strokeWidth: 6, - strokeOpacity: 0.65, - stroke: euiThemeVars.euiColorPrimary, - }, - - 'rect.scheduled-event-marker': { - strokeWidth: 1, - stroke: euiThemeVars.euiColorDarkShade, - fill: euiThemeVars.euiColorLightShade, - }, - - '.forecast': { - '.metric-value, .metric-value:hover': { - stroke: euiThemeVars.euiColorVis5, - }, - }, + '.metric-value': { + opacity: 1, + fill: 'transparent', + stroke: euiTheme.colors.primary, + strokeWidth: 0, + }, - '.focus-chart': { - '.x-axis-background': { - line: { - fill: 'none', - shapeRendering: 'crispEdges', - stroke: euiThemeVars.euiColorLightestShade, + '.anomaly-marker': { + strokeWidth: 1, + stroke: euiTheme.colors.mediumShade, + + '&.critical': { + fill: mlColors.critical, + }, + + '&.major': { + fill: mlColors.major, + }, + + '&.minor': { + fill: mlColors.minor, + }, + + '&.warning': { + fill: mlColors.warning, + }, + + '&.low': { + fill: mlColors.lowWarning, + }, }, - rect: { - fill: euiThemeVars.euiColorLightestShade, + + '.metric-value:hover, .anomaly-marker:hover, .anomaly-marker.highlighted': { + strokeWidth: 6, + strokeOpacity: 0.65, + stroke: euiTheme.colors.primary, }, - }, - '.focus-zoom': { - fill: euiThemeVars.euiColorDarkShade, - a: { - text: { - fill: euiThemeVars.euiColorPrimary, - cursor: 'pointer', + + 'rect.scheduled-event-marker': { + strokeWidth: 1, + stroke: euiTheme.colors.darkShade, + fill: euiTheme.colors.lightShade, + }, + + '.forecast': { + '.metric-value, .metric-value:hover': { + stroke: forecastColor, }, - '&:hover, &:active, &:focus': { - textDecoration: 'underline', - fill: euiThemeVars.euiColorPrimary, + }, + + '.focus-chart': { + '.x-axis-background': { + line: { + fill: 'none', + shapeRendering: 'crispEdges', + stroke: euiTheme.colors.lightestShade, + }, + rect: { + fill: euiTheme.colors.lightestShade, + }, + }, + '.focus-zoom': { + fill: euiTheme.colors.darkShade, + a: { + text: { + fill: euiTheme.colors.primary, + cursor: 'pointer', + }, + '&:hover, &:active, &:focus': { + textDecoration: 'underline', + fill: euiTheme.colors.primary, + }, + }, }, }, - }, - }, - '.context-chart': { - '.x.axis path': { - display: 'none', - }, - '.axis text': { - fontSize: '10px', - fill: euiThemeVars.euiTextColor, - }, - '.values-line': { - strokeWidth: 1, - }, - '.mask': { - polygon: { - fillOpacity: 0.1, + '.context-chart': { + '.x.axis path': { + display: 'none', + }, + '.axis text': { + fontSize: '10px', + fill: euiTheme.colors.textParagraph, + }, + '.values-line': { + strokeWidth: 1, + }, + '.mask': { + polygon: { + fillOpacity: 0.1, + }, + '.area.bounds': { + fill: euiTheme.colors.lightShade, + }, + '.values-line': { + strokeWidth: 1, + stroke: euiTheme.colors.mediumShade, + }, + }, + }, + + '.swimlane .axis text': { + display: 'none', }, - '.area.bounds': { - fill: euiThemeVars.euiColorLightShade, + + '.swimlane rect.swimlane-cell-hidden': { + display: 'none', }, - '.values-line': { + + '.brush .extent': { + fillOpacity: 0, + shapeRendering: 'crispEdges', + stroke: euiTheme.colors.darkShade, + strokeWidth: 2, + cursor: 'move', + '&:hover': { + opacity: 1, + }, + }, + + '.top-border': { + fill: euiTheme.colors.emptyShade, + }, + + 'foreignObject.brush-handle': { + pointerEvents: 'none', + paddingTop: '1px', + }, + + 'div.brush-handle-inner': { + border: `1px solid ${euiTheme.colors.darkShade}`, + backgroundColor: euiTheme.colors.lightShade, + height: '70px', + width: '10px', + textAlign: 'center', + cursor: 'ew-resize', + marginTop: '9px', + fontSize: euiFontSizeS, + fill: euiTheme.colors.darkShade, + }, + + 'div.brush-handle-inner-left': { + borderRadius: `${euiTheme.border.radius.small} 0 0 ${euiTheme.border.radius.small}`, + }, + + 'div.brush-handle-inner-right': { + borderRadius: `0 ${euiTheme.border.radius.small} ${euiTheme.border.radius.small} 0`, + }, + + 'rect.brush-handle': { strokeWidth: 1, - stroke: euiThemeVars.euiColorMediumShade, + stroke: euiTheme.colors.darkShade, + fill: euiTheme.colors.lightShade, + pointerEvents: 'none', + '&:hover': { + opacity: 1, + }, }, }, - }, - - '.swimlane .axis text': { - display: 'none', - }, - - '.swimlane rect.swimlane-cell-hidden': { - display: 'none', - }, - - '.brush .extent': { - fillOpacity: 0, - shapeRendering: 'crispEdges', - stroke: euiThemeVars.euiColorDarkShade, - strokeWidth: 2, - cursor: 'move', - '&:hover': { - opacity: 1, - }, - }, - - '.top-border': { - fill: euiThemeVars.euiColorEmptyShade, - }, - - 'foreignObject.brush-handle': { - pointerEvents: 'none', - paddingTop: '1px', - }, - - 'div.brush-handle-inner': { - border: `1px solid ${euiThemeVars.euiColorDarkShade}`, - backgroundColor: euiThemeVars.euiColorLightShade, - height: '70px', - width: '10px', - textAlign: 'center', - cursor: 'ew-resize', - marginTop: '9px', - fontSize: euiThemeVars.euiFontSizeS, - fill: euiThemeVars.euiColorDarkShade, - }, - - 'div.brush-handle-inner-left': { - borderRadius: `${euiThemeVars.euiBorderRadius} 0 0 ${euiThemeVars.euiBorderRadius}`, - }, - - 'div.brush-handle-inner-right': { - borderRadius: `0 ${euiThemeVars.euiBorderRadius} ${euiThemeVars.euiBorderRadius} 0`, - }, - - 'rect.brush-handle': { - strokeWidth: 1, - stroke: euiThemeVars.euiColorDarkShade, - fill: euiThemeVars.euiColorLightShade, - pointerEvents: 'none', - '&:hover': { - opacity: 1, - }, - }, - }, - }); - -export const getAnnotationStyles = () => - css({ - '.ml-annotation': { - '&__brush': { - '.extent': { - stroke: euiThemeVars.euiColorLightShade, - strokeWidth: mlAnnotationBorderWidth, - strokeDasharray: '2 2', - fill: euiThemeVars.euiColorLightestShade, - shapeRendering: 'geometricPrecision', - }, - }, - - '&__rect': { - stroke: euiThemeVars.euiColorFullShade, - strokeWidth: mlAnnotationBorderWidth, - strokeOpacity: mlAnnotationRectDefaultStrokeOpacity, - fill: euiThemeVars.euiColorFullShade, - fillOpacity: mlAnnotationRectDefaultFillOpacity, - shapeRendering: 'geometricPrecision', - transition: `stroke-opacity ${euiThemeVars.euiAnimSpeedFast}, fill-opacity ${euiThemeVars.euiAnimSpeedFast}`, - - '&--highlight': { - strokeOpacity: mlAnnotationRectDefaultStrokeOpacity * 2, - fillOpacity: mlAnnotationRectDefaultFillOpacity * 2, - }, + }), + [euiTheme, euiFontSizeS, euiFontSizeXS, forecastColor] + ); +}; + +export const useAnnotationStyles = () => { + const { euiTheme } = useEuiTheme(); + const euiFontSizeXS = useEuiFontSize('xs', { unit: 'px' }).fontSize as string; + + return useMemo( + () => + css({ + '.ml-annotation': { + '&__brush': { + '.extent': { + stroke: euiTheme.colors.lightShade, + strokeWidth: mlAnnotationBorderWidth, + strokeDasharray: '2 2', + fill: euiTheme.colors.lightestShade, + shapeRendering: 'geometricPrecision', + }, + }, - '&--blur': { - strokeOpacity: mlAnnotationRectDefaultStrokeOpacity / 2, - fillOpacity: mlAnnotationRectDefaultFillOpacity / 2, - }, - }, - - '&__text': { - textAnchor: 'middle', - fontSize: euiThemeVars.euiFontSizeXS, - fontFamily: euiThemeVars.euiFontFamily, - fontWeight: euiThemeVars.euiFontWeightMedium, - fill: euiThemeVars.euiColorFullShade, - transition: `fill ${euiThemeVars.euiAnimSpeedFast}`, - userSelect: 'none', - - '&--blur': { - fill: euiThemeVars.euiColorMediumShade, - }, - }, + '&__rect': { + stroke: euiTheme.colors.fullShade, + strokeWidth: mlAnnotationBorderWidth, + strokeOpacity: mlAnnotationRectDefaultStrokeOpacity, + fill: euiTheme.colors.fullShade, + fillOpacity: mlAnnotationRectDefaultFillOpacity, + shapeRendering: 'geometricPrecision', + transition: `stroke-opacity ${euiTheme.animation.fast}, fill-opacity ${euiTheme.animation.fast}`, + + '&--highlight': { + strokeOpacity: mlAnnotationRectDefaultStrokeOpacity * 2, + fillOpacity: mlAnnotationRectDefaultFillOpacity * 2, + }, - '&__text-rect': { - fill: euiThemeVars.euiColorLightShade, - transition: `fill ${euiThemeVars.euiAnimSpeedFast}`, + '&--blur': { + strokeOpacity: mlAnnotationRectDefaultStrokeOpacity / 2, + fillOpacity: mlAnnotationRectDefaultFillOpacity / 2, + }, + }, - '&--blur': { - fill: euiThemeVars.euiColorLightestShade, - }, - }, - - '&--hidden': { - display: 'none', - }, - - '&__context-rect': { - stroke: euiThemeVars.euiColorFullShade, - strokeWidth: mlAnnotationBorderWidth, - strokeOpacity: mlAnnotationRectDefaultStrokeOpacity, - fill: euiThemeVars.euiColorFullShade, - fillOpacity: mlAnnotationRectDefaultFillOpacity, - transition: `stroke-opacity ${euiThemeVars.euiAnimSpeedFast}, fill-opacity ${euiThemeVars.euiAnimSpeedFast}`, - shapeRendering: 'geometricPrecision', - - '&--blur': { - strokeOpacity: mlAnnotationRectDefaultStrokeOpacity / 2, - fillOpacity: mlAnnotationRectDefaultFillOpacity / 2, + '&__text': { + textAnchor: 'middle', + fontSize: euiFontSizeXS, + fontFamily: euiTheme.font.family, + fontWeight: euiTheme.font.weight.medium, + fill: euiTheme.colors.fullShade, + transition: `fill ${euiTheme.animation.fast}`, + userSelect: 'none', + + '&--blur': { + fill: euiTheme.colors.mediumShade, + }, + }, + + '&__text-rect': { + fill: euiTheme.colors.lightShade, + transition: `fill ${euiTheme.animation.fast}`, + + '&--blur': { + fill: euiTheme.colors.lightestShade, + }, + }, + + '&--hidden': { + display: 'none', + }, + + '&__context-rect': { + stroke: euiTheme.colors.fullShade, + strokeWidth: mlAnnotationBorderWidth, + strokeOpacity: mlAnnotationRectDefaultStrokeOpacity, + fill: euiTheme.colors.fullShade, + fillOpacity: mlAnnotationRectDefaultFillOpacity, + transition: `stroke-opacity ${euiTheme.animation.fast}, fill-opacity ${euiTheme.animation.fast}`, + shapeRendering: 'geometricPrecision', + + '&--blur': { + strokeOpacity: mlAnnotationRectDefaultStrokeOpacity / 2, + fillOpacity: mlAnnotationRectDefaultFillOpacity / 2, + }, + }, }, - }, - }, - }); + }), + [euiTheme, euiFontSizeXS] + ); +}; diff --git a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/timeseriesexplorer_page.tsx b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/timeseriesexplorer_page.tsx index c998dda0bcd9..a3be4319de78 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/timeseriesexplorer_page.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/timeseriesexplorer_page.tsx @@ -19,7 +19,7 @@ import { HelpMenu } from '../components/help_menu'; import { useMlKibana } from '../contexts/kibana'; import { MlPageHeader } from '../components/page_header'; import { PageTitle } from '../components/page_title'; -import { getAnnotationStyles, getTimeseriesExplorerStyles } from './styles'; +import { useAnnotationStyles, useTimeseriesExplorerStyles } from './styles'; interface TimeSeriesExplorerPageProps { dateFormatTz?: string; @@ -35,9 +35,6 @@ interface TimeSeriesExplorerPageProps { selectedJobId?: string[]; } -const timeseriesExplorerStyles = getTimeseriesExplorerStyles(); -const annotationStyles = getAnnotationStyles(); - export const TimeSeriesExplorerPage: FC> = ({ children, dateFormatTz, @@ -53,6 +50,9 @@ export const TimeSeriesExplorerPage: FC
{ - const color = tabColor(geoField); + const color = tabColor(geoField, euiTheme); initialLayers.push({ id: htmlIdGenerator()(), diff --git a/x-pack/platform/plugins/shared/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx b/x-pack/platform/plugins/shared/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx index 39f22e2e988d..1ab62d914078 100644 --- a/x-pack/platform/plugins/shared/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx +++ b/x-pack/platform/plugins/shared/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx @@ -32,8 +32,8 @@ import type { SingleMetricViewerEmbeddableApi, } from '../../embeddables/types'; import { - getTimeseriesExplorerStyles, - getAnnotationStyles, + useTimeseriesExplorerStyles, + useAnnotationStyles, } from '../../application/timeseriesexplorer/styles'; const containerPadding = 20; @@ -88,9 +88,6 @@ export interface SingleMetricViewerProps { type Zoom = AppStateZoom | undefined; type ForecastId = string | undefined; -const timeseriesExplorerStyles = getTimeseriesExplorerStyles(); -const annotationStyles = getAnnotationStyles(); - const SingleMetricViewerWrapper: FC = ({ // Component dependencies api, @@ -111,6 +108,8 @@ const SingleMetricViewerWrapper: FC = ({ shouldShowForecastButton, uuid, }) => { + const timeseriesExplorerStyles = useTimeseriesExplorerStyles(); + const annotationStyles = useAnnotationStyles(); const [chartDimensions, setChartDimensions] = useState<{ width: number; height: number }>({ width: 0, height: 0, diff --git a/x-pack/platform/plugins/shared/ml/server/plugin.ts b/x-pack/platform/plugins/shared/ml/server/plugin.ts index e40bed733f0d..beeab9767d95 100644 --- a/x-pack/platform/plugins/shared/ml/server/plugin.ts +++ b/x-pack/platform/plugins/shared/ml/server/plugin.ts @@ -138,7 +138,7 @@ export class MlServerPlugin catalogue: [PLUGIN_ID, `${PLUGIN_ID}_file_data_visualizer`], privilegesTooltip: i18n.translate('xpack.ml.featureRegistry.privilegesTooltip', { defaultMessage: - 'Granting All or Read feature privilege for Machine Learning will also grant the equivalent feature privileges to certain types of Kibana saved objects, namely index patterns, dashboards, saved searches and visualizations as well as machine learning job, trained model and module saved objects.', + 'Granting All or Read feature privilege for Machine Learning will also grant the equivalent feature privileges to certain types of Kibana saved objects, namely index patterns, dashboards, saved Discover sessions and visualizations as well as machine learning job, trained model and module saved objects.', }), management: { insightsAndAlerting: ['jobsListLink', 'triggersActions'], diff --git a/x-pack/platform/plugins/shared/ml/tsconfig.json b/x-pack/platform/plugins/shared/ml/tsconfig.json index b65618569ec7..dce8710d648f 100644 --- a/x-pack/platform/plugins/shared/ml/tsconfig.json +++ b/x-pack/platform/plugins/shared/ml/tsconfig.json @@ -128,7 +128,6 @@ "@kbn/test-jest-helpers", "@kbn/triggers-actions-ui-plugin", "@kbn/ui-actions-plugin", - "@kbn/ui-theme", "@kbn/unified-field-list", "@kbn/unified-search-plugin", "@kbn/usage-collection-plugin", diff --git a/x-pack/platform/plugins/shared/observability_solution/observability_ai_assistant/server/utils/recall/score_suggestions.ts b/x-pack/platform/plugins/shared/observability_solution/observability_ai_assistant/server/utils/recall/score_suggestions.ts index 7d1a19463cce..b57e5928ce0b 100644 --- a/x-pack/platform/plugins/shared/observability_solution/observability_ai_assistant/server/utils/recall/score_suggestions.ts +++ b/x-pack/platform/plugins/shared/observability_solution/observability_ai_assistant/server/utils/recall/score_suggestions.ts @@ -102,7 +102,7 @@ export async function scoreSuggestions({ type: 'string', }, }, - required: ['score'], + required: ['scores'], } as const, }; diff --git a/x-pack/platform/plugins/shared/screenshotting/README.md b/x-pack/platform/plugins/shared/screenshotting/README.md new file mode 100644 index 000000000000..b129bbb5ad9a --- /dev/null +++ b/x-pack/platform/plugins/shared/screenshotting/README.md @@ -0,0 +1,156 @@ +# Kibana Screenshotting + +This plugin provides functionality to take screenshots of the Kibana pages. +It uses Chromium and Puppeteer underneath to run the browser in headless mode. + +## Capabilities +- Canvas workpads screenshots. +- Dashboards screenshots. +- Expressions screenshots. +- PDF generation. +- Batch screenshotting. + +## Usage + +### Getting started +After listing the `screenshotting` plugin in your dependencies, the plugin will be intitalized on the setup stage. +The intitalization process downloads (if it is not already present) and verifies the Chromium build. + +The start contract exposes a public API to interact with the plugin. +Apart from the actual screenshotting functionality, it also provides a way for self-diagnostics. + +Here is an example of how you can take a screenshot of a Kibana URL. + +```typescript +import { lastValueFrom } from 'rxjs'; +import type { CoreSetup, Plugin } from 'src/core/server'; +import type { ScreenshottingStart } from 'x-pack/platform/plugins/shared/screenshotting/server'; + + +interface StartDeps { + screenshotting: ScreenshottingStart; +} + +class ExamplePlugin implements Plugin { + setup({ http, getStartServices }: CoreSetup) { + const router = http.createRouter(); + + router.get( + { + path: '/api/capture', + validate: { + query: schema.object({ + id: schema.string(), + }), + }, + }, + async (context, request, response) => { + const [, { screenshotting }] = await getStartServices(); + const { metrics, results } = await lastValueFrom( + screenshotting.getScreenshots({ + request, + urls: [`http://localhost/app/canvas#/workpad/workpad-${request.query.id}`], + }) + ); + + return response.ok({ + body: JSON.stringify({ + metrics, + image: results[0]?.screenshots[0]?.data.toString('base64'), + errors: results[0]?.renderErrors, + } as ScreenshottingExpressionResponse), + }); + } + ); + } + + start() {} +} + +export function plugin() { + return new ExamplePlugin(); +} +``` + +### API +Please use automatically generated API reference or generated TypeDoc comments to find the complete documentation. + +#### `getScreenshots(options): Observable` +Takes screenshots of multiple pages or an expression and returns an observable with the screenshotting results. + +The `options` parameter is an object with parameters of the screenshotting session. +Option | Required | Default | Description +--- | :---: | --- | --- +`browserTimezone` | no | _none_ | The browser timezone that will be emulated in the browser instance. This option should be used to keep timezone on server and client in sync. +`expression` | no | _none_ | An expression to capture screenshot of. Mutually exclusive with the `urls` parameter. +`format` | no | `'png'` | An output format. It can either be PDF or PNG. In case of capturing multiple URLs, all the screenshots will be combined into one document for PDF format. For PNG format, an array of screenshots will be returned. +`headers` | no | _none_ | Custom headers to be sent with each request. The headers will be used for authorization. +`input` | no | `undefined` | The expression input. +`layout` | no | `{}` | Page layout parameters describing characteristics of the capturing screenshot (e.g., dimensions, zoom, etc.). +`request` | no | _none_ | Kibana Request reference to extract headers from. +`timeouts` | no | _none_ | Timeouts for each phase of the screenshot. +`timeouts.openUrl` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for the "Loading…" screen to dismiss and find the initial data for the page. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. +`timeouts.renderComplete` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for all visualizations to fetch and render the data. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. +`timeouts.waitForElements` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for all visualization panels to load on the page. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. +`urls` | no | `[]` | The list or URL to take screenshots of. Every item can either be a string or a tuple containing a URL and a context. The contextual data can be gathered using the screenshot mode plugin. Mutually exclusive with the `expression` parameter. + +#### `diagnose(flags?: string[]): Observable` +Runs browser diagnostics. +The diagnostic implementation launches Chromium and emits the output in the resulting observable. + +There is a way to override some Chromium command line arguments using the `flags` parameter. + +### Configuration +Option | Default | Description +--- | --- | --- +`xpack.screenshotting.networkPolicy.enabled` | `true` | Capturing a screenshot from a Kibana page involves sending out requests for all the linked web assets. For example, a Markdown visualization can show an image from a remote server. +`xpack.screenshotting.networkPolicy.rules` | Allow http, https, ws, wss, and data. | A policy is specified as an array of objects that describe what to allow or deny based on a host or protocol. If a host or protocol is not specified, the rule matches any host or protocol. +`xpack.screenshotting.browser.autoDownload` | Depends on the `dist` parameter. | Flag to automatically download chromium distribution. +`xpack.screenshotting.browser.chromium.disableSandbox` | Defaults to `false` for all operating systems except Debian and Red Hat Linux, which use `true`. | It is recommended that you research the feasibility of enabling unprivileged user namespaces. An exception is if you are running Kibana in Docker because the container runs in a user namespace with the built-in seccomp/bpf filters. For more information, refer to [Chromium sandbox](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/linux/sandboxing.md). +`xpack.screenshotting.browser.chromium.proxy.enabled` | `false` | Enables the proxy for Chromium to use. +`xpack.screenshotting.browser.chromium.proxy.server` | _none_ | The uri for the proxy server. Providing the username and password for the proxy server via the uri is not supported. +`xpack.screenshotting.browser.chromium.proxy.bypass` | `[]` | An array of hosts that should not go through the proxy server and should use a direct connection instead. Examples of valid entries are "elastic.co", "*.elastic.co", ".elastic.co", ".elastic.co:5601". + +## How It Works +```mermaid +sequenceDiagram + participant User + participant Screenshotting + participant Browser + + User ->> Screenshotting: API call + Screenshotting ->> Browser: Launch browser + activate Browser + Screenshotting ->> Browser: Create page + Screenshotting ->> Browser: Set parameters + Note over Screenshotting,Browser: timezone + + Screenshotting ->> Browser: Open URL + Screenshotting ->> Browser: Set contextual data + Note over Screenshotting,Browser: custom context, screenshot mode flag + Browser ->> Screenshotting: Rendering + + Screenshotting ->> Browser: Wait for visualizations + Note over Screenshotting,Browser: poll for a number of DOM nodes to match
the number of dashboard elements + Screenshotting ->> Browser: Wait for render completion + Note over Screenshotting,Browser: poll for selectors indicating rendering completion + Browser ->> Screenshotting: Page is ready + + Screenshotting ->> Browser: Take screenshot + Browser ->> Screenshotting: Return PNG buffer + Screenshotting ->> User: Return screenshot +``` + +## Testing +### Integration +There is an example plugin that demonstrates integration with the screenshotting plugin. That plugin utilizes expression capturing. + +### Chromium Downloads +To download all Chromium browsers for all platforms and architectures: + +```bash +cd x-pack +npx gulp downloadChromium +``` + +This command is used to provision CI workspaces so that Chromium does not need to be downloaded for every CI run. diff --git a/x-pack/plugins/screenshotting/common/errors.ts b/x-pack/platform/plugins/shared/screenshotting/common/errors.ts similarity index 100% rename from x-pack/plugins/screenshotting/common/errors.ts rename to x-pack/platform/plugins/shared/screenshotting/common/errors.ts diff --git a/x-pack/plugins/screenshotting/common/expression.ts b/x-pack/platform/plugins/shared/screenshotting/common/expression.ts similarity index 100% rename from x-pack/plugins/screenshotting/common/expression.ts rename to x-pack/platform/plugins/shared/screenshotting/common/expression.ts diff --git a/x-pack/plugins/screenshotting/common/index.ts b/x-pack/platform/plugins/shared/screenshotting/common/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/common/index.ts rename to x-pack/platform/plugins/shared/screenshotting/common/index.ts diff --git a/x-pack/plugins/screenshotting/common/layout.ts b/x-pack/platform/plugins/shared/screenshotting/common/layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/common/layout.ts rename to x-pack/platform/plugins/shared/screenshotting/common/layout.ts diff --git a/x-pack/plugins/screenshotting/common/types.ts b/x-pack/platform/plugins/shared/screenshotting/common/types.ts similarity index 100% rename from x-pack/plugins/screenshotting/common/types.ts rename to x-pack/platform/plugins/shared/screenshotting/common/types.ts diff --git a/x-pack/platform/plugins/shared/screenshotting/jest.config.js b/x-pack/platform/plugins/shared/screenshotting/jest.config.js new file mode 100644 index 000000000000..0fd6d74a1d65 --- /dev/null +++ b/x-pack/platform/plugins/shared/screenshotting/jest.config.js @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/platform/plugins/shared/screenshotting'], + coverageDirectory: + '/target/kibana-coverage/jest/x-pack/platform/plugins/shared/screenshotting', + coverageReporters: ['text', 'html'], + collectCoverageFrom: ['/x-pack/platform/plugins/shared/screenshotting/server/**/*.{ts}'], +}; diff --git a/x-pack/plugins/screenshotting/jest.integration.config.js b/x-pack/platform/plugins/shared/screenshotting/jest.integration.config.js similarity index 76% rename from x-pack/plugins/screenshotting/jest.integration.config.js rename to x-pack/platform/plugins/shared/screenshotting/jest.integration.config.js index 45a65c93c6af..d0694061ed92 100644 --- a/x-pack/plugins/screenshotting/jest.integration.config.js +++ b/x-pack/platform/plugins/shared/screenshotting/jest.integration.config.js @@ -7,6 +7,6 @@ module.exports = { preset: '@kbn/test/jest_integration', - rootDir: '../../..', - roots: ['/x-pack/plugins/screenshotting'], + rootDir: '../../../../..', + roots: ['/x-pack/platform/plugins/shared/screenshotting'], }; diff --git a/x-pack/plugins/screenshotting/kibana.jsonc b/x-pack/platform/plugins/shared/screenshotting/kibana.jsonc similarity index 100% rename from x-pack/plugins/screenshotting/kibana.jsonc rename to x-pack/platform/plugins/shared/screenshotting/kibana.jsonc diff --git a/x-pack/plugins/screenshotting/public/app/app.scss b/x-pack/platform/plugins/shared/screenshotting/public/app/app.scss similarity index 100% rename from x-pack/plugins/screenshotting/public/app/app.scss rename to x-pack/platform/plugins/shared/screenshotting/public/app/app.scss diff --git a/x-pack/plugins/screenshotting/public/app/app.tsx b/x-pack/platform/plugins/shared/screenshotting/public/app/app.tsx similarity index 100% rename from x-pack/plugins/screenshotting/public/app/app.tsx rename to x-pack/platform/plugins/shared/screenshotting/public/app/app.tsx diff --git a/x-pack/plugins/screenshotting/public/app/index.ts b/x-pack/platform/plugins/shared/screenshotting/public/app/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/public/app/index.ts rename to x-pack/platform/plugins/shared/screenshotting/public/app/index.ts diff --git a/x-pack/plugins/screenshotting/public/app/screenshot_mode_context.ts b/x-pack/platform/plugins/shared/screenshotting/public/app/screenshot_mode_context.ts similarity index 100% rename from x-pack/plugins/screenshotting/public/app/screenshot_mode_context.ts rename to x-pack/platform/plugins/shared/screenshotting/public/app/screenshot_mode_context.ts diff --git a/x-pack/plugins/screenshotting/public/index.ts b/x-pack/platform/plugins/shared/screenshotting/public/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/public/index.ts rename to x-pack/platform/plugins/shared/screenshotting/public/index.ts diff --git a/x-pack/plugins/screenshotting/public/plugin.tsx b/x-pack/platform/plugins/shared/screenshotting/public/plugin.tsx similarity index 100% rename from x-pack/plugins/screenshotting/public/plugin.tsx rename to x-pack/platform/plugins/shared/screenshotting/public/plugin.tsx diff --git a/x-pack/plugins/screenshotting/server/__mocks__/puppeteer.ts b/x-pack/platform/plugins/shared/screenshotting/server/__mocks__/puppeteer.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/__mocks__/puppeteer.ts rename to x-pack/platform/plugins/shared/screenshotting/server/__mocks__/puppeteer.ts diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/noto/LICENSE_OFL.txt b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/LICENSE_OFL.txt similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/noto/LICENSE_OFL.txt rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/LICENSE_OFL.txt diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Medium.ttf diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/NotoSansCJKtc-Regular.ttf diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/noto/index.js b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/index.js similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/noto/index.js rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/noto/index.js diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/roboto/LICENSE.txt b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/LICENSE.txt similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/roboto/LICENSE.txt rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/LICENSE.txt diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Italic.ttf diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Medium.ttf diff --git a/x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf b/x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf rename to x-pack/platform/plugins/shared/screenshotting/server/assets/fonts/roboto/Roboto-Regular.ttf diff --git a/x-pack/plugins/screenshotting/server/assets/img/logo-grey.png b/x-pack/platform/plugins/shared/screenshotting/server/assets/img/logo-grey.png similarity index 100% rename from x-pack/plugins/screenshotting/server/assets/img/logo-grey.png rename to x-pack/platform/plugins/shared/screenshotting/server/assets/img/logo-grey.png diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/index.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/index.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/metrics.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/metrics.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/metrics.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/metrics.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/metrics.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/metrics.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/metrics.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/metrics.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/integration_tests/downloads.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/integration_tests/downloads.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/integration_tests/downloads.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/integration_tests/downloads.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/strip_unsafe_headers.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/strip_unsafe_headers.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/strip_unsafe_headers.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/strip_unsafe_headers.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/strip_unsafe_headers.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/strip_unsafe_headers.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/strip_unsafe_headers.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/strip_unsafe_headers.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/templates/footer.handlebars.html b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/footer.handlebars.html similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/templates/footer.handlebars.html rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/footer.handlebars.html diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/templates/header.handlebars.html b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/header.handlebars.html similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/templates/header.handlebars.html rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/header.handlebars.html diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/templates/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/chromium/templates/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/templates/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/checksum.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/checksum.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/checksum.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/checksum.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/checksum.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/checksum.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/checksum.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/checksum.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/fetch.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/fetch.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/fetch.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/fetch.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/fetch.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/fetch.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/fetch.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/fetch.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/index.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/index.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/index.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/index.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/download/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/download/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/download/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/download/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/__fixtures__/file.md b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/__fixtures__/file.md similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/__fixtures__/file.md rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/__fixtures__/file.md diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/__fixtures__/file.md.zip b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/__fixtures__/file.md.zip similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/__fixtures__/file.md.zip rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/__fixtures__/file.md.zip diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/extract.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/extract.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/extract.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/extract.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/extract_error.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract_error.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/extract_error.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/extract_error.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/unzip.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/unzip.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/extract/unzip.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/extract/unzip.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/extract/unzip.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/index.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/install.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/install.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/install.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/install.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/mock.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/mock.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/mock.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/mock.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/network_policy.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/network_policy.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/network_policy.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/network_policy.test.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/network_policy.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/network_policy.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/network_policy.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/network_policy.ts diff --git a/x-pack/plugins/screenshotting/server/browsers/safe_child_process.ts b/x-pack/platform/plugins/shared/screenshotting/server/browsers/safe_child_process.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/browsers/safe_child_process.ts rename to x-pack/platform/plugins/shared/screenshotting/server/browsers/safe_child_process.ts diff --git a/x-pack/plugins/screenshotting/server/cloud/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/cloud/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/cloud/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/cloud/index.ts diff --git a/x-pack/plugins/screenshotting/server/config/schema.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/config/schema.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/config/schema.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/config/schema.test.ts diff --git a/x-pack/plugins/screenshotting/server/constants.ts b/x-pack/platform/plugins/shared/screenshotting/server/constants.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/constants.ts rename to x-pack/platform/plugins/shared/screenshotting/server/constants.ts diff --git a/x-pack/plugins/screenshotting/server/formats/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/index.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/index.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/README.md b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/README.md similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/README.md rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/README.md diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/constants.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/constants.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/constants.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/constants.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_doc_options.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_doc_options.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_doc_options.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_doc_options.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_font.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_font.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_font.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_font.test.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_font.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_font.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_font.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_font.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_template.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_template.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/get_template.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/get_template.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/index.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/buggy_worker.js b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/buggy_worker.js similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/buggy_worker.js rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/buggy_worker.js diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/memory_leak_worker.js b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/memory_leak_worker.js similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/memory_leak_worker.js rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/memory_leak_worker.js diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/pdfmaker.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/pdfmaker.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/integration_tests/pdfmaker.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/integration_tests/pdfmaker.test.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/pdfmaker.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/pdfmaker.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/pdfmaker.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/pdfmaker.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/types.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/types.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/types.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/types.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_dependencies.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker_dependencies.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_dependencies.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker_dependencies.ts diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js similarity index 90% rename from x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js rename to x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js index ca319ace9d02..05a6c8eaa975 100644 --- a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js +++ b/x-pack/platform/plugins/shared/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js @@ -11,6 +11,6 @@ */ // eslint-disable-next-line @kbn/imports/no_boundary_crossing -require('../../../../../../../src/setup_node_env'); +require('../../../../../../../../../src/setup_node_env'); // eslint-disable-next-line @kbn/imports/uniform_imports require('./worker.ts'); diff --git a/x-pack/plugins/screenshotting/server/formats/png.ts b/x-pack/platform/plugins/shared/screenshotting/server/formats/png.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/formats/png.ts rename to x-pack/platform/plugins/shared/screenshotting/server/formats/png.ts diff --git a/x-pack/plugins/screenshotting/server/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/index.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/base_layout.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/base_layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/base_layout.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/base_layout.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/canvas_layout.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/canvas_layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/canvas_layout.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/canvas_layout.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/create_layout.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/create_layout.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/create_layout.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/create_layout.test.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/create_layout.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/create_layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/create_layout.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/create_layout.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/index.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/mock.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/mock.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/mock.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/mock.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/preserve_layout.css b/x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.css similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/preserve_layout.css rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.css diff --git a/x-pack/plugins/screenshotting/server/layouts/preserve_layout.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/preserve_layout.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.test.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/preserve_layout.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/preserve_layout.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/preserve_layout.ts diff --git a/x-pack/plugins/screenshotting/server/layouts/print_layout.ts b/x-pack/platform/plugins/shared/screenshotting/server/layouts/print_layout.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/layouts/print_layout.ts rename to x-pack/platform/plugins/shared/screenshotting/server/layouts/print_layout.ts diff --git a/x-pack/plugins/screenshotting/server/mock.ts b/x-pack/platform/plugins/shared/screenshotting/server/mock.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/mock.ts rename to x-pack/platform/plugins/shared/screenshotting/server/mock.ts diff --git a/x-pack/plugins/screenshotting/server/plugin.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/plugin.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/plugin.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/plugin.test.ts diff --git a/x-pack/plugins/screenshotting/server/plugin.ts b/x-pack/platform/plugins/shared/screenshotting/server/plugin.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/plugin.ts rename to x-pack/platform/plugins/shared/screenshotting/server/plugin.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/__snapshots__/index.test.ts.snap b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/__snapshots__/index.test.ts.snap similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/__snapshots__/index.test.ts.snap rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/__snapshots__/index.test.ts.snap diff --git a/x-pack/plugins/screenshotting/server/screenshots/constants.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/constants.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/constants.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/constants.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/event_logger/index.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/event_logger/index.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/event_logger/index.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/event_logger/index.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/event_logger/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/event_logger/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/event_logger/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/event_logger/index.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_element_position_data.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_element_position_data.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_element_position_data.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_element_position_data.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_element_position_data.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_element_position_data.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_element_position_data.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_element_position_data.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_number_of_items.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_number_of_items.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_number_of_items.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_number_of_items.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_number_of_items.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_number_of_items.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_number_of_items.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_number_of_items.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_pdf.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_pdf.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_pdf.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_pdf.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_render_errors.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_render_errors.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_render_errors.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_render_errors.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_render_errors.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_render_errors.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_render_errors.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_render_errors.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_screenshots.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_screenshots.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_screenshots.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_screenshots.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_screenshots.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_screenshots.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_screenshots.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_screenshots.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_time_range.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_time_range.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_time_range.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_time_range.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/get_time_range.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_time_range.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/get_time_range.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/get_time_range.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/index.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/index.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/index.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/index.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/index.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/index.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/index.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/index.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/inject_css.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/inject_css.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/inject_css.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/inject_css.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/mock.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/mock.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/mock.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/mock.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/observable.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/observable.test.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/observable.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/observable.test.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/observable.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/observable.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/observable.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/observable.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/open_url.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/open_url.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/open_url.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/open_url.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/screenshots.test.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/screenshots.test.ts similarity index 98% rename from x-pack/plugins/screenshotting/server/screenshots/screenshots.test.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/screenshots.test.ts index 4f217ef96c61..95261626e15f 100644 --- a/x-pack/plugins/screenshotting/server/screenshots/screenshots.test.ts +++ b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/screenshots.test.ts @@ -30,7 +30,8 @@ describe('class Screenshots', () => { let mockLogger: Logger; let mockScreenshotModeSetup: ScreenshotModePluginSetup; - const mockBinaryPath = '/kibana/x-pack/plugins/screenshotting/chromium/linux/headless_shell'; + const mockBinaryPath = + '/kibana/x-pack/platform/plugins/shared/screenshotting/chromium/linux/headless_shell'; const mockBasePath = '/kibanaTest1'; beforeEach(() => { diff --git a/x-pack/plugins/screenshotting/server/screenshots/screenshots.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/screenshots.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/screenshots.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/screenshots.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/types.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/types.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/types.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/types.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/wait_for_render.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/wait_for_render.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/wait_for_render.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/wait_for_render.ts diff --git a/x-pack/plugins/screenshotting/server/screenshots/wait_for_visualizations.ts b/x-pack/platform/plugins/shared/screenshotting/server/screenshots/wait_for_visualizations.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/screenshots/wait_for_visualizations.ts rename to x-pack/platform/plugins/shared/screenshotting/server/screenshots/wait_for_visualizations.ts diff --git a/x-pack/plugins/screenshotting/server/utils.ts b/x-pack/platform/plugins/shared/screenshotting/server/utils.ts similarity index 100% rename from x-pack/plugins/screenshotting/server/utils.ts rename to x-pack/platform/plugins/shared/screenshotting/server/utils.ts diff --git a/x-pack/platform/plugins/shared/screenshotting/tsconfig.json b/x-pack/platform/plugins/shared/screenshotting/tsconfig.json new file mode 100644 index 000000000000..200c6d9c2592 --- /dev/null +++ b/x-pack/platform/plugins/shared/screenshotting/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + }, + "include": [ + "common/**/*", + "public/**/*", + "server/**/*", + "../../../../../typings/**/*" + ], + "kbn_references": [ + "@kbn/core", + { "path": "../../../../../src/setup_node_env/tsconfig.json" }, + "@kbn/expressions-plugin", + "@kbn/screenshot-mode-plugin", + "@kbn/cloud-plugin", + "@kbn/utility-types", + "@kbn/logging", + "@kbn/std", + "@kbn/i18n", + "@kbn/utils", + "@kbn/core-logging-server-mocks", + "@kbn/logging-mocks", + "@kbn/core-http-server", + "@kbn/core-plugins-server", + "@kbn/task-manager-plugin", + "@kbn/screenshotting-server", + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/x-pack/plugins/actions/server/lib/gen_ai_token_tracking.ts b/x-pack/plugins/actions/server/lib/gen_ai_token_tracking.ts index d73610892098..ff73095ac242 100644 --- a/x-pack/plugins/actions/server/lib/gen_ai_token_tracking.ts +++ b/x-pack/plugins/actions/server/lib/gen_ai_token_tracking.ts @@ -295,4 +295,7 @@ export const getGenAiTokenTracking = async ({ }; export const shouldTrackGenAiToken = (actionTypeId: string) => - actionTypeId === '.gen-ai' || actionTypeId === '.bedrock' || actionTypeId === '.gemini'; + actionTypeId === '.gen-ai' || + actionTypeId === '.bedrock' || + actionTypeId === '.gemini' || + actionTypeId === '.inference'; diff --git a/x-pack/plugins/canvas/i18n/functions/dict/saved_search.ts b/x-pack/plugins/canvas/i18n/functions/dict/saved_search.ts index 7cdac8909c6e..d00ea3cf79b7 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/saved_search.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/saved_search.ts @@ -12,9 +12,9 @@ import { FunctionFactory } from '../../../types'; export const help: FunctionHelp> = { help: i18n.translate('xpack.canvas.functions.savedSearchHelpText', { - defaultMessage: `Returns an embeddable for a saved search object`, + defaultMessage: `Returns an embeddable for a saved Discover session object`, }), args: { - id: 'The id of the saved search object', + id: 'The id of the saved Discover session object', }, }; diff --git a/x-pack/plugins/cases/server/services/alerts/index.test.ts b/x-pack/plugins/cases/server/services/alerts/index.test.ts index a18681c6478a..450efd67c9e1 100644 --- a/x-pack/plugins/cases/server/services/alerts/index.test.ts +++ b/x-pack/plugins/cases/server/services/alerts/index.test.ts @@ -16,11 +16,19 @@ describe('updateAlertsStatus', () => { const alertsClient = alertsClientMock.create(); let alertService: AlertService; - beforeEach(async () => { + beforeEach(() => { + jest.useFakeTimers(); + jest.setSystemTime(new Date('2022-02-21T17:35:00Z')); + alertService = new AlertService(esClient, logger, alertsClient); jest.clearAllMocks(); }); + afterEach(() => { + jest.runOnlyPendingTimers(); + jest.useRealTimers(); + }); + describe('happy path', () => { it('updates the status of the alert correctly', async () => { const args = [{ id: 'alert-id-1', index: '.siem-signals', status: CaseStatuses.closed }]; @@ -41,7 +49,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed' + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'closed' @@ -80,7 +89,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed' + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'closed' @@ -115,7 +125,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'acknowledged' + ctx._source['kibana.alert.workflow_status'] = 'acknowledged'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'acknowledged' @@ -154,7 +165,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed' + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'closed' @@ -183,7 +195,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'open' + ctx._source['kibana.alert.workflow_status'] = 'open'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'open' @@ -222,7 +235,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed' + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'closed' @@ -251,7 +265,8 @@ describe('updateAlertsStatus', () => { "script": Object { "lang": "painless", "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'open' + ctx._source['kibana.alert.workflow_status'] = 'open'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = 'open' diff --git a/x-pack/plugins/cases/server/services/alerts/index.ts b/x-pack/plugins/cases/server/services/alerts/index.ts index 50a8e286cea4..94694b7f243b 100644 --- a/x-pack/plugins/cases/server/services/alerts/index.ts +++ b/x-pack/plugins/cases/server/services/alerts/index.ts @@ -10,7 +10,10 @@ import { isEmpty } from 'lodash'; import type { ElasticsearchClient, Logger } from '@kbn/core/server'; import type { STATUS_VALUES } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names'; -import { ALERT_WORKFLOW_STATUS } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names'; +import { + ALERT_WORKFLOW_STATUS, + ALERT_WORKFLOW_STATUS_UPDATED_AT, +} from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names'; import type { MgetResponse } from '@elastic/elasticsearch/lib/api/types'; import type { AlertsClient } from '@kbn/rule-registry-plugin/server'; import type { PublicMethodsOf } from '@kbn/utility-types'; @@ -169,7 +172,8 @@ export class AlertService { body: { script: { source: `if (ctx._source['${ALERT_WORKFLOW_STATUS}'] != null) { - ctx._source['${ALERT_WORKFLOW_STATUS}'] = '${status}' + ctx._source['${ALERT_WORKFLOW_STATUS}'] = '${status}'; + ctx._source['${ALERT_WORKFLOW_STATUS_UPDATED_AT}'] = '${new Date().toISOString()}'; } if (ctx._source.signal != null && ctx._source.signal.status != null) { ctx._source.signal.status = '${status}' diff --git a/x-pack/plugins/enterprise_search/common/constants.ts b/x-pack/plugins/enterprise_search/common/constants.ts index 638e292ff0e2..8e69b8056480 100644 --- a/x-pack/plugins/enterprise_search/common/constants.ts +++ b/x-pack/plugins/enterprise_search/common/constants.ts @@ -235,7 +235,7 @@ export const ENTERPRISE_SEARCH_DOCUMENTS_DEFAULT_DOC_COUNT = 25; export const ENTERPRISE_SEARCH_CONNECTOR_CRAWLER_SERVICE_TYPE = 'elastic-crawler'; -export const DEFAULT_PIPELINE_NAME = 'ent-search-generic-ingestion'; +export const DEFAULT_PIPELINE_NAME = 'search-default-ingestion'; export const DEFAULT_PIPELINE_VALUES: IngestPipelineParams = { extract_binary_content: true, name: DEFAULT_PIPELINE_NAME, diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/crawler_domain_detail/authentication_panel/authentication_panel_actions.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/crawler_domain_detail/authentication_panel/authentication_panel_actions.tsx index ba6e9d2c1931..49d15c041f14 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/crawler_domain_detail/authentication_panel/authentication_panel_actions.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/crawler_domain_detail/authentication_panel/authentication_panel_actions.tsx @@ -61,7 +61,7 @@ export const AuthenticationPanelActions: React.FC = () => { ) : currentAuth === null ? ( enableEditing(currentAuth)} diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/domain_management/domains_panel.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/domain_management/domains_panel.tsx index 41af7db78b6b..60f2e5221197 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/domain_management/domains_panel.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/crawler/domain_management/domains_panel.tsx @@ -47,7 +47,7 @@ export const DomainsPanel: React.FC = () => { data-telemetry-id="entSearchContent-crawler-domainManagement-addDomain-addDomain" onClick={openFlyout} size="s" - color="success" + color="primary" iconType="plusInCircle" > {i18n.translate('xpack.enterpriseSearch.crawler.addDomainFlyout.openButtonLabel', { diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/add_ml_inference_button.tsx b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/add_ml_inference_button.tsx index 1f8bc30e2903..c7c296a443eb 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/add_ml_inference_button.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/ml_inference/add_ml_inference_button.tsx @@ -79,7 +79,7 @@ const AddButton: React.FC<{ + - + - +

{i18n.translate( 'xpack.enterpriseSearch.content.index.pipelines.textExpansionCallOut.title', @@ -87,7 +87,7 @@ export const DeployModel = ({ > { hasIndexIngestionPipeline ? ( - + {i18n.translate( 'xpack.enterpriseSearch.content.indices.pipelines.ingestionPipeline.customBadge', { defaultMessage: 'Custom' } diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_json_configurations_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_json_configurations_logic.test.ts index 6fbeffd30b71..367cf8631676 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_json_configurations_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_json_configurations_logic.test.ts @@ -53,7 +53,7 @@ describe('IndexPipelinesConfigurationsLogic', () => { }); it('fetchIndexPipelinesDataSuccess selects index ingest pipeline if found', async () => { const pipelines = { - 'ent-search-generic-ingest': { + 'search-default-ingest': { version: 1, }, [indexName]: { @@ -68,7 +68,7 @@ describe('IndexPipelinesConfigurationsLogic', () => { }); it('fetchIndexPipelinesDataSuccess selects first pipeline as default pipeline', async () => { const pipelines = { - 'ent-search-generic-ingest': { + 'search-default-ingest': { version: 1, }, }; @@ -76,7 +76,7 @@ describe('IndexPipelinesConfigurationsLogic', () => { await nextTick(); expect(IndexPipelinesConfigurationsLogic.values.selectedPipelineId).toEqual( - 'ent-search-generic-ingest' + 'search-default-ingest' ); }); }); @@ -84,7 +84,7 @@ describe('IndexPipelinesConfigurationsLogic', () => { describe('selectors', () => { it('pipelineNames returns names of pipelines', async () => { const pipelines = { - 'ent-search-generic-ingest': { + 'search-default-ingest': { version: 1, }, [indexName]: { @@ -96,13 +96,13 @@ describe('IndexPipelinesConfigurationsLogic', () => { await nextTick(); expect(IndexPipelinesConfigurationsLogic.values.pipelineNames).toEqual([ - 'ent-search-generic-ingest', + 'search-default-ingest', indexName, ]); }); it('selectedPipeline returns full pipeline', async () => { const pipelines = { - 'ent-search-generic-ingest': { + 'search-default-ingest': { version: 1, }, foo: { diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_logic.test.ts index bacde5895073..597b22f15049 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/search_index/pipelines/pipelines_logic.test.ts @@ -21,7 +21,7 @@ import { PipelinesLogic } from './pipelines_logic'; const DEFAULT_PIPELINE_VALUES = { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: true, }; diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/shared/header_actions/syncs_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/shared/header_actions/syncs_logic.test.ts index 5406622ff9f3..88f1f2663a95 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/shared/header_actions/syncs_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/components/shared/header_actions/syncs_logic.test.ts @@ -126,7 +126,7 @@ const mockConnector: Connector = { name: 'test', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: true, }, diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/search_labs_banner/search_labs_banner.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/search_labs_banner/search_labs_banner.tsx index d9f1be314a56..a1b3302cd35a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/search_labs_banner/search_labs_banner.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/search_labs_banner/search_labs_banner.tsx @@ -36,10 +36,11 @@ export const SearchLabsBanner: React.FC = () => { ({ iconType="plusInCircle" disabled={isEditing} onClick={editNewItem} - color="success" + color="primary" data-test-subj="inlineEditableTableActionButton" > {addButtonText || diff --git a/x-pack/plugins/enterprise_search/public/applications/vector_search/components/dev_tools_console_code_block/dev_tools_console_code_block.tsx b/x-pack/plugins/enterprise_search/public/applications/vector_search/components/dev_tools_console_code_block/dev_tools_console_code_block.tsx index d48011d54cdf..46a60456be7c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/vector_search/components/dev_tools_console_code_block/dev_tools_console_code_block.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/vector_search/components/dev_tools_console_code_block/dev_tools_console_code_block.tsx @@ -39,7 +39,7 @@ export const DevToolsConsoleCodeBlock: React.FC = return ( - + { _meta: { pipeline: { default_extract_binary_content: true, - default_name: 'ent-search-generic-ingestion', + default_name: 'search-default-ingestion', default_reduce_whitespace: true, default_run_ml_inference: true, }, @@ -89,7 +89,7 @@ describe('addConnector lib function', () => { name: 'index_name', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: true, }, @@ -134,7 +134,7 @@ describe('addConnector lib function', () => { name: 'index_name', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: true, }, @@ -264,7 +264,7 @@ describe('addConnector lib function', () => { name: '', pipeline: { extract_binary_content: true, - name: 'ent-search-generic-ingestion', + name: 'search-default-ingestion', reduce_whitespace: true, run_ml_inference: true, }, diff --git a/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap b/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap index 140d20f8ebdb..cc32fa26b475 100644 --- a/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap +++ b/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap @@ -434,7 +434,7 @@ Array [ "reporting", ], }, - "name": "Generate CSV reports from Saved Search panels", + "name": "Generate CSV reports from Discover session panels", "savedObject": Object { "all": Array [], "read": Array [], diff --git a/x-pack/plugins/features/server/oss_features.ts b/x-pack/plugins/features/server/oss_features.ts index 12978c35777e..d0596a59ca50 100644 --- a/x-pack/plugins/features/server/oss_features.ts +++ b/x-pack/plugins/features/server/oss_features.ts @@ -636,7 +636,7 @@ const reportingFeatures: { { id: 'download_csv_report', name: i18n.translate('xpack.features.ossFeatures.reporting.dashboardDownloadCSV', { - defaultMessage: 'Generate CSV reports from Saved Search panels', + defaultMessage: 'Generate CSV reports from Discover session panels', }), includeIn: 'all', savedObject: { all: [], read: [] }, diff --git a/x-pack/plugins/fleet/common/experimental_features.ts b/x-pack/plugins/fleet/common/experimental_features.ts index 1c42bf3ab2af..1cf35952904a 100644 --- a/x-pack/plugins/fleet/common/experimental_features.ts +++ b/x-pack/plugins/fleet/common/experimental_features.ts @@ -10,7 +10,6 @@ export type ExperimentalFeatures = typeof allowedExperimentalValues; const _allowedExperimentalValues = { createPackagePolicyMultiPageLayout: true, packageVerification: true, - showDevtoolsRequest: true, diagnosticFileUploadEnabled: true, displayAgentMetrics: true, showIntegrationsSubcategories: true, diff --git a/x-pack/plugins/fleet/dev_docs/integrations_overview.md b/x-pack/plugins/fleet/dev_docs/integrations_overview.md index b6ce0f5ce991..19d0564cf6f2 100644 --- a/x-pack/plugins/fleet/dev_docs/integrations_overview.md +++ b/x-pack/plugins/fleet/dev_docs/integrations_overview.md @@ -143,7 +143,7 @@ Contains screenshots rendered on the integrations detail page for the integratio ## `kibana` directory -Contains top level Kibana assets (dashboards, visualizations, saved searches etc) for the integration. +Contains top level Kibana assets (dashboards, visualizations, Discover sessions etc) for the integration. ## Relationship diagram diff --git a/x-pack/plugins/fleet/public/applications/fleet/app.tsx b/x-pack/plugins/fleet/public/applications/fleet/app.tsx index 8a4edef8dc87..0041ffa09105 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/app.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/app.tsx @@ -247,7 +247,7 @@ const FleetTopNav = memo( const readOnlyBtnClass = React.useMemo(() => { return css` - color: ${euiTheme.colors.text}; + color: ${euiTheme.colors.textParagraph}; `; }, [euiTheme]); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_select_hosts.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_select_hosts.test.tsx index dd3945664bd6..a0329a1c9ce0 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_select_hosts.test.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_select_hosts.test.tsx @@ -42,7 +42,8 @@ jest.mock('../../../../../hooks', () => { }; }); -describe('StepSelectHosts', () => { +// FLAKY: https://github.com/elastic/kibana/issues/203307 +describe.skip('StepSelectHosts', () => { const packageInfo: PackageInfo = { name: 'apache', version: '1.0.0', diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/horizontal_page_steps.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/horizontal_page_steps.tsx index 752b49431dad..a00ef9118b85 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/horizontal_page_steps.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/multi_page_layout/components/horizontal_page_steps.tsx @@ -7,31 +7,7 @@ import React from 'react'; import { EuiStepsHorizontal } from '@elastic/eui'; import type { EuiStepsHorizontalProps } from '@elastic/eui'; -import styled from 'styled-components'; -// polyfill until https://github.com/elastic/eui/discussions/5836 implemented -const NumberlessHorizontalSteps = styled(EuiStepsHorizontal)` - .euiStepNumber { - color: transparent; - width: 16px; - height: 16px; - outline-color: #07c; - } - .euiStepHorizontal::before { - width: calc(50% - 8px); - top: 32px; - } - .euiStepHorizontal::after { - width: calc(50% - 8px); - top: 32px; - } - .euiStepHorizontal { - padding: 25px 16px 16px; - } - .euiStepHorizontal[data-step-status='incomplete'] .euiStepHorizontal__title { - color: #69707d; - } -`; const getStepStatus = (currentStep: number, stepIndex: number, currentStepComplete: boolean) => { if (currentStep === stepIndex) { if (currentStepComplete) return 'complete'; @@ -58,5 +34,5 @@ export const PageSteps: React.FC<{ }; }) as EuiStepsHorizontalProps['steps']; - return ; + return ; }; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/devtools_request.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/devtools_request.tsx index 91ca089f2ffe..81f2304efee9 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/devtools_request.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/devtools_request.tsx @@ -11,7 +11,6 @@ import { i18n } from '@kbn/i18n'; import { omit } from 'lodash'; import { set } from '@kbn/safer-lodash-set'; -import { ExperimentalFeaturesService } from '../../../../../services'; import { generateCreatePackagePolicyDevToolsRequest, generateCreateAgentPolicyDevToolsRequest, @@ -39,12 +38,7 @@ export function useDevToolsRequest({ packageInfo?: PackageInfo; packagePolicyId?: string; }) { - const { showDevtoolsRequest: isShowDevtoolRequestExperimentEnabled } = - ExperimentalFeaturesService.get(); - - const showDevtoolsRequest = - !HIDDEN_API_REFERENCE_PACKAGES.includes(packageInfo?.name ?? '') && - isShowDevtoolRequestExperimentEnabled; + const showDevtoolsRequest = !HIDDEN_API_REFERENCE_PACKAGES.includes(packageInfo?.name ?? ''); const [devtoolRequest, devtoolRequestDescription] = useMemo(() => { if (selectedPolicyTab === SelectedPolicyTab.NEW) { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/components/settings/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/components/settings/index.tsx index 50baac84ff4a..efb7066b0d5e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/components/settings/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/components/settings/index.tsx @@ -40,7 +40,6 @@ import { ConfirmDeployAgentPolicyModal, } from '../../../components'; import { DevtoolsRequestFlyoutButton } from '../../../../../components'; -import { ExperimentalFeaturesService } from '../../../../../services'; import { generateUpdateAgentPolicyDevToolsRequest } from '../../../services'; import { UNKNOWN_SPACE } from '../../../../../../../../common/constants'; @@ -155,7 +154,6 @@ export const SettingsView = memo<{ agentPolicy: AgentPolicy }>( setIsLoading(false); }; - const { showDevtoolsRequest } = ExperimentalFeaturesService.get(); const devtoolRequest = useMemo( () => generateUpdateAgentPolicyDevToolsRequest( @@ -235,28 +233,26 @@ export const SettingsView = memo<{ agentPolicy: AgentPolicy }>( /> - {showDevtoolsRequest ? ( - - 0 || - hasAdvancedSettingsErrors || - hasInvalidSpaceError + + 0 || + hasAdvancedSettingsErrors || + hasInvalidSpaceError + } + btnProps={{ + color: 'text', + }} + description={i18n.translate( + 'xpack.fleet.editAgentPolicy.devtoolsRequestDescription', + { + defaultMessage: 'This Kibana request updates an agent policy.', } - btnProps={{ - color: 'text', - }} - description={i18n.translate( - 'xpack.fleet.editAgentPolicy.devtoolsRequestDescription', - { - defaultMessage: 'This Kibana request updates an agent policy.', - } - )} - request={devtoolRequest} - /> - - ) : null} + )} + request={devtoolRequest} + /> + = ({ /> ); - const { showDevtoolsRequest } = ExperimentalFeaturesService.get(); const agentPolicyContent = useMemo( () => generateCreateAgentPolicyDevToolsRequest(agentPolicy, withSysMonitoring), [agentPolicy, withSysMonitoring] @@ -128,25 +126,23 @@ export const CreateAgentPolicyFlyout: React.FunctionComponent = ({ - {showDevtoolsRequest ? ( - - 0 || - hasAdvancedSettingsErrors || - hasInvalidSpaceError + + 0 || + hasAdvancedSettingsErrors || + hasInvalidSpaceError + } + description={i18n.translate( + 'xpack.fleet.createAgentPolicy.devtoolsRequestDescription', + { + defaultMessage: 'This Kibana request creates a new agent policy.', } - description={i18n.translate( - 'xpack.fleet.createAgentPolicy.devtoolsRequestDescription', - { - defaultMessage: 'This Kibana request creates a new agent policy.', - } - )} - request={agentPolicyContent} - /> - - ) : null} + )} + request={agentPolicyContent} + /> + void; }> = ({ action, onClickViewAgents }) => { + const theme = useEuiTheme(); + const completeTitle = action.type === 'POLICY_CHANGE' && action.nbAgentsActioned === 0 ? ( @@ -104,18 +101,21 @@ export const ActivityItem: React.FunctionComponent<{ IN_PROGRESS: { icon: , title: {inProgressTitle(action)}, - titleColor: inProgressTitleColor, + titleColor: theme.euiTheme.colors.textPrimary, description: {inProgressDescription(action.creationTime)}, }, ROLLOUT_PASSED: { icon: action.nbAgentsFailed > 0 ? ( - + ) : ( - + ), title: completeTitle, - titleColor: action.nbAgentsFailed > 0 ? 'red' : 'green', + titleColor: + action.nbAgentsFailed > 0 + ? theme.euiTheme.colors.textDanger + : theme.euiTheme.colors.textSuccess, description: action.nbAgentsFailed > 0 ? ( failedDescription @@ -124,9 +124,9 @@ export const ActivityItem: React.FunctionComponent<{ ), }, COMPLETE: { - icon: , + icon: , title: completeTitle, - titleColor: 'green', + titleColor: theme.euiTheme.colors.textSuccess, description: action.type === 'POLICY_REASSIGN' && action.newPolicyId ? ( @@ -160,14 +160,14 @@ export const ActivityItem: React.FunctionComponent<{ ), }, FAILED: { - icon: , + icon: , title: completeTitle, - titleColor: 'red', + titleColor: theme.euiTheme.colors.textDanger, description: failedDescription, }, CANCELLED: { - icon: , - titleColor: 'grey', + icon: , + titleColor: theme.euiTheme.colors.textSubdued, title: ( , - titleColor: 'grey', + icon: , + titleColor: theme.euiTheme.colors.textSubdued, title: ( void; }> = ({ action, abortUpgrade, onClickViewAgents }) => { const { docLinks } = useStartServices(); + const theme = useEuiTheme(); + const [isAborting, setIsAborting] = useState(false); const onClickAbortUpgrade = useCallback(async () => { try { @@ -69,7 +67,10 @@ export const UpgradeInProgressActivityItem: React.FunctionComponent<{ {isScheduled ? : } - + {isScheduled && action.startTime ? ( = ({ action }) => { const coreStart = useStartServices(); + const theme = useEuiTheme(); const getLogsButton = (agentId: string, timestamp: string) => { const start = moment(timestamp).subtract(5, 'm').toISOString(); @@ -70,7 +71,11 @@ export const ViewErrors: React.FunctionComponent<{ action: ActionStatus }> = ({ }), render: (error: string) => ( - + {error} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/es_requirements_page.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/es_requirements_page.tsx index 969f9357a21d..3128b05f3af8 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/es_requirements_page.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_requirements_page/es_requirements_page.tsx @@ -20,9 +20,10 @@ import { EuiCode, EuiCodeBlock, EuiLink, + useEuiTheme, } from '@elastic/eui'; -import styled from 'styled-components'; +import { css } from '@emotion/react'; import { WithoutHeaderLayout } from '../../../layouts'; import type { GetFleetStatusResponse } from '../../../types'; @@ -50,20 +51,21 @@ export const RequirementItem: React.FunctionComponent<{ ); }; -const borderColor = '#d3dae6'; - -const StyledPageBody = styled(EuiPageBody)` - border: 1px solid ${borderColor}; - border-radius: 5px; -`; - export const MissingESRequirementsPage: React.FunctionComponent<{ missingRequirements: GetFleetStatusResponse['missing_requirements']; }> = ({ missingRequirements }) => { const { docLinks } = useStartServices(); + const theme = useEuiTheme(); + return ( - + - + ); }; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/donut_chart.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/donut_chart.tsx deleted file mode 100644 index 6f3d865b2284..000000000000 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/donut_chart.tsx +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React, { useEffect, useRef } from 'react'; -import d3 from 'd3'; -import { EuiFlexItem } from '@elastic/eui'; - -interface DonutChartProps { - data: { - [key: string]: number; - }; - height: number; - width: number; -} - -export const DonutChart = ({ height, width, data }: DonutChartProps) => { - const chartElement = useRef(null); - - useEffect(() => { - if (chartElement.current !== null) { - // we must remove any existing paths before painting - d3.selectAll('g').remove(); - const svgElement = d3 - .select(chartElement.current) - .append('g') - .attr('transform', `translate(${width / 2}, ${height / 2})`); - const color = d3.scale - .ordinal() - // @ts-ignore - .domain(data) - .range(['#017D73', '#98A2B3', '#BD271E', '#F5A700']); - const pieGenerator = d3.layout - .pie() - .value(({ value }: any) => value) - // these start/end angles will reverse the direction of the pie, - // which matches our design - .startAngle(2 * Math.PI) - .endAngle(0); - - svgElement - .selectAll('g') - // @ts-ignore - .data(pieGenerator(d3.entries(data))) - .enter() - .append('path') - .attr( - 'd', - // @ts-ignore attr does not expect a param of type Arc but it behaves as desired - d3.svg - .arc() - .innerRadius(width * 0.36) - .outerRadius(Math.min(width, height) / 2) - ) - .attr('fill', (d: any) => color(d.data.key) as any); - } - }, [data, height, width]); - return ( - - - - ); -}; diff --git a/x-pack/plugins/fleet/public/applications/integrations/components/header/header.tsx b/x-pack/plugins/fleet/public/applications/integrations/components/header/header.tsx index 30fc0f0d4965..f9a8ad22cddc 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/components/header/header.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/components/header/header.tsx @@ -34,7 +34,7 @@ export const IntegrationsHeader = ({ const { euiTheme } = useEuiTheme(); const readOnlyBtnClass = React.useMemo(() => { return css` - color: ${euiTheme.colors.text}; + color: ${euiTheme.colors.textParagraph}; `; }, [euiTheme]); const isReadOnly = useIsReadOnly(); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/package_card.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/package_card.tsx index 52a3a90ae641..2bf1f58a6e12 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/package_card.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/package_card.tsx @@ -6,7 +6,6 @@ */ import React from 'react'; -import styled from 'styled-components'; import { EuiBadge, EuiButton, @@ -15,6 +14,7 @@ import { EuiFlexItem, EuiSpacer, EuiToolTip, + useEuiTheme, } from '@elastic/eui'; import { css } from '@emotion/react'; @@ -43,15 +43,6 @@ import { export type PackageCardProps = IntegrationCardItem; -// Min-height is roughly 3 lines of content. -// This keeps the cards from looking overly unbalanced because of content differences. -const Card = styled(EuiCard)<{ isquickstart?: boolean; $maxCardHeight?: number }>` - min-height: 127px; - border-color: ${({ isquickstart }) => (isquickstart ? '#ba3d76' : null)}; - ${({ $maxCardHeight }) => - $maxCardHeight ? `max-height: ${$maxCardHeight}px; overflow: hidden;` : ''}; -`; - export function PackageCard({ description, name, @@ -78,6 +69,8 @@ export function PackageCard({ descriptionLineClamp, maxCardHeight, }: PackageCardProps) { + const theme = useEuiTheme(); + let releaseBadge: React.ReactNode | null = null; if (release && release !== 'ga') { releaseBadge = ( @@ -202,8 +195,10 @@ export function PackageCard({ tourOffset={10} > - } onClick={onClickProp ?? onCardClick} - $maxCardHeight={maxCardHeight} > {showLabels && extraLabelsBadges ? extraLabelsBadges : null} @@ -258,7 +256,7 @@ export function PackageCard({ showInstallationStatus={showInstallationStatus} /> - + ); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/constants.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/constants.tsx index 03f0b0b5cee8..c65e5c8d5644 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/constants.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/constants.tsx @@ -36,7 +36,7 @@ export const AssetTitleMap: Record< defaultMessage: 'Visualizations', }), search: i18n.translate('xpack.fleet.epm.assetTitles.savedSearches', { - defaultMessage: 'Saved searches', + defaultMessage: 'Discover sessions', }), 'index-pattern': i18n.translate('xpack.fleet.epm.assetTitles.indexPatterns', { defaultMessage: 'Data views', diff --git a/x-pack/plugins/fleet/public/components/danger_eui_context_menu_item.tsx b/x-pack/plugins/fleet/public/components/danger_eui_context_menu_item.tsx index 87fb523121cf..b7983ac255fb 100644 --- a/x-pack/plugins/fleet/public/components/danger_eui_context_menu_item.tsx +++ b/x-pack/plugins/fleet/public/components/danger_eui_context_menu_item.tsx @@ -5,9 +5,19 @@ * 2.0. */ -import styled from 'styled-components'; -import { EuiContextMenuItem } from '@elastic/eui'; +import React from 'react'; +import { css } from '@emotion/react'; +import type { EuiContextMenuItemProps } from '@elastic/eui'; +import { EuiContextMenuItem, useEuiTheme } from '@elastic/eui'; -export const DangerEuiContextMenuItem = styled(EuiContextMenuItem)` - color: ${(props) => props.theme.eui.euiColorDangerText}; -`; +export const DangerEuiContextMenuItem = (props: EuiContextMenuItemProps) => { + const theme = useEuiTheme(); + return ( + + ); +}; diff --git a/x-pack/plugins/fleet/public/components/enrollment_instructions/standalone/index.tsx b/x-pack/plugins/fleet/public/components/enrollment_instructions/standalone/index.tsx index dd8eafec86ec..8901c3b5f088 100644 --- a/x-pack/plugins/fleet/public/components/enrollment_instructions/standalone/index.tsx +++ b/x-pack/plugins/fleet/public/components/enrollment_instructions/standalone/index.tsx @@ -22,24 +22,24 @@ export const StandaloneInstructions = ({ const { windows: windowsDownloadSourceProxyArgs, curl: curlDownloadSourceProxyArgs } = getDownloadSourceProxyArgs(downloadSourceProxy); - const linuxDebCommand = `curl -L -O ${downloadBaseUrl}/downloads/beats/elastic-agent/elastic-agent-${agentVersion}-amd64.deb ${curlDownloadSourceProxyArgs} + const linuxDebCommand = `curl -L -O ${downloadBaseUrl}/beats/elastic-agent/elastic-agent-${agentVersion}-amd64.deb ${curlDownloadSourceProxyArgs} sudo dpkg -i elastic-agent-${agentVersion}-amd64.deb \nsudo systemctl enable elastic-agent \nsudo systemctl start elastic-agent`; - const linuxRpmCommand = `curl -L -O ${downloadBaseUrl}/downloads/beats/elastic-agent/elastic-agent-${agentVersion}-x86_64.rpm ${curlDownloadSourceProxyArgs} + const linuxRpmCommand = `curl -L -O ${downloadBaseUrl}/beats/elastic-agent/elastic-agent-${agentVersion}-x86_64.rpm ${curlDownloadSourceProxyArgs} sudo rpm -vi elastic-agent-${agentVersion}-x86_64.rpm \nsudo systemctl enable elastic-agent \nsudo systemctl start elastic-agent`; - const linuxCommand = `curl -L -O ${downloadBaseUrl}/downloads/beats/elastic-agent/elastic-agent-${agentVersion}-linux-x86_64.tar.gz ${curlDownloadSourceProxyArgs} + const linuxCommand = `curl -L -O ${downloadBaseUrl}/beats/elastic-agent/elastic-agent-${agentVersion}-linux-x86_64.tar.gz ${curlDownloadSourceProxyArgs} tar xzvf elastic-agent-${agentVersion}-linux-x86_64.tar.gz cd elastic-agent-${agentVersion}-linux-x86_64 sudo ./elastic-agent install`; - const macCommand = `curl -L -O ${downloadBaseUrl}/downloads/beats/elastic-agent/elastic-agent-${agentVersion}-darwin-aarch64.tar.gz ${curlDownloadSourceProxyArgs} + const macCommand = `curl -L -O ${downloadBaseUrl}/beats/elastic-agent/elastic-agent-${agentVersion}-darwin-aarch64.tar.gz ${curlDownloadSourceProxyArgs} tar xzvf elastic-agent-${agentVersion}-darwin-aarch64.tar.gz cd elastic-agent-${agentVersion}-darwin-aarch64 sudo ./elastic-agent install`; const windowsCommand = `$ProgressPreference = 'SilentlyContinue' -Invoke-WebRequest -Uri ${downloadBaseUrl}/downloads/beats/elastic-agent/elastic-agent-${agentVersion}-windows-x86_64.zip -OutFile elastic-agent-${agentVersion}-windows-x86_64.zip ${windowsDownloadSourceProxyArgs} +Invoke-WebRequest -Uri ${downloadBaseUrl}/beats/elastic-agent/elastic-agent-${agentVersion}-windows-x86_64.zip -OutFile elastic-agent-${agentVersion}-windows-x86_64.zip ${windowsDownloadSourceProxyArgs} Expand-Archive .\elastic-agent-${agentVersion}-windows-x86_64.zip -DestinationPath . cd elastic-agent-${agentVersion}-windows-x86_64 .\\elastic-agent.exe install`; diff --git a/x-pack/plugins/fleet/server/constants/fleet_es_assets.ts b/x-pack/plugins/fleet/server/constants/fleet_es_assets.ts index 621adc5b3b81..384a77afd112 100644 --- a/x-pack/plugins/fleet/server/constants/fleet_es_assets.ts +++ b/x-pack/plugins/fleet/server/constants/fleet_es_assets.ts @@ -11,7 +11,7 @@ import { getESAssetMetadata } from '../services/epm/elasticsearch/meta'; const meta = getESAssetMetadata(); -export const FLEET_INSTALL_FORMAT_VERSION = '1.3.0'; +export const FLEET_INSTALL_FORMAT_VERSION = '1.4.0'; export const FLEET_AGENT_POLICIES_SCHEMA_VERSION = '1.1.1'; diff --git a/x-pack/plugins/fleet/server/services/epm/packages/install_state_machine/steps/step_save_system_object.test.ts b/x-pack/plugins/fleet/server/services/epm/packages/install_state_machine/steps/step_save_system_object.test.ts index 8d80c236aefb..c4ae211c58fc 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/install_state_machine/steps/step_save_system_object.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/install_state_machine/steps/step_save_system_object.test.ts @@ -13,14 +13,12 @@ import { } from '@kbn/core/server/mocks'; import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants'; +import { FLEET_INSTALL_FORMAT_VERSION } from '../../../../../constants'; import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../../common/constants'; - import { appContextService } from '../../../../app_context'; import { createAppContextStartContractMock } from '../../../../../mocks'; - import { auditLoggingService } from '../../../../audit_logging'; import { packagePolicyService } from '../../../../package_policy'; - import { createArchiveIteratorFromMap } from '../../../archive/archive_iterator'; import { stepSaveSystemObject } from './step_save_system_object'; @@ -94,7 +92,7 @@ describe('updateLatestExecutedState', () => { 'epm-packages', 'test-integration', { - install_format_schema_version: '1.3.0', + install_format_schema_version: FLEET_INSTALL_FORMAT_VERSION, install_status: 'installed', install_version: '1.0.0', latest_install_failed_attempts: [], @@ -161,7 +159,7 @@ describe('updateLatestExecutedState', () => { 'epm-packages', 'test-integration', { - install_format_schema_version: '1.3.0', + install_format_schema_version: FLEET_INSTALL_FORMAT_VERSION, install_status: 'installed', install_version: '1.0.0', latest_install_failed_attempts: [], diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx index 24f641ae2833..535e0219bf82 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx @@ -95,6 +95,7 @@ const appDependencies = { monitor: true, manageEnrich: true, monitorEnrich: true, + manageIndexTemplates: true, }, } as any; diff --git a/x-pack/plugins/index_management/public/application/app_context.tsx b/x-pack/plugins/index_management/public/application/app_context.tsx index 3573ae33812d..1019d580dec5 100644 --- a/x-pack/plugins/index_management/public/application/app_context.tsx +++ b/x-pack/plugins/index_management/public/application/app_context.tsx @@ -84,6 +84,7 @@ export interface AppDependencies { monitor: boolean; manageEnrich: boolean; monitorEnrich: boolean; + manageIndexTemplates: boolean; }; } diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/auth_provider.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/auth_provider.tsx deleted file mode 100644 index 88da23007a4f..000000000000 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/auth_provider.tsx +++ /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 React from 'react'; - -import { AuthorizationProvider } from '../shared_imports'; -import { useComponentTemplatesContext } from '../component_templates_context'; - -export const ComponentTemplatesAuthProvider: React.FunctionComponent<{ - children?: React.ReactNode; -}> = ({ children }) => { - const { httpClient, apiBasePath } = useComponentTemplatesContext(); - - return ( - - {children} - - ); -}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list_container.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list_container.tsx index 30cec1554561..e3583b41c110 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list_container.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list_container.tsx @@ -11,8 +11,6 @@ import { RouteComponentProps } from 'react-router-dom'; import qs from 'query-string'; import { useExecutionContext } from '../shared_imports'; import { useComponentTemplatesContext } from '../component_templates_context'; -import { ComponentTemplatesAuthProvider } from './auth_provider'; -import { ComponentTemplatesWithPrivileges } from './with_privileges'; import { ComponentTemplateList } from './component_template_list'; interface MatchParams { @@ -39,14 +37,10 @@ export const ComponentTemplateListContainer: React.FunctionComponent< const filter = urlParams.filter ?? ''; return ( - - - - - + ); }; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/with_privileges.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/with_privileges.tsx deleted file mode 100644 index 5ae9b2f14ec8..000000000000 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/with_privileges.tsx +++ /dev/null @@ -1,83 +0,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 { FormattedMessage } from '@kbn/i18n-react'; -import React, { FunctionComponent } from 'react'; - -import { - PageLoading, - PageError, - useAuthorizationContext, - WithPrivileges, - NotAuthorizedSection, -} from '../shared_imports'; -import { APP_CLUSTER_REQUIRED_PRIVILEGES } from '../constants'; - -export const ComponentTemplatesWithPrivileges: FunctionComponent<{ - children?: React.ReactNode; -}> = ({ children }) => { - const { apiError } = useAuthorizationContext(); - - if (apiError) { - return ( - - } - error={apiError} - /> - ); - } - - return ( - `cluster.${privilege}`)} - > - {({ isLoading, hasPrivileges, privilegesMissing }) => { - if (isLoading) { - return ( - - - - ); - } - - if (!hasPrivileges) { - return ( - - } - message={ - - } - /> - ); - } - - return <>{children}; - }} - - ); -}; diff --git a/x-pack/plugins/index_management/public/application/mount_management_section.ts b/x-pack/plugins/index_management/public/application/mount_management_section.ts index 83cf620a0e8e..003f5279ae52 100644 --- a/x-pack/plugins/index_management/public/application/mount_management_section.ts +++ b/x-pack/plugins/index_management/public/application/mount_management_section.ts @@ -73,7 +73,8 @@ export function getIndexManagementDependencies({ }): AppDependencies { const { docLinks, application, uiSettings, settings } = core; const { url } = startDependencies.share; - const { monitor, manageEnrich, monitorEnrich } = application.capabilities.index_management; + const { monitor, manageEnrich, monitorEnrich, manageIndexTemplates } = + application.capabilities.index_management; return { core: { @@ -109,6 +110,7 @@ export function getIndexManagementDependencies({ monitor: !!monitor, manageEnrich: !!manageEnrich, monitorEnrich: !!monitorEnrich, + manageIndexTemplates: !!manageIndexTemplates, }, }; } diff --git a/x-pack/plugins/index_management/public/application/sections/home/home.tsx b/x-pack/plugins/index_management/public/application/sections/home/home.tsx index 2d0fc7d4ec10..53ef500f597e 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/home.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/home.tsx @@ -66,7 +66,10 @@ export const IndexManagementHome: React.FunctionComponent ), }, - { + ]; + + if (privs.manageIndexTemplates) { + tabs.push({ id: Section.ComponentTemplates, name: ( ), - }, - ]; + }); + } if (privs.monitorEnrich) { tabs.push({ @@ -139,14 +142,16 @@ export const IndexManagementHome: React.FunctionComponent - + {privs.manageIndexTemplates && ( + + )} {privs.monitorEnrich && ( )} diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/details_page/semantic_text_banner.tsx b/x-pack/plugins/index_management/public/application/sections/home/index_list/details_page/semantic_text_banner.tsx index b07886c4526f..2ebcde354bab 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/details_page/semantic_text_banner.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/details_page/semantic_text_banner.tsx @@ -57,10 +57,10 @@ export function SemanticTextBanner({ return isSemanticTextBannerDisplayable && isSemanticTextEnabled ? ( <> - + - + {isPlatinumLicense ? platinumLicenseMessage : defaultLicenseMessage} diff --git a/x-pack/plugins/index_management/public/plugin.ts b/x-pack/plugins/index_management/public/plugin.ts index 06adcc75d80b..35996a43e2cd 100644 --- a/x-pack/plugins/index_management/public/plugin.ts +++ b/x-pack/plugins/index_management/public/plugin.ts @@ -105,8 +105,12 @@ export class IndexMgmtUIPlugin const { fleet, usageCollection, management, cloud } = plugins; this.capabilities$.subscribe((capabilities) => { - const { monitor, manageEnrich, monitorEnrich } = capabilities.index_management; - if (this.config.isIndexManagementUiEnabled && (monitor || manageEnrich || monitorEnrich)) { + const { monitor, manageEnrich, monitorEnrich, manageIndexTemplates } = + capabilities.index_management; + if ( + this.config.isIndexManagementUiEnabled && + (monitor || manageEnrich || monitorEnrich || manageIndexTemplates) + ) { management.sections.section.data.registerApp({ id: PLUGIN.id, title: i18n.translate('xpack.idxMgmt.appTitle', { defaultMessage: 'Index Management' }), diff --git a/x-pack/plugins/index_management/server/plugin.ts b/x-pack/plugins/index_management/server/plugin.ts index ab6b058cddc7..d6689f02255b 100644 --- a/x-pack/plugins/index_management/server/plugin.ts +++ b/x-pack/plugins/index_management/server/plugin.ts @@ -46,6 +46,10 @@ export class IndexMgmtServerPlugin implements Plugin { - const routeContextMock = { - core: { - elasticsearch: { - client: { - asCurrentUser: { - security: { - hasPrivileges, - }, - }, - }, - }, - }, - } as unknown as RequestHandlerContext; - - return routeContextMock; -}; - -describe('GET privileges', () => { - let routeHandler: RequestHandler; - - beforeEach(() => { - const router = httpService.createRouter(); - - registerPrivilegesRoute({ - router, - config: { - isSecurityEnabled: () => true, - isLegacyTemplatesEnabled: true, - isIndexStatsEnabled: true, - isSizeAndDocCountEnabled: false, - isDataStreamStatsEnabled: true, - enableMappingsSourceFieldSection: true, - enableTogglingDataRetention: true, - enableProjectLevelRetentionChecks: false, - }, - indexDataEnricher: mockedIndexDataEnricher, - lib: { - handleEsError: jest.fn(), - }, - }); - - routeHandler = router.get.mock.calls[0][1]; - }); - - it('should return the correct response when a user has privileges', async () => { - const privilegesResponseMock = { - username: 'elastic', - has_all_requested: true, - cluster: { manage_index_templates: true }, - index: {}, - application: {}, - }; - - const routeContextMock = mockRouteContext({ - hasPrivileges: jest.fn().mockResolvedValueOnce(privilegesResponseMock), - }); - - const request = httpServerMock.createKibanaRequest(); - const response = await routeHandler(routeContextMock, request, kibanaResponseFactory); - - expect(response.payload).toEqual({ - hasAllPrivileges: true, - missingPrivileges: { - cluster: [], - }, - }); - }); - - it('should return the correct response when a user does not have privileges', async () => { - const privilegesResponseMock = { - username: 'elastic', - has_all_requested: false, - cluster: { manage_index_templates: false }, - index: {}, - application: {}, - }; - - const routeContextMock = mockRouteContext({ - hasPrivileges: jest.fn().mockResolvedValueOnce(privilegesResponseMock), - }); - - const request = httpServerMock.createKibanaRequest(); - const response = await routeHandler(routeContextMock, request, kibanaResponseFactory); - - expect(response.payload).toEqual({ - hasAllPrivileges: false, - missingPrivileges: { - cluster: ['manage_index_templates'], - }, - }); - }); - - describe('With security disabled', () => { - beforeEach(() => { - const router = httpService.createRouter(); - - registerPrivilegesRoute({ - router, - config: { - isSecurityEnabled: () => false, - isLegacyTemplatesEnabled: true, - isIndexStatsEnabled: true, - isSizeAndDocCountEnabled: false, - isDataStreamStatsEnabled: true, - enableMappingsSourceFieldSection: true, - enableTogglingDataRetention: true, - enableProjectLevelRetentionChecks: false, - }, - indexDataEnricher: mockedIndexDataEnricher, - lib: { - handleEsError: jest.fn(), - }, - }); - - routeHandler = router.get.mock.calls[0][1]; - }); - - it('should return the default privileges response', async () => { - const routeContextMock = mockRouteContext({ - hasPrivileges: jest.fn(), - }); - - const request = httpServerMock.createKibanaRequest(); - const response = await routeHandler(routeContextMock, request, kibanaResponseFactory); - - expect(response.payload).toEqual({ - hasAllPrivileges: true, - missingPrivileges: { - cluster: [], - }, - }); - }); - }); -}); diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts deleted file mode 100644 index a053eb44657c..000000000000 --- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.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 type { Privileges } from '@kbn/es-ui-shared-plugin/public'; -import { RouteDependencies } from '../../../types'; -import { addBasePath } from '..'; - -const extractMissingPrivileges = (privilegesObject: { [key: string]: boolean } = {}): string[] => - Object.keys(privilegesObject).reduce((privileges: string[], privilegeName: string): string[] => { - if (!privilegesObject[privilegeName]) { - privileges.push(privilegeName); - } - return privileges; - }, []); - -export const registerPrivilegesRoute = ({ - router, - config, - lib: { handleEsError }, -}: RouteDependencies) => { - router.get( - { - path: addBasePath('/component_templates/privileges'), - validate: false, - }, - async (context, request, response) => { - const privilegesResult: Privileges = { - hasAllPrivileges: true, - missingPrivileges: { - cluster: [], - }, - }; - - // Skip the privileges check if security is not enabled - if (!config.isSecurityEnabled()) { - return response.ok({ body: privilegesResult }); - } - - const { client } = (await context.core).elasticsearch; - - try { - const { has_all_requested: hasAllPrivileges, cluster } = - await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage_index_templates'], - }, - }); - - if (!hasAllPrivileges) { - privilegesResult.missingPrivileges.cluster = extractMissingPrivileges(cluster); - } - - privilegesResult.hasAllPrivileges = hasAllPrivileges; - return response.ok({ body: privilegesResult }); - } catch (error) { - return handleEsError({ error, response }); - } - } - ); -}; diff --git a/x-pack/plugins/lens/public/app_plugin/share_action.ts b/x-pack/plugins/lens/public/app_plugin/share_action.ts index dbb5d9d61eda..e9e0c73cd5d6 100644 --- a/x-pack/plugins/lens/public/app_plugin/share_action.ts +++ b/x-pack/plugins/lens/public/app_plugin/share_action.ts @@ -31,7 +31,7 @@ interface ShareableConfiguration export const DEFAULT_LENS_LAYOUT_DIMENSIONS = { width: 1793, // this is a magic number from the reporting tool implementation - // see: x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts#L146 + // see: x-pack/platform/plugins/shared/screenshotting/server/browsers/chromium/driver_factory/index.ts#L146 height: 1086, }; diff --git a/x-pack/plugins/lens/public/react_embeddable/data_loader.ts b/x-pack/plugins/lens/public/react_embeddable/data_loader.ts index ac69b79b4223..a1d2e713d3f8 100644 --- a/x-pack/plugins/lens/public/react_embeddable/data_loader.ts +++ b/x-pack/plugins/lens/public/react_embeddable/data_loader.ts @@ -22,13 +22,7 @@ import { import fastIsEqual from 'fast-deep-equal'; import { pick } from 'lodash'; import { getEditPath } from '../../common/constants'; -import type { - GetStateType, - LensApi, - LensInternalApi, - LensPublicCallbacks, - VisualizationContextHelper, -} from './types'; +import type { GetStateType, LensApi, LensInternalApi, LensPublicCallbacks } from './types'; import { getExpressionRendererParams } from './expressions/expression_params'; import type { LensEmbeddableStartServices } from './types'; import { prepareCallbacks } from './expressions/callbacks'; @@ -84,7 +78,6 @@ export function loadEmbeddableData( parentApi: unknown, internalApi: LensInternalApi, services: LensEmbeddableStartServices, - { getVisualizationContext, updateVisualizationContext }: VisualizationContextHelper, metaInfo?: SharingSavedObjectProps ) { const { onLoad, onBeforeBadgesRender, ...callbacks } = apiHasLensComponentCallbacks(parentApi) @@ -103,7 +96,6 @@ export function loadEmbeddableData( } = buildUserMessagesHelpers( api, internalApi, - getVisualizationContext, services, onBeforeBadgesRender, services.spaces, @@ -174,7 +166,7 @@ export function loadEmbeddableData( }; const onDataCallback = (adapters: Partial | undefined) => { - updateVisualizationContext({ + internalApi.updateVisualizationContext({ activeData: adapters?.tables?.tables, }); // data has loaded @@ -243,8 +235,8 @@ export function loadEmbeddableData( // update the visualization context before anything else // as it will be used to compute blocking errors also in case of issues - updateVisualizationContext({ - doc: currentState.attributes, + internalApi.updateVisualizationContext({ + activeAttributes: currentState.attributes, mergedSearchContext: params?.searchContext || {}, ...rest, }); diff --git a/x-pack/plugins/lens/public/react_embeddable/helper.ts b/x-pack/plugins/lens/public/react_embeddable/helper.ts index 3ee63d907068..bc0b7c957b9d 100644 --- a/x-pack/plugins/lens/public/react_embeddable/helper.ts +++ b/x-pack/plugins/lens/public/react_embeddable/helper.ts @@ -40,7 +40,7 @@ export function createEmptyLensState( query: query || { query: '', language: 'kuery' }, filters: filters || [], internalReferences: [], - datasourceStates: { ...(isTextBased ? { text_based: {} } : { form_based: {} }) }, + datasourceStates: { ...(isTextBased ? { textBased: {} } : { formBased: {} }) }, visualization: {}, }, }, diff --git a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.test.ts b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.test.ts index 016bc0e87f11..d7a073f10e02 100644 --- a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.test.ts +++ b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.test.ts @@ -13,8 +13,8 @@ import { getLensApiMock, makeEmbeddableServices, getLensRuntimeStateMock, - getVisualizationContextHelperMock, createUnifiedSearchApi, + getLensInternalApiMock, } from '../mocks'; import { createEmptyLensState } from '../helper'; const DATAVIEW_ID = 'myDataView'; @@ -40,11 +40,17 @@ function setupActionsApi( ) { const services = makeEmbeddableServices(undefined, undefined, { visOverrides: { id: 'lnsXY' }, - dataOverrides: { id: 'form_based' }, + dataOverrides: { id: 'formBased' }, }); const uuid = faker.string.uuid(); const runtimeState = getLensRuntimeStateMock(stateOverrides); const apiMock = getLensApiMock(); + // create the internal API and customize internal state + const internalApi = getLensInternalApiMock(); + internalApi.updateVisualizationContext({ + ...contextOverrides, + activeAttributes: runtimeState.attributes, + }); const { api } = initializeActionApi( uuid, @@ -53,7 +59,7 @@ function setupActionsApi( createUnifiedSearchApi(), pick(apiMock, ['timeRange$']), pick(apiMock, ['panelTitle']), - getVisualizationContextHelperMock(stateOverrides?.attributes, contextOverrides), + internalApi, { ...services, data: { @@ -85,6 +91,7 @@ describe('Dashboard actions', () => { describe('Explore in Discover', () => { // make it pass the basic check on viewUnderlyingData const visualizationContextMockOverrides = { + activeAttributes: undefined, mergedSearchContext: {}, indexPatterns: { [DATAVIEW_ID]: { diff --git a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.ts b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.ts index 65fd13c8fca5..ac6739d9ded1 100644 --- a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.ts +++ b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_actions.ts @@ -34,10 +34,10 @@ import { buildObservableVariable, isTextBasedLanguage } from '../helper'; import type { GetStateType, LensEmbeddableStartServices, + LensInternalApi, LensRuntimeState, ViewInDiscoverCallbacks, ViewUnderlyingDataArgs, - VisualizationContextHelper, } from '../types'; import { getActiveDatasourceIdFromDoc, getActiveVisualizationIdFromDoc } from '../../utils'; @@ -120,7 +120,7 @@ function getViewUnderlyingDataArgs({ function loadViewUnderlyingDataArgs( state: LensRuntimeState, - { getVisualizationContext }: VisualizationContextHelper, + { getVisualizationContext }: LensInternalApi, searchContextApi: { timeRange$: PublishingSubject }, parentApi: unknown, { @@ -132,16 +132,21 @@ function loadViewUnderlyingDataArgs( visualizationMap, }: LensEmbeddableStartServices ) { - const { doc, activeData, activeDatasourceState, activeVisualizationState, indexPatterns } = - getVisualizationContext(); - const activeVisualizationId = getActiveVisualizationIdFromDoc(doc); - const activeDatasourceId = getActiveDatasourceIdFromDoc(doc); + const { + activeAttributes, + activeData, + activeDatasourceState, + activeVisualizationState, + indexPatterns, + } = getVisualizationContext(); + const activeVisualizationId = getActiveVisualizationIdFromDoc(activeAttributes); + const activeDatasourceId = getActiveDatasourceIdFromDoc(activeAttributes); const activeVisualization = activeVisualizationId ? visualizationMap[activeVisualizationId] : undefined; const activeDatasource = activeDatasourceId ? datasourceMap[activeDatasourceId] : undefined; if ( - !doc || + !activeAttributes || !activeData || !activeDatasource || !activeDatasourceState || @@ -199,7 +204,7 @@ function loadViewUnderlyingDataArgs( function createViewUnderlyingDataApis( getState: GetStateType, - visualizationContextHelper: VisualizationContextHelper, + internalApi: LensInternalApi, searchContextApi: { timeRange$: PublishingSubject }, parentApi: unknown, services: LensEmbeddableStartServices @@ -213,7 +218,7 @@ function createViewUnderlyingDataApis( loadViewUnderlyingData: () => { viewUnderlyingDataArgs = loadViewUnderlyingDataArgs( getState(), - visualizationContextHelper, + internalApi, searchContextApi, parentApi, services @@ -237,7 +242,7 @@ export function initializeActionApi( parentApi: unknown, searchContextApi: { timeRange$: PublishingSubject }, titleApi: { panelTitle: PublishingSubject }, - visualizationContextHelper: VisualizationContextHelper, + internalApi: LensInternalApi, services: LensEmbeddableStartServices ): { api: ViewInDiscoverCallbacks & HasDynamicActions; @@ -257,7 +262,7 @@ export function initializeActionApi( ...(isTextBasedLanguage(initialState) ? {} : dynamicActionsApi?.dynamicActionsApi ?? {}), ...createViewUnderlyingDataApis( getLatestState, - visualizationContextHelper, + internalApi, searchContextApi, parentApi, services diff --git a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_internal_api.ts b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_internal_api.ts index e366c24a6c0e..2c89ed463e1c 100644 --- a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_internal_api.ts +++ b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_internal_api.ts @@ -15,6 +15,7 @@ import type { LensInternalApi, LensOverrides, LensRuntimeState, + VisualizationContext, } from '../types'; import { apiHasAbortController, apiHasLensComponentProps } from '../type_guards'; import type { UserMessage } from '../../types'; @@ -52,6 +53,18 @@ export function initializeInternalApi( // the isNewPanel won't be serialized so it will be always false after the edit panel closes applying the changes const isNewlyCreated$ = new BehaviorSubject(initialState.isNewPanel || false); + const visualizationContext$ = new BehaviorSubject({ + // doc can point to a different set of attributes for the visualization + // i.e. when inline editing or applying a suggestion + activeAttributes: initialState.attributes, + mergedSearchContext: {}, + indexPatterns: {}, + indexPatternRefs: [], + activeVisualizationState: undefined, + activeDatasourceState: undefined, + activeData: undefined, + }); + // No need to expose anything at public API right now, that would happen later on // where each initializer will pick what it needs and publish it return { @@ -65,6 +78,8 @@ export function initializeInternalApi( renderCount$, isNewlyCreated$, dataViews: dataViews$, + messages$, + validationMessages$, dispatchError: () => { hasRenderCompleted$.next(true); renderCount$.next(renderCount$.getValue() + 1); @@ -82,9 +97,7 @@ export function initializeInternalApi( updateAbortController: (abortController: AbortController | undefined) => expressionAbortController$.next(abortController), updateDataViews: (dataViews: DataView[] | undefined) => dataViews$.next(dataViews), - messages$, updateMessages: (newMessages: UserMessage[]) => messages$.next(newMessages), - validationMessages$, updateValidationMessages: (newMessages: UserMessage[]) => validationMessages$.next(newMessages), resetAllMessages: () => { messages$.next([]); @@ -116,5 +129,12 @@ export function initializeInternalApi( return displayOptions; }, + getVisualizationContext: () => visualizationContext$.getValue(), + updateVisualizationContext: (newVisualizationContext: Partial) => { + visualizationContext$.next({ + ...visualizationContext$.getValue(), + ...newVisualizationContext, + }); + }, }; } diff --git a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_visualization_context.ts b/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_visualization_context.ts deleted file mode 100644 index 93d544013e71..000000000000 --- a/x-pack/plugins/lens/public/react_embeddable/initializers/initialize_visualization_context.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 type { LensInternalApi, VisualizationContext, VisualizationContextHelper } from '../types'; - -export function initializeVisualizationContext( - internalApi: LensInternalApi -): VisualizationContextHelper { - // TODO: this will likely be merged together with the state$ observable - let visualizationContext: VisualizationContext = { - doc: internalApi.attributes$.getValue(), - mergedSearchContext: {}, - indexPatterns: {}, - indexPatternRefs: [], - activeVisualizationState: undefined, - activeDatasourceState: undefined, - activeData: undefined, - }; - return { - getVisualizationContext: () => visualizationContext, - updateVisualizationContext: (newVisualizationContext: Partial) => { - visualizationContext = { - ...visualizationContext, - ...newVisualizationContext, - }; - }, - }; -} diff --git a/x-pack/plugins/lens/public/react_embeddable/lens_embeddable.tsx b/x-pack/plugins/lens/public/react_embeddable/lens_embeddable.tsx index 074ae451115b..2fc1928dc40c 100644 --- a/x-pack/plugins/lens/public/react_embeddable/lens_embeddable.tsx +++ b/x-pack/plugins/lens/public/react_embeddable/lens_embeddable.tsx @@ -22,7 +22,6 @@ import { initializeInspector } from './initializers/initialize_inspector'; import { initializeDashboardServices } from './initializers/initialize_dashboard_services'; import { initializeInternalApi } from './initializers/initialize_internal_api'; import { initializeSearchContext } from './initializers/initialize_search_context'; -import { initializeVisualizationContext } from './initializers/initialize_visualization_context'; import { initializeActionApi } from './initializers/initialize_actions'; import { initializeIntegrations } from './initializers/initialize_integrations'; import { initializeStateManagement } from './initializers/initialize_state_management'; @@ -61,8 +60,6 @@ export const createLensEmbeddableFactory = ( */ const internalApi = initializeInternalApi(initialState, parentApi, services); - const visualizationContextHelper = initializeVisualizationContext(internalApi); - /** * Initialize various configurations required to build all the required * parts for the Lens embeddable. @@ -108,7 +105,7 @@ export const createLensEmbeddableFactory = ( parentApi, searchContextConfig.api, dashboardConfig.api, - visualizationContextHelper, + internalApi, services ); @@ -165,8 +162,7 @@ export const createLensEmbeddableFactory = ( api, parentApi, internalApi, - services, - visualizationContextHelper + services ); const onUnmount = () => { diff --git a/x-pack/plugins/lens/public/react_embeddable/mocks/index.tsx b/x-pack/plugins/lens/public/react_embeddable/mocks/index.tsx index 30a0920f9557..96ba1b547a5d 100644 --- a/x-pack/plugins/lens/public/react_embeddable/mocks/index.tsx +++ b/x-pack/plugins/lens/public/react_embeddable/mocks/index.tsx @@ -32,19 +32,9 @@ import { LensSerializedState, VisualizationContext, } from '../types'; -import { - createMockDatasource, - createMockVisualization, - defaultDoc, - makeDefaultServices, -} from '../../mocks'; -import { - Datasource, - DatasourceMap, - UserMessage, - Visualization, - VisualizationMap, -} from '../../types'; +import { createMockDatasource, createMockVisualization, makeDefaultServices } from '../../mocks'; +import { Datasource, DatasourceMap, Visualization, VisualizationMap } from '../../types'; +import { initializeInternalApi } from '../initializers/initialize_internal_api'; const LensApiMock: LensApi = { // Static props @@ -263,7 +253,7 @@ export function createExpressionRendererMock(): jest.Mock< )); } -function getValidExpressionParams( +export function getValidExpressionParams( overrides: Partial = {} ): ExpressionWrapperProps { return { @@ -284,34 +274,11 @@ function getValidExpressionParams( }; } -const LensInternalApiMock: LensInternalApi = { - dataViews: new BehaviorSubject(undefined), - attributes$: new BehaviorSubject(defaultDoc), - overrides$: new BehaviorSubject(undefined), - disableTriggers$: new BehaviorSubject(undefined), - dataLoading$: new BehaviorSubject(undefined), - hasRenderCompleted$: new BehaviorSubject(true), - expressionParams$: new BehaviorSubject(getValidExpressionParams()), - expressionAbortController$: new BehaviorSubject(undefined), - renderCount$: new BehaviorSubject(0), - messages$: new BehaviorSubject([]), - validationMessages$: new BehaviorSubject([]), - isNewlyCreated$: new BehaviorSubject(true), - updateAttributes: jest.fn(), - updateOverrides: jest.fn(), - dispatchRenderStart: jest.fn(), - dispatchRenderComplete: jest.fn(), - updateDataLoading: jest.fn(), - updateExpressionParams: jest.fn(), - updateAbortController: jest.fn(), - updateDataViews: jest.fn(), - updateMessages: jest.fn(), - resetAllMessages: jest.fn(), - dispatchError: jest.fn(), - updateValidationMessages: jest.fn(), - setAsCreated: jest.fn(), - getDisplayOptions: jest.fn(() => ({})), -}; +const LensInternalApiMock = initializeInternalApi( + getLensRuntimeStateMock(), + {}, + makeEmbeddableServices() +); export function getLensInternalApiMock(overrides: Partial = {}): LensInternalApi { return { @@ -326,6 +293,7 @@ export function getVisualizationContextHelperMock( ) { return { getVisualizationContext: jest.fn(() => ({ + activeAttributes: getLensAttributesMock(attributesOverrides), mergedSearchContext: {}, indexPatterns: {}, indexPatternRefs: [], @@ -333,7 +301,6 @@ export function getVisualizationContextHelperMock( activeDatasourceState: undefined, activeData: undefined, ...contextOverrides, - doc: getLensAttributesMock(attributesOverrides), })), updateVisualizationContext: jest.fn(), }; diff --git a/x-pack/plugins/lens/public/react_embeddable/renderer/lens_embeddable_component.test.tsx b/x-pack/plugins/lens/public/react_embeddable/renderer/lens_embeddable_component.test.tsx index f444f429250b..fd6d271e2c9b 100644 --- a/x-pack/plugins/lens/public/react_embeddable/renderer/lens_embeddable_component.test.tsx +++ b/x-pack/plugins/lens/public/react_embeddable/renderer/lens_embeddable_component.test.tsx @@ -6,7 +6,7 @@ */ import { render, screen } from '@testing-library/react'; -import { getLensApiMock, getLensInternalApiMock } from '../mocks'; +import { getLensApiMock, getLensInternalApiMock, getValidExpressionParams } from '../mocks'; import { LensApi, LensInternalApi } from '../types'; import { BehaviorSubject } from 'rxjs'; import { PublishingSubject } from '@kbn/presentation-publishing'; @@ -25,6 +25,9 @@ function getDefaultProps({ internalApiOverrides = undefined, apiOverrides = undefined, }: { internalApiOverrides?: Partial; apiOverrides?: Partial } = {}) { + const internalApi = getLensInternalApiMock(internalApiOverrides); + // provide a valid expression to render + internalApi.updateExpressionParams(getValidExpressionParams()); return { internalApi: getLensInternalApiMock(internalApiOverrides), api: getLensApiMock(apiOverrides), diff --git a/x-pack/plugins/lens/public/react_embeddable/types.ts b/x-pack/plugins/lens/public/react_embeddable/types.ts index 1a4bf45b11f1..98b85860f414 100644 --- a/x-pack/plugins/lens/public/react_embeddable/types.ts +++ b/x-pack/plugins/lens/public/react_embeddable/types.ts @@ -100,8 +100,12 @@ interface LensApiProps {} export type LensSavedObjectAttributes = Omit; +/** + * This visualization context can have a different attributes than the + * one stored in the Lens API attributes + */ export interface VisualizationContext { - doc: LensDocument | undefined; + activeAttributes: LensDocument | undefined; mergedSearchContext: ExecutionContextSearch; indexPatterns: IndexPatternMap; indexPatternRefs: IndexPatternRef[]; @@ -111,6 +115,7 @@ export interface VisualizationContext { } export interface VisualizationContextHelper { + // the doc prop here is a convenience reference to the internalApi.attributes getVisualizationContext: () => VisualizationContext; updateVisualizationContext: (newContext: Partial) => void; } @@ -399,7 +404,8 @@ export type LensApi = Simplify< // there's some overlapping between this and the LensApi but they are shared references export type LensInternalApi = Simplify< Pick & - PublishesDataViews & { + PublishesDataViews & + VisualizationContextHelper & { attributes$: PublishingSubject; overrides$: PublishingSubject; disableTriggers$: PublishingSubject; diff --git a/x-pack/plugins/lens/public/react_embeddable/user_messages/api.ts b/x-pack/plugins/lens/public/react_embeddable/user_messages/api.ts index 90061cfb7c2f..8058f7961955 100644 --- a/x-pack/plugins/lens/public/react_embeddable/user_messages/api.ts +++ b/x-pack/plugins/lens/public/react_embeddable/user_messages/api.ts @@ -28,7 +28,6 @@ import { import { LensPublicCallbacks, LensEmbeddableStartServices, - VisualizationContext, VisualizationContextHelper, LensApi, LensInternalApi, @@ -43,7 +42,7 @@ function getUpdatedState( datasourceMap: LensEmbeddableStartServices['datasourceMap'] ) { const { - doc, + activeAttributes, mergedSearchContext, indexPatterns, indexPatternRefs, @@ -51,15 +50,15 @@ function getUpdatedState( activeDatasourceState, activeData, } = getVisualizationContext(); - const activeVisualizationId = getActiveVisualizationIdFromDoc(doc); - const activeDatasourceId = getActiveDatasourceIdFromDoc(doc); + const activeVisualizationId = getActiveVisualizationIdFromDoc(activeAttributes); + const activeDatasourceId = getActiveDatasourceIdFromDoc(activeAttributes); const activeDatasource = activeDatasourceId ? datasourceMap[activeDatasourceId] : null; const activeVisualization = activeVisualizationId ? visualizationMap[activeVisualizationId] : undefined; const dataViewObject = getInitialDataViewsObject(indexPatterns, indexPatternRefs); return { - doc, + activeAttributes, mergedSearchContext, activeDatasource, activeVisualization, @@ -100,7 +99,6 @@ function getWarningMessages( export function buildUserMessagesHelpers( api: LensApi, internalApi: LensInternalApi, - getVisualizationContext: () => VisualizationContext, { coreStart, data, visualizationMap, datasourceMap }: LensEmbeddableStartServices, onBeforeBadgesRender: LensPublicCallbacks['onBeforeBadgesRender'], spaces?: SpacesApi, @@ -131,7 +129,7 @@ export function buildUserMessagesHelpers( const getUserMessages: UserMessagesGetter = (locationId, filters) => { const { - doc, + activeAttributes, activeVisualizationState, activeVisualization, activeVisualizationId, @@ -141,12 +139,12 @@ export function buildUserMessagesHelpers( dataViewObject, mergedSearchContext, activeData, - } = getUpdatedState(getVisualizationContext, visualizationMap, datasourceMap); + } = getUpdatedState(internalApi.getVisualizationContext, visualizationMap, datasourceMap); const userMessages: UserMessage[] = []; userMessages.push( ...getApplicationUserMessages({ - visualizationType: doc?.visualizationType, + visualizationType: activeAttributes?.visualizationType, visualizationState: { state: activeVisualizationState, activeId: activeVisualizationId, @@ -162,7 +160,7 @@ export function buildUserMessagesHelpers( }) ); - if (!doc || !activeDatasourceState || !activeVisualizationState) { + if (!activeAttributes || !activeDatasourceState || !activeVisualizationState) { return userMessages; } @@ -178,7 +176,7 @@ export function buildUserMessagesHelpers( datasourceMap, dataViewObject.indexPatterns ), - query: doc.state.query, + query: activeAttributes.state.query, filters: mergedSearchContext.filters ?? [], dateRange: { fromDate: mergedSearchContext.timeRange?.from ?? '', @@ -278,7 +276,7 @@ export function buildUserMessagesHelpers( updateWarnings: () => { addUserMessages( getWarningMessages( - getUpdatedState(getVisualizationContext, visualizationMap, datasourceMap), + getUpdatedState(internalApi.getVisualizationContext, visualizationMap, datasourceMap), api.adapters$.getValue(), data ) diff --git a/x-pack/plugins/lists/README.md b/x-pack/plugins/lists/README.md deleted file mode 100644 index 02be75730341..000000000000 --- a/x-pack/plugins/lists/README.md +++ /dev/null @@ -1,238 +0,0 @@ -README.md for developers working on the backend lists on how to get started -using the CURL scripts in the scripts folder. - -The scripts rely on CURL and jq: - -- [CURL](https://curl.haxx.se) -- [jq](https://stedolan.github.io/jq/) - -Install curl and jq (mac instructions) - -```sh -brew update -brew install curl -brew install jq -``` - -Open `$HOME/.zshrc` or `${HOME}.bashrc` depending on your SHELL output from `echo $SHELL` -and add these environment variables: - -```sh -export ELASTICSEARCH_USERNAME=${user} -export ELASTICSEARCH_PASSWORD=${password} -export ELASTICSEARCH_URL=https://${ip}:9200 -export KIBANA_URL=http://localhost:5601 -export TASK_MANAGER_INDEX=.kibana-task-manager-${your user id} -export KIBANA_INDEX=.kibana-${your user id} -``` - -source `$HOME/.zshrc` or `${HOME}.bashrc` to ensure variables are set: - -```sh -source ~/.zshrc -``` - -Open your `kibana.dev.yml` file and add these lines with your name: - -```sh -xpack.lists.listIndex: '.lists-your-name' -xpack.lists.listItemIndex: '.items-your-name' -``` - -Restart Kibana and ensure that you are using `--no-base-path` as changing the base path is a feature but will -get in the way of the CURL scripts written as is. - -Go to the scripts folder `cd kibana/x-pack/plugins/lists/server/scripts` and run: - -```sh -./hard_reset.sh -./post_list.sh -``` - -which will: - -- Delete any existing lists you have -- Delete any existing list items you have -- Delete any existing exception lists you have -- Delete any existing exception list items you have -- Delete any existing mapping, policies, and templates, you might have previously had. -- Add the latest list and list item index and its mappings using your settings from `kibana.dev.yml` environment variable of `xpack.lists.listIndex` and `xpack.lists.listItemIndex`. -- Posts the sample list from `./lists/new/ip_list.json` - -Now you can run - -```sh -./post_list.sh -``` - -You should see the new list created like so: - -```sh -{ - "id": "ip_list", - "created_at": "2020-05-28T19:15:22.344Z", - "created_by": "yo", - "description": "This list describes bad internet ip", - "name": "Simple list with an ip", - "tie_breaker_id": "c57efbc4-4977-4a32-995f-cfd296bed521", - "type": "ip", - "updated_at": "2020-05-28T19:15:22.344Z", - "updated_by": "yo" -} -``` - -You can add a list item like so: - -```sh - ./post_list_item.sh -``` - -You should see the new list item created and attached to the above list like so: - -```sh -{ - "id": "hand_inserted_item_id", - "type": "ip", - "value": "127.0.0.1", - "created_at": "2020-05-28T19:15:49.790Z", - "created_by": "yo", - "list_id": "ip_list", - "tie_breaker_id": "a881bf2e-1e17-4592-bba8-d567cb07d234", - "updated_at": "2020-05-28T19:15:49.790Z", - "updated_by": "yo" -} -``` - -If you want to post an exception list it would be like so: - -```sh -./post_exception_list.sh -``` - -You should see the new exception list created like so: - -```sh -{ - "created_at": "2020-05-28T19:16:31.052Z", - "created_by": "yo", - "description": "This is a sample endpoint type exception", - "id": "bcb94680-a117-11ea-ad9d-c71f4820e65b", - "list_id": "endpoint_list", - "name": "Sample Endpoint Exception List", - "namespace_type": "single", - "tags": [ - "user added string for a tag", - "malware" - ], - "tie_breaker_id": "86e08c8c-c970-4b08-a6e2-cdba7bb4e023", - "type": "endpoint", - "updated_at": "2020-05-28T19:16:31.080Z", - "updated_by": "yo" -} -``` - -And you can attach exception list items like so: - -```ts -{ - "comments": [], - "created_at": "2020-05-28T19:17:21.099Z", - "created_by": "yo", - "description": "This is a sample endpoint type exception", - "entries": [ - { - "field": "actingProcess.file.signer", - "operator": "included", - "type": "match", - "value": "Elastic, N.V." - }, - { - "field": "event.category", - "operator": "included", - "type": "match_any", - "value": [ - "process", - "malware" - ] - } - ], - "id": "da8d3b30-a117-11ea-ad9d-c71f4820e65b", - "item_id": "endpoint_list_item", - "list_id": "endpoint_list", - "name": "Sample Endpoint Exception List", - "namespace_type": "single", - "os_types": ["linux"], - "tags": [ - "user added string for a tag", - "malware" - ], - "tie_breaker_id": "21f84703-9476-4af8-a212-aad31e18dcb9", - "type": "simple", - "updated_at": "2020-05-28T19:17:21.123Z", - "updated_by": "yo" -} -``` - -You can then do find for each one like so: - -```sh -./find_lists.sh -``` - -```sh -{ - "cursor": "WzIwLFsiYzU3ZWZiYzQtNDk3Ny00YTMyLTk5NWYtY2ZkMjk2YmVkNTIxIl1d", - "data": [ - { - "id": "ip_list", - "created_at": "2020-05-28T19:15:22.344Z", - "created_by": "yo", - "description": "This list describes bad internet ip", - "name": "Simple list with an ip", - "tie_breaker_id": "c57efbc4-4977-4a32-995f-cfd296bed521", - "type": "ip", - "updated_at": "2020-05-28T19:15:22.344Z", - "updated_by": "yo" - } - ], - "page": 1, - "per_page": 20, - "total": 1 -} -``` - -or for finding exception lists: - -```sh -./find_exception_lists.sh -``` - -```sh -{ - "data": [ - { - "created_at": "2020-05-28T19:16:31.052Z", - "created_by": "yo", - "description": "This is a sample endpoint type exception", - "id": "bcb94680-a117-11ea-ad9d-c71f4820e65b", - "list_id": "endpoint_list", - "name": "Sample Endpoint Exception List", - "namespace_type": "single", - "os_types": ["linux"], - "tags": [ - "user added string for a tag", - "malware" - ], - "tie_breaker_id": "86e08c8c-c970-4b08-a6e2-cdba7bb4e023", - "type": "endpoint", - "updated_at": "2020-05-28T19:16:31.080Z", - "updated_by": "yo" - } - ], - "page": 1, - "per_page": 20, - "total": 1 -} -``` - -See the full scripts folder for all the capabilities. diff --git a/x-pack/plugins/lists/jest.config.js b/x-pack/plugins/lists/jest.config.js deleted file mode 100644 index cb9832920183..000000000000 --- a/x-pack/plugins/lists/jest.config.js +++ /dev/null @@ -1,15 +0,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. - */ - -module.exports = { - collectCoverageFrom: ['/x-pack/plugins/lists/{common,public,server}/**/*.{ts,tsx}'], - coverageDirectory: '/target/kibana-coverage/jest/x-pack/plugins/lists', - coverageReporters: ['text', 'html'], - preset: '@kbn/test', - rootDir: '../../..', - roots: ['/x-pack/plugins/lists'], -}; diff --git a/x-pack/plugins/lists/tsconfig.json b/x-pack/plugins/lists/tsconfig.json deleted file mode 100644 index 61229d39bdbd..000000000000 --- a/x-pack/plugins/lists/tsconfig.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types" - }, - "include": [ - "common/**/*", - "public/**/*", - "server/**/*", - // have to declare *.json explicitly due to https://github.com/microsoft/TypeScript/issues/25636 - "server/**/*.json" - ], - "kbn_references": [ - "@kbn/core", - "@kbn/spaces-plugin", - "@kbn/security-plugin", - "@kbn/unified-search-plugin", - "@kbn/securitysolution-io-ts-list-types", - "@kbn/securitysolution-list-constants", - "@kbn/securitysolution-list-hooks", - "@kbn/securitysolution-list-api", - "@kbn/securitysolution-lists-common", - "@kbn/securitysolution-exceptions-common", - "@kbn/securitysolution-endpoint-exceptions-common", - "@kbn/kibana-react-plugin", - "@kbn/i18n", - "@kbn/data-plugin", - "@kbn/securitysolution-list-utils", - "@kbn/securitysolution-utils", - "@kbn/es-query", - "@kbn/i18n-react", - "@kbn/securitysolution-autocomplete", - "@kbn/config-schema", - "@kbn/securitysolution-io-ts-utils", - "@kbn/core-http-server", - "@kbn/securitysolution-es-utils", - "@kbn/securitysolution-io-ts-types", - "@kbn/std", - "@kbn/utils", - "@kbn/logging-mocks", - "@kbn/utility-types", - "@kbn/core-elasticsearch-client-server-mocks", - "@kbn/core-saved-objects-server", - "@kbn/zod-helpers", - "@kbn/core-security-server", - "@kbn/core-http-server-mocks", - "@kbn/core-http-server-utils" - ], - "exclude": ["target/**/*"] -} diff --git a/x-pack/plugins/observability_solution/apm/common/service_health_status.ts b/x-pack/plugins/observability_solution/apm/common/service_health_status.ts index 7f5530aa7fa0..65427caba747 100644 --- a/x-pack/plugins/observability_solution/apm/common/service_health_status.ts +++ b/x-pack/plugins/observability_solution/apm/common/service_health_status.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; +import type { EuiThemeComputed } from '@elastic/eui'; import { ML_ANOMALY_SEVERITY } from '@kbn/ml-anomaly-utils/anomaly_severity'; export enum ServiceHealthStatus { @@ -34,29 +34,35 @@ export function getServiceHealthStatus({ severity }: { severity: ML_ANOMALY_SEVE } } -export function getServiceHealthStatusColor(theme: EuiTheme, status: ServiceHealthStatus) { +export function getServiceHealthStatusColor( + euiTheme: EuiThemeComputed, + status: ServiceHealthStatus +) { switch (status) { case ServiceHealthStatus.healthy: - return theme.eui.euiColorVis0; + return euiTheme.colors.success; case ServiceHealthStatus.warning: - return theme.eui.euiColorVis5; + return euiTheme.colors.warning; case ServiceHealthStatus.critical: - return theme.eui.euiColorVis9; + return euiTheme.colors.danger; case ServiceHealthStatus.unknown: - return theme.eui.euiColorMediumShade; + return euiTheme.colors.mediumShade; } } -export function getServiceHealthStatusBadgeColor(theme: EuiTheme, status: ServiceHealthStatus) { +export function getServiceHealthStatusBadgeColor( + euiTheme: EuiThemeComputed, + status: ServiceHealthStatus +) { switch (status) { case ServiceHealthStatus.healthy: - return theme.eui.euiColorVis0_behindText; + return euiTheme.colors.success; case ServiceHealthStatus.warning: - return theme.eui.euiColorVis5_behindText; + return euiTheme.colors.warning; case ServiceHealthStatus.critical: - return theme.eui.euiColorVis9_behindText; + return euiTheme.colors.danger; case ServiceHealthStatus.unknown: - return theme.eui.euiColorMediumShade; + return euiTheme.colors.mediumShade; } } diff --git a/x-pack/plugins/observability_solution/apm/public/assistant_functions/get_apm_timeseries.tsx b/x-pack/plugins/observability_solution/apm/public/assistant_functions/get_apm_timeseries.tsx index 16d5d077a9b4..9c29bb936db8 100644 --- a/x-pack/plugins/observability_solution/apm/public/assistant_functions/get_apm_timeseries.tsx +++ b/x-pack/plugins/observability_solution/apm/public/assistant_functions/get_apm_timeseries.tsx @@ -20,7 +20,6 @@ import type { GetApmTimeseriesFunctionResponse, } from '../../server/assistant_functions/get_apm_timeseries'; import { Coordinate, TimeSeries } from '../../typings/timeseries'; -import { ApmThemeProvider } from '../components/routing/app_root'; import { ChartType, getTimeSeriesColor, @@ -54,101 +53,99 @@ export function registerGetApmTimeseriesFunction({ return ( - - - {Object.values(groupedSeries).map((groupSeries) => { - const groupId = groupSeries[0].group; - - const maxY = getMaxY(groupSeries); - const latencyFormatter = getDurationFormatter(maxY, 10, 1000); - - let yLabelFormat: (value: number) => string; - - const firstStat = groupSeries[0].stat; - - switch (firstStat.timeseries.name) { - case 'transaction_throughput': - case 'exit_span_throughput': - case 'error_event_rate': - yLabelFormat = asTransactionRate; - break; - - case 'transaction_latency': - case 'exit_span_latency': - yLabelFormat = getResponseTimeTickFormatter(latencyFormatter); - break; - - case 'transaction_failure_rate': - case 'exit_span_failure_rate': - yLabelFormat = (y) => asPercent(y || 0, 100); - break; - } - - const timeseries: Array> = groupSeries.map( - (series): TimeSeries => { - let chartType: ChartType; - - const data = series.data; - - switch (series.stat.timeseries.name) { - case 'transaction_throughput': - case 'exit_span_throughput': - chartType = ChartType.THROUGHPUT; - break; - - case 'transaction_failure_rate': - case 'exit_span_failure_rate': - chartType = ChartType.FAILED_TRANSACTION_RATE; - break; - - case 'transaction_latency': - if (series.stat.timeseries.function === LatencyAggregationType.p99) { - chartType = ChartType.LATENCY_P99; - } else if (series.stat.timeseries.function === LatencyAggregationType.p95) { - chartType = ChartType.LATENCY_P95; - } else { - chartType = ChartType.LATENCY_AVG; - } - break; - - case 'exit_span_latency': + + {Object.values(groupedSeries).map((groupSeries) => { + const groupId = groupSeries[0].group; + + const maxY = getMaxY(groupSeries); + const latencyFormatter = getDurationFormatter(maxY, 10, 1000); + + let yLabelFormat: (value: number) => string; + + const firstStat = groupSeries[0].stat; + + switch (firstStat.timeseries.name) { + case 'transaction_throughput': + case 'exit_span_throughput': + case 'error_event_rate': + yLabelFormat = asTransactionRate; + break; + + case 'transaction_latency': + case 'exit_span_latency': + yLabelFormat = getResponseTimeTickFormatter(latencyFormatter); + break; + + case 'transaction_failure_rate': + case 'exit_span_failure_rate': + yLabelFormat = (y) => asPercent(y || 0, 100); + break; + } + + const timeseries: Array> = groupSeries.map( + (series): TimeSeries => { + let chartType: ChartType; + + const data = series.data; + + switch (series.stat.timeseries.name) { + case 'transaction_throughput': + case 'exit_span_throughput': + chartType = ChartType.THROUGHPUT; + break; + + case 'transaction_failure_rate': + case 'exit_span_failure_rate': + chartType = ChartType.FAILED_TRANSACTION_RATE; + break; + + case 'transaction_latency': + if (series.stat.timeseries.function === LatencyAggregationType.p99) { + chartType = ChartType.LATENCY_P99; + } else if (series.stat.timeseries.function === LatencyAggregationType.p95) { + chartType = ChartType.LATENCY_P95; + } else { chartType = ChartType.LATENCY_AVG; - break; - - case 'error_event_rate': - chartType = ChartType.ERROR_OCCURRENCES; - break; - } - - return { - title: series.id, - type: 'line', - color: getTimeSeriesColor(chartType!).currentPeriodColor, - data, - }; + } + break; + + case 'exit_span_latency': + chartType = ChartType.LATENCY_AVG; + break; + + case 'error_event_rate': + chartType = ChartType.ERROR_OCCURRENCES; + break; } - ); - - return ( - - - - {groupId} - - - - - ); - })} - - + + return { + title: series.id, + type: 'line', + color: getTimeSeriesColor(chartType!).currentPeriodColor, + data, + }; + } + ); + + return ( + + + + {groupId} + + + + + ); + })} + ); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/alerting/ui_components/chart_preview/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/alerting/ui_components/chart_preview/index.tsx index 8e7cce37b5be..0136fcfb88f3 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/alerting/ui_components/chart_preview/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/alerting/ui_components/chart_preview/index.tsx @@ -10,6 +10,8 @@ import { Axis, BarSeries, Chart, + LIGHT_THEME, + DARK_THEME, LineAnnotation, Position, RectAnnotation, @@ -20,7 +22,7 @@ import { Tooltip, niceTimeFormatter, } from '@elastic/charts'; -import { EuiSpacer } from '@elastic/eui'; +import { COLOR_MODES_STANDARD, EuiSpacer, useEuiTheme } from '@elastic/eui'; import React, { useMemo } from 'react'; import { IUiSettingsClient } from '@kbn/core/public'; import { TimeUnitChar } from '@kbn/observability-plugin/common'; @@ -28,7 +30,6 @@ import { UI_SETTINGS } from '@kbn/data-plugin/public'; import moment from 'moment'; import { i18n } from '@kbn/i18n'; import { Coordinate } from '../../../../../typings/timeseries'; -import { useTheme } from '../../../../hooks/use_theme'; import { getTimeZone } from '../../../shared/charts/helper/timezone'; import { TimeLabelForData, TIME_LABELS, getDomain } from './chart_preview_helper'; import { ALERT_PREVIEW_BUCKET_SIZE } from '../../utils/helper'; @@ -52,15 +53,15 @@ export function ChartPreview({ timeUnit = 'm', totalGroups, }: ChartPreviewProps) { - const theme = useTheme(); + const theme = useEuiTheme(); const thresholdOpacity = 0.3; const DEFAULT_DATE_FORMAT = 'Y-MM-DD HH:mm:ss'; const style = { - fill: theme.eui.euiColorVis2, + fill: theme.euiTheme.colors.vis.euiColorVis2, line: { strokeWidth: 2, - stroke: theme.eui.euiColorVis2, + stroke: theme.euiTheme.colors.vis.euiColorVis2, opacity: 1, }, opacity: thresholdOpacity, @@ -121,6 +122,7 @@ export function ChartPreview({ legendPosition={'bottom'} legendSize={legendSize} locale={i18n.getLocale()} + theme={theme.colorMode === COLOR_MODES_STANDARD.dark ? DARK_THEME : LIGHT_THEME} /> setInfoOpen(false), []); - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const params = useFetchParams(); @@ -280,7 +280,9 @@ export function FieldStatsPopover({ } )} data-test-subj={'apmCorrelationsContextPopoverButton'} - style={{ marginLeft: theme.eui.euiSizeXS }} + css={css` + margin-left: ${euiTheme.size.xs}; + `} /> ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/correlations_table.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/correlations_table.tsx index ea79b1ef198b..8524a29fb4b6 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/correlations_table.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/correlations_table.tsx @@ -7,13 +7,12 @@ import React, { useCallback, useMemo, useState } from 'react'; import { debounce } from 'lodash'; -import { EuiBasicTable, EuiBasicTableColumn } from '@elastic/eui'; +import { EuiBasicTable, EuiBasicTableColumn, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import type { EuiTableSortingType } from '@elastic/eui/src/components/basic_table/table_types'; import type { Criteria } from '@elastic/eui/src/components/basic_table/basic_table'; import { useUiTracker } from '@kbn/observability-shared-plugin/public'; import { FETCH_STATUS } from '../../../hooks/use_fetcher'; -import { useTheme } from '../../../hooks/use_theme'; import type { FieldValuePair } from '../../../../common/correlations/types'; const PAGINATION_SIZE_OPTIONS = [5, 10, 20, 50]; @@ -43,7 +42,7 @@ export function CorrelationsTable({ sorting, rowHeader, }: CorrelationsTableProps) { - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const trackApmEvent = useUiTracker({ app: 'apm' }); const trackSelectSignificantCorrelationTerm = useCallback( () => debounce(() => trackApmEvent({ metric: 'select_significant_term' }), 1000), @@ -105,7 +104,7 @@ export function CorrelationsTable({ selectedTerm.fieldValue === term.fieldValue && selectedTerm.fieldName === term.fieldName ? { - backgroundColor: euiTheme.eui.euiColorLightestShade, + backgroundColor: euiTheme.colors.lightestShade, } : null, }; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/failed_transactions_correlations.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/failed_transactions_correlations.tsx index d02eed810acd..e6c6ce65dfff 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/failed_transactions_correlations.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/failed_transactions_correlations.tsx @@ -18,6 +18,7 @@ import { EuiBadge, EuiSwitch, EuiIconTip, + useEuiTheme, } from '@elastic/eui'; import type { EuiTableSortingType } from '@elastic/eui/src/components/basic_table/table_types'; import type { Direction } from '@elastic/eui/src/services/sort/sort_direction'; @@ -34,7 +35,6 @@ import { FailedTransactionsCorrelation } from '../../../../common/correlations/f import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { useLocalStorage } from '../../../hooks/use_local_storage'; import { FETCH_STATUS } from '../../../hooks/use_fetcher'; -import { useTheme } from '../../../hooks/use_theme'; import { push } from '../../shared/links/url_helpers'; import { CorrelationsTable } from './correlations_table'; @@ -54,7 +54,7 @@ import { MIN_TAB_TITLE_HEIGHT } from '../../shared/charts/duration_distribution_ import { TotalDocCountLabel } from '../../shared/charts/duration_distribution_chart/total_doc_count_label'; export function FailedTransactionsCorrelations({ onFilter }: { onFilter: () => void }) { - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const { core: { notifications }, @@ -456,7 +456,7 @@ export function FailedTransactionsCorrelations({ onFilter }: { onFilter: () => v style={{ display: 'flex', flexDirection: 'row', - paddingLeft: euiTheme.eui.euiSizeS, + paddingLeft: euiTheme.size.s, }} > v void }) { core: { notifications }, } = useApmPluginContext(); - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const { progress, response, startFetch, cancelFetch } = useLatencyCorrelations(); const { overallHistogram, hasData, status } = getOverallHistogram(response, progress.isRunning); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/dependency_operation_detail_view/dependency_operation_distribution_chart.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/dependency_operation_detail_view/dependency_operation_distribution_chart.tsx index 3f8b8728fd48..f7cd26fab3f8 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/dependency_operation_detail_view/dependency_operation_distribution_chart.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/dependency_operation_detail_view/dependency_operation_distribution_chart.tsx @@ -7,11 +7,11 @@ import { i18n } from '@kbn/i18n'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import React from 'react'; +import { useEuiTheme } from '@elastic/eui'; import { DEFAULT_PERCENTILE_THRESHOLD } from '../../../../common/correlations/constants'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useFetcher } from '../../../hooks/use_fetcher'; import { useSampleChartSelection } from '../../../hooks/use_sample_chart_selection'; -import { useTheme } from '../../../hooks/use_theme'; import { useTimeRange } from '../../../hooks/use_time_range'; import { DurationDistributionChartData } from '../../shared/charts/duration_distribution_chart'; import { DurationDistributionChartWithScrubber } from '../../shared/charts/duration_distribution_chart_with_scrubber'; @@ -22,7 +22,7 @@ export function DependencyOperationDistributionChart() { // there is no "current" event in the dependency operation detail view const markerCurrentEvent = undefined; - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const { query: { @@ -67,14 +67,14 @@ export function DependencyOperationDistributionChart() { const chartData: DurationDistributionChartData[] = [ { - areaSeriesColor: euiTheme.eui.euiColorVis1, + areaSeriesColor: euiTheme.colors.vis.euiColorVis1, histogram: data?.allSpansDistribution.overallHistogram ?? [], id: i18n.translate('xpack.apm.dependencyOperationDistributionChart.allSpansLegendLabel', { defaultMessage: 'All spans', }), }, { - areaSeriesColor: euiTheme.eui.euiColorVis7, + areaSeriesColor: euiTheme.colors.vis.euiColorVis7, histogram: data?.failedSpansDistribution?.overallHistogram ?? [], id: i18n.translate('xpack.apm.dependencyOperationDistributionChart.failedSpansLegendLabel', { defaultMessage: 'Failed spans', diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/entity_link.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/entity_link.test.tsx index 4515c2cdd571..7bbfb43af71b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/entity_link.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/entity_link.test.tsx @@ -17,7 +17,6 @@ import { fromQuery } from '../../../shared/links/url_helpers'; import { APIReturnType } from '../../../../services/rest/create_call_apm_api'; import { Redirect } from 'react-router-dom'; import { ApmPluginContextValue } from '../../../../context/apm_plugin/apm_plugin_context'; -import { ApmThemeProvider } from '../../../routing/app_root'; import * as useEntityCentricExperienceSetting from '../../../../hooks/use_entity_centric_experience_setting'; jest.mock('react-router-dom', () => ({ @@ -85,9 +84,7 @@ const renderEntityLink = ({ } as unknown as ApmPluginContextValue } > - - - + ); return { rerender, ...tools }; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/index.tsx index 2ea10868957b..7ad5661159fd 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/entities/entity_link/index.tsx @@ -5,7 +5,14 @@ * 2.0. */ -import { EuiButtonEmpty, EuiEmptyPrompt, EuiImage, EuiLink, EuiLoadingSpinner } from '@elastic/eui'; +import { + EuiButtonEmpty, + EuiEmptyPrompt, + EuiImage, + EuiLink, + EuiLoadingSpinner, + useEuiTheme, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import { useKibana } from '@kbn/kibana-react-plugin/public'; @@ -18,7 +25,6 @@ import { useApmParams } from '../../../../hooks/use_apm_params'; import { useApmRouter } from '../../../../hooks/use_apm_router'; import { useEntityCentricExperienceSetting } from '../../../../hooks/use_entity_centric_experience_setting'; import { FETCH_STATUS, isPending, useFetcher } from '../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../hooks/use_theme'; import { ApmPluginStartDeps } from '../../../../plugin'; const pageHeader = { @@ -27,7 +33,7 @@ const pageHeader = { export function EntityLink() { const router = useApmRouter({ prependBasePath: false }); - const theme = useTheme(); + const { colorMode } = useEuiTheme(); const { services } = useKibana(); const { observabilityShared, data } = services; const timeRange = data.query.timefilter.timefilter.getTime(); @@ -65,7 +71,7 @@ export function EntityLink() { icon={ } diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/distribution/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/distribution/index.tsx index b8902b30dcff..47101471a551 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/distribution/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/distribution/index.tsx @@ -18,14 +18,13 @@ import { DARK_THEME, LegendValue, } from '@elastic/charts'; -import { EuiTitle } from '@elastic/eui'; +import { EuiTitle, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { usePreviousPeriodLabel } from '../../../../hooks/use_previous_period_text'; -import { useTheme } from '../../../../hooks/use_theme'; import { APIReturnType } from '../../../../services/rest/create_call_apm_api'; import { ChartContainer } from '../../../shared/charts/chart_container'; import { ChartType, getTimeSeriesColor } from '../../../shared/charts/helper/get_timeseries_color'; @@ -42,7 +41,7 @@ interface Props { export function ErrorDistribution({ distribution, title, fetchStatus }: Props) { const { core } = useApmPluginContext(); - const theme = useTheme(); + const { colorMode } = useEuiTheme(); const { urlParams } = useLegacyUrlParams(); const { comparisonEnabled } = urlParams; @@ -97,7 +96,7 @@ export function ErrorDistribution({ distribution, title, fetchStatus }: Props) { showLegend legendValues={[LegendValue.CurrentAndLastValue]} legendPosition={Position.Bottom} - theme={theme.darkMode ? DARK_THEME : LIGHT_THEME} + theme={colorMode === 'DARK' ? DARK_THEME : LIGHT_THEME} locale={i18n.getLocale()} /> theme.eui.euiSizeS}; +const TransactionLinkName = styled.div` + margin-left: ${({ theme }) => theme.euiTheme.size.s}; display: inline-block; vertical-align: middle; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/exception_stacktrace.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/exception_stacktrace.test.tsx index a4c23555edda..3740edcbfe7d 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/exception_stacktrace.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/exception_stacktrace.test.tsx @@ -8,6 +8,7 @@ import { composeStories } from '@storybook/testing-react'; import React from 'react'; import { mount } from 'enzyme'; +import { EuiThemeProvider } from '@elastic/eui'; import * as stories from './exception_stacktrace.stories'; import { ExceptionStackTraceTitleProps } from './exception_stacktrace_title'; @@ -17,10 +18,16 @@ describe('ExceptionStacktrace', () => { describe('render', () => { describe('with stacktraces', () => { it('renders the stacktraces', () => { - expect(mount().find('Stacktrace')).toHaveLength(3); + expect( + mount(, { + wrappingComponent: EuiThemeProvider, + }).find('Stacktrace') + ).toHaveLength(3); }); it('should have the title in a specific format', function () { - const wrapper = mount().find('ExceptionStacktraceTitle'); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }).find('ExceptionStacktraceTitle'); expect(wrapper).toHaveLength(1); const { type, message } = wrapper.props() as ExceptionStackTraceTitleProps; expect(wrapper.text()).toContain(`${type}: ${message}`); @@ -29,7 +36,11 @@ describe('ExceptionStacktrace', () => { describe('with more than one stack trace', () => { it('renders cause stacktraces', () => { - expect(mount().find('CauseStacktrace')).toHaveLength(2); + expect( + mount(, { + wrappingComponent: EuiThemeProvider, + }).find('CauseStacktrace') + ).toHaveLength(2); }); }); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/sample_summary.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/sample_summary.tsx index c7acbfee7e45..40d9a21bee35 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/sample_summary.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_details/error_sampler/sample_summary.tsx @@ -4,17 +4,17 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { EuiText, EuiSpacer, EuiCodeBlock } from '@elastic/eui'; +import { EuiText, EuiSpacer, EuiCodeBlock, useEuiFontSize } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { APMError } from '../../../../../typings/es_schemas/ui/apm_error'; import { NOT_AVAILABLE_LABEL } from '../../../../../common/i18n'; -const Label = euiStyled.div` - margin-bottom: ${({ theme }) => theme.eui.euiSizeXS}; - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; - color: ${({ theme }) => theme.eui.euiColorDarkestShade}; +const Label = styled.div` + margin-bottom: ${({ theme }) => theme.euiTheme.size.xs}; + font-size: ${() => useEuiFontSize('s').fontSize}; + color: ${({ theme }) => theme.euiTheme.colors.darkestShade}; `; interface Props { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_overview/error_group_list/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_overview/error_group_list/index.tsx index 51377d5e3770..c6593806191f 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/error_group_overview/error_group_list/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/error_group_overview/error_group_list/index.tsx @@ -7,7 +7,7 @@ import { EuiBadge, EuiIconTip, EuiToolTip, RIGHT_ALIGNMENT } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import React, { useMemo, useState } from 'react'; import { apmEnableTableSearchBar } from '@kbn/observability-plugin/common'; import { isPending } from '../../../../hooks/use_fetcher'; @@ -30,25 +30,25 @@ import { isTimeComparison } from '../../../shared/time_comparison/get_comparison import { ErrorGroupItem, useErrorGroupListData } from './use_error_group_list_data'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; -const GroupIdLink = euiStyled(ErrorDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const GroupIdLink = styled(ErrorDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; `; -const MessageAndCulpritCell = euiStyled.div` +const MessageAndCulpritCell = styled.div` ${truncate('100%')}; `; -const ErrorLink = euiStyled(ErrorOverviewLink)` +const ErrorLink = styled(ErrorOverviewLink)` ${truncate('100%')}; `; -const MessageLink = euiStyled(ErrorDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const MessageLink = styled(ErrorDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; ${truncate('100%')}; `; -const Culprit = euiStyled.div` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const Culprit = styled.div` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; `; interface Props { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/help_popover/help_popover.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/help_popover/help_popover.tsx index c883376cac4e..cfb50f983fdb 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/help_popover/help_popover.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/help_popover/help_popover.tsx @@ -16,9 +16,9 @@ import { EuiPopoverTitle, EuiText, } from '@elastic/eui'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; -const PopoverContent = euiStyled(EuiText)` +const PopoverContent = styled(EuiText)` max-width: 480px; max-height: 40vh; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/empty_prompt.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/empty_prompt.tsx index 293dff7b6080..0d212682145f 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/empty_prompt.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/empty_prompt.tsx @@ -11,12 +11,12 @@ import { EuiDescriptionListTitle, EuiEmptyPrompt, EuiImage, + useEuiTheme, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import noResultsIllustrationDark from '../../../../assets/no_results_dark.svg'; import noResultsIllustrationLight from '../../../../assets/no_results_light.svg'; -import { useTheme } from '../../../../hooks/use_theme'; export function EmptyPrompt() { return ( @@ -52,9 +52,10 @@ export function EmptyPrompt() { } function NoResultsIllustration() { - const theme = useTheme(); + const { colorMode } = useEuiTheme(); - const illustration = theme.darkMode ? noResultsIllustrationDark : noResultsIllustrationLight; + const illustration = + colorMode === 'DARK' ? noResultsIllustrationDark : noResultsIllustrationLight; return ( diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/jvm_metrics_overview/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/jvm_metrics_overview/index.tsx index 63a1dac2017b..a936ec601ebe 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/jvm_metrics_overview/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/jvm_metrics_overview/index.tsx @@ -7,7 +7,7 @@ import { EuiToolTip, EuiIcon } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { getServiceNodeName, SERVICE_NODE_NAME_MISSING } from '../../../../../common/service_nodes'; import { asDynamicBytes, asInteger, asPercent } from '../../../../../common/utils/formatters'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; @@ -21,7 +21,7 @@ import { ITableColumn, ManagedTable } from '../../../shared/managed_table'; const INITIAL_SORT_FIELD = 'cpu'; const INITIAL_SORT_DIRECTION = 'desc'; -const ServiceNodeName = euiStyled.div` +const ServiceNodeName = styled.div` ${truncate(8 * unit)} `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_function_name_link.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_function_name_link.tsx index 2de5991b19b4..eb1ab41f1dfa 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_function_name_link.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_function_name_link.tsx @@ -5,14 +5,16 @@ * 2.0. */ import { EuiLink } from '@elastic/eui'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import React from 'react'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useApmRouter } from '../../../../hooks/use_apm_router'; import { truncate } from '../../../../utils/style'; -const StyledLink = euiStyled(EuiLink)`${truncate('100%')};`; +const StyledLink = styled(EuiLink)` + ${truncate('100%')}; +`; interface Props { serverlessFunctionName: string; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_summary.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_summary.tsx index ab662e53d9d8..30544489eb0d 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_summary.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/metrics/serverless_metrics/serverless_summary.tsx @@ -15,7 +15,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { asMillisecondDuration, asPercent } from '../../../../../common/utils/formatters'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; import { useApmParams } from '../../../../hooks/use_apm_params'; @@ -34,7 +34,7 @@ const CentralizedContainer = styled.div` const Border = styled.div` height: 55px; - border-right: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; + border-right: ${({ theme }) => theme.euiTheme.border.thin}; `; function VerticalRule() { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/metrics_details/service_node_metrics/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/metrics_details/service_node_metrics/index.tsx index 89ffc3b0be3f..e01dc55447f2 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/metrics_details/service_node_metrics/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/metrics_details/service_node_metrics/index.tsx @@ -20,7 +20,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import React from 'react'; import { ApmDocumentType } from '../../../../../common/document_type'; import { getServiceNodeName, SERVICE_NODE_NAME_MISSING } from '../../../../../common/service_nodes'; @@ -42,7 +42,7 @@ const INITIAL_DATA = { containerId: '', }; -const Truncate = euiStyled.span` +const Truncate = styled.span` display: block; ${truncate(unit * 12)} `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/crash_group_list.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/crash_group_list.test.tsx index cd1d4110e32f..aab5a3a3af20 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/crash_group_list.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/crash_group_list.test.tsx @@ -6,14 +6,14 @@ */ import { composeStories } from '@storybook/testing-react'; -import { render } from '@testing-library/react'; import React from 'react'; import * as stories from './crash_group_list.stories'; +import { renderWithTheme } from '../../../../../utils/test_helpers'; const { Example } = composeStories(stories); describe('MobileCrashGroupList', () => { it('renders', () => { - expect(() => render()).not.toThrowError(); + expect(() => renderWithTheme()).not.toThrowError(); }); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/index.tsx index 4923ed35a6d4..403a5ff03db7 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/crash_group_list/index.tsx @@ -7,7 +7,7 @@ import { EuiToolTip, RIGHT_ALIGNMENT, LEFT_ALIGNMENT, EuiIconTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import React, { useMemo } from 'react'; import { NOT_AVAILABLE_LABEL } from '../../../../../../common/i18n'; import { asInteger } from '../../../../../../common/utils/formatters'; @@ -25,20 +25,20 @@ import { ITableColumn, ManagedTable } from '../../../../shared/managed_table'; import { TimestampTooltip } from '../../../../shared/timestamp_tooltip'; import { isTimeComparison } from '../../../../shared/time_comparison/get_comparison_options'; -const MessageAndCulpritCell = euiStyled.div` +const MessageAndCulpritCell = styled.div` ${truncate('100%')}; `; -const ErrorLink = euiStyled(ErrorOverviewLink)` +const ErrorLink = styled(ErrorOverviewLink)` ${truncate('100%')}; `; -const GroupIdLink = euiStyled(CrashDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const GroupIdLink = styled(CrashDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; `; -const MessageLink = euiStyled(CrashDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const MessageLink = styled(CrashDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; ${truncate('100%')}; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/error_group_list.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/error_group_list.test.tsx index 278825c25c68..92cad40623c0 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/error_group_list.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/error_group_list.test.tsx @@ -6,14 +6,14 @@ */ import { composeStories } from '@storybook/testing-react'; -import { render } from '@testing-library/react'; import React from 'react'; import * as stories from './error_group_list.stories'; +import { renderWithTheme } from '../../../../../utils/test_helpers'; const { Example } = composeStories(stories); describe('ErrorGroupList', () => { it('renders', () => { - expect(() => render()).not.toThrowError(); + expect(() => renderWithTheme()).not.toThrowError(); }); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/index.tsx index 0938c97d737d..7153b673b319 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/errors_and_crashes_overview/error_group_list/index.tsx @@ -7,7 +7,7 @@ import { EuiBadge, EuiToolTip, RIGHT_ALIGNMENT, LEFT_ALIGNMENT, EuiIconTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import React, { useMemo } from 'react'; import { NOT_AVAILABLE_LABEL } from '../../../../../../common/i18n'; import { asInteger } from '../../../../../../common/utils/formatters'; @@ -25,20 +25,20 @@ import { ITableColumn, ManagedTable } from '../../../../shared/managed_table'; import { TimestampTooltip } from '../../../../shared/timestamp_tooltip'; import { isTimeComparison } from '../../../../shared/time_comparison/get_comparison_options'; -const GroupIdLink = euiStyled(ErrorDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const GroupIdLink = styled(ErrorDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; `; -const MessageAndCulpritCell = euiStyled.div` +const MessageAndCulpritCell = styled.div` ${truncate('100%')}; `; -const ErrorLink = euiStyled(ErrorOverviewLink)` +const ErrorLink = styled(ErrorOverviewLink)` ${truncate('100%')}; `; -const MessageLink = euiStyled(ErrorDetailLink)` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const MessageLink = styled(ErrorDetailLink)` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; ${truncate('100%')}; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/location_stats.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/location_stats.tsx index 47451fac265c..b514277a5dc9 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/location_stats.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/location_stats.tsx @@ -6,9 +6,8 @@ */ import { MetricDatum, MetricTrendShape } from '@elastic/charts'; import { i18n } from '@kbn/i18n'; -import { EuiIcon, EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui'; +import { EuiIcon, EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, useEuiTheme } from '@elastic/eui'; import React, { useCallback } from 'react'; -import { useTheme } from '@kbn/observability-shared-plugin/public'; import { useFetcher, isPending, FETCH_STATUS } from '../../../../../hooks/use_fetcher'; import { CLIENT_GEO_COUNTRY_NAME } from '../../../../../../common/es_fields/apm'; import { NOT_AVAILABLE_LABEL } from '../../../../../../common/i18n'; @@ -45,7 +44,7 @@ export function MobileLocationStats({ environment: string; comparisonEnabled: boolean; }) { - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const previousPeriodLabel = usePreviousPeriodLabel(); @@ -107,7 +106,7 @@ export function MobileLocationStats({ const metrics: MetricDatum[] = [ { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.location.metrics.http.requests.title', { defaultMessage: 'Most used in', }), @@ -121,7 +120,7 @@ export function MobileLocationStats({ trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.location.metrics.mostCrashes', { defaultMessage: 'Most crashes', }), @@ -135,7 +134,7 @@ export function MobileLocationStats({ trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.location.metrics.sessions', { defaultMessage: 'Most sessions', }), @@ -149,7 +148,7 @@ export function MobileLocationStats({ trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.location.metrics.launches', { defaultMessage: 'Most launches', }), diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/stats.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/stats.tsx index 59f6020d61c3..4376eeccab5c 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/stats.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/mobile/service_overview/stats/stats.tsx @@ -6,9 +6,8 @@ */ import { MetricDatum, MetricTrendShape } from '@elastic/charts'; import { i18n } from '@kbn/i18n'; -import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiLoadingSpinner } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiLoadingSpinner, useEuiTheme } from '@elastic/eui'; import React, { useCallback } from 'react'; -import { useTheme } from '@kbn/observability-shared-plugin/public'; import { NOT_AVAILABLE_LABEL } from '../../../../../../common/i18n'; import { useAnyOfApmParams } from '../../../../../hooks/use_apm_params'; import { FETCH_STATUS, isPending, useFetcher } from '../../../../../hooks/use_fetcher'; @@ -20,7 +19,7 @@ const valueFormatter = (value: number, suffix = '') => { }; export function MobileStats({ start, end, kuery }: { start: string; end: string; kuery: string }) { - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const { path: { serviceName }, @@ -77,7 +76,7 @@ export function MobileStats({ start, end, kuery }: { start: string; end: string; const metrics: MetricDatum[] = [ { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.metrics.crash.rate', { defaultMessage: 'Crash rate', }), @@ -92,7 +91,7 @@ export function MobileStats({ start, end, kuery }: { start: string; end: string; trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.metrics.load.time', { defaultMessage: 'Average app load time', }), @@ -105,7 +104,7 @@ export function MobileStats({ start, end, kuery }: { start: string; end: string; trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.metrics.sessions', { defaultMessage: 'Sessions', }), @@ -118,7 +117,7 @@ export function MobileStats({ start, end, kuery }: { start: string; end: string; trendShape: MetricTrendShape.Area, }, { - color: euiTheme.eui.euiColorLightestShade, + color: euiTheme.colors.lightestShade, title: i18n.translate('xpack.apm.mobile.metrics.http.requests', { defaultMessage: 'HTTP requests', }), diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_dashboards/empty_dashboards.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_dashboards/empty_dashboards.tsx index 9b7ace008206..bf4c23406099 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_dashboards/empty_dashboards.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_dashboards/empty_dashboards.tsx @@ -5,17 +5,16 @@ * 2.0. */ import React from 'react'; -import { EuiEmptyPrompt, EuiImage } from '@elastic/eui'; +import { EuiEmptyPrompt, EuiImage, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { dashboardsDark, dashboardsLight } from '@kbn/shared-svg'; -import { useTheme } from '../../../hooks/use_theme'; interface Props { actions: React.ReactNode; } export function EmptyDashboards({ actions }: Props) { - const theme = useTheme(); + const { colorMode } = useEuiTheme(); return ( <> @@ -25,7 +24,7 @@ export function EmptyDashboards({ actions }: Props) { icon={ } diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_groups/service_group_save/select_services.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_groups/service_group_save/select_services.tsx index b6a901bac8d2..38f681921a6c 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_groups/service_group_save/select_services.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_groups/service_group_save/select_services.tsx @@ -23,7 +23,7 @@ import { import { i18n } from '@kbn/i18n'; import { css } from '@emotion/react'; import React, { useEffect, useState, useMemo } from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { isEmpty } from 'lodash'; import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; import { KueryBar } from '../../../shared/kuery_bar'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_inventory/service_list/health_badge.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_inventory/service_list/health_badge.tsx index aa4299006cc4..1c21826c80d3 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_inventory/service_list/health_badge.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_inventory/service_list/health_badge.tsx @@ -6,19 +6,18 @@ */ import React from 'react'; -import { EuiBadge } from '@elastic/eui'; +import { EuiBadge, useEuiTheme } from '@elastic/eui'; import { getServiceHealthStatusBadgeColor, getServiceHealthStatusLabel, ServiceHealthStatus, } from '../../../../../common/service_health_status'; -import { useTheme } from '../../../../hooks/use_theme'; export function HealthBadge({ healthStatus }: { healthStatus: ServiceHealthStatus }) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return ( - + {getServiceHealthStatusLabel(healthStatus)} ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.test.tsx index 21d7bbf6d120..71d3f7aa271d 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.test.tsx @@ -5,15 +5,13 @@ * 2.0. */ -import { euiLightVars as lightTheme } from '@kbn/ui-theme'; -import { render } from '@testing-library/react'; import cytoscape from 'cytoscape'; import React, { ReactNode } from 'react'; import { MemoryRouter } from 'react-router-dom'; -import { ThemeContext } from 'styled-components'; import { MockApmPluginContextWrapper } from '../../../context/apm_plugin/mock_apm_plugin_context'; import { Controls } from './controls'; import { CytoscapeContext } from './cytoscape'; +import { renderWithTheme } from '../../../utils/test_helpers'; const cy = cytoscape({ elements: [{ classes: 'primary', data: { id: 'test node' } }], @@ -27,11 +25,8 @@ function Wrapper({ children }: { children?: ReactNode }) { '/service-map?rangeFrom=now-15m&rangeTo=now&environment=ENVIRONMENT_ALL&kuery=', ]} > - - {children} - + {children} - s ); } @@ -39,7 +34,7 @@ function Wrapper({ children }: { children?: ReactNode }) { describe('Controls', () => { describe('with a primary node', () => { it('links to the full map', async () => { - const result = render(, { wrapper: Wrapper }); + const result = renderWithTheme(, { wrapper: Wrapper }); const { findByTestId } = result; const button = await findByTestId('viewFullMapButton'); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.tsx index ac15281d6121..e3a293a279e2 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/controls.tsx @@ -5,12 +5,11 @@ * 2.0. */ -import { EuiButtonIcon, EuiPanel, EuiToolTip } from '@elastic/eui'; +import { EuiButtonIcon, EuiPanel, EuiToolTip, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useContext, useEffect, useState } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; -import { useTheme } from '../../../hooks/use_theme'; import { getLegacyApmHref } from '../../shared/links/apm/apm_link'; import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { APMQueryParams } from '../../shared/links/url_helpers'; @@ -18,24 +17,24 @@ import { CytoscapeContext } from './cytoscape'; import { getAnimationOptions, getNodeHeight } from './cytoscape_options'; import { useAnyOfApmParams } from '../../../hooks/use_apm_params'; -const ControlsContainer = euiStyled('div')` - left: ${({ theme }) => theme.eui.euiSize}; +const ControlsContainer = styled('div')` + left: ${({ theme }) => theme.euiTheme.size.base}; position: absolute; - top: ${({ theme }) => theme.eui.euiSizeS}; + top: ${({ theme }) => theme.euiTheme.size.s}; z-index: 1; /* The element containing the cytoscape canvas has z-index = 0. */ `; -const Button = euiStyled(EuiButtonIcon)` +const Button = styled(EuiButtonIcon)` display: block; - margin: ${({ theme }) => theme.eui.euiSizeXS}; + margin: ${({ theme }) => theme.euiTheme.size.xs}; `; -const ZoomInButton = euiStyled(Button)` - margin-bottom: ${({ theme }) => theme.eui.euiSizeS}; +const ZoomInButton = styled(Button)` + margin-bottom: ${({ theme }) => theme.euiTheme.size.s}; `; -const Panel = euiStyled(EuiPanel)` - margin-bottom: ${({ theme }) => theme.eui.euiSizeS}; +const Panel = styled(EuiPanel)` + margin-bottom: ${({ theme }) => theme.euiTheme.size.s}; `; const steps = 5; @@ -97,7 +96,7 @@ function useDebugDownloadUrl(cy?: cytoscape.Core) { export function Controls() { const { core } = useApmPluginContext(); const { basePath } = core.http; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const cy = useContext(CytoscapeContext); const { urlParams } = useLegacyUrlParams(); @@ -110,7 +109,7 @@ export function Controls() { ); const [zoom, setZoom] = useState((cy && cy.zoom()) || 1); - const duration = parseInt(theme.eui.euiAnimSpeedFast, 10); + const duration = euiTheme.animation.fast ? parseInt(euiTheme.animation.fast, 10) : 0; const downloadUrl = useDebugDownloadUrl(cy); const viewFullMapUrl = getLegacyApmHref({ basePath, @@ -140,9 +139,9 @@ export function Controls() { if (cy) { const eles = cy.nodes(); cy.animate({ - ...getAnimationOptions(theme), + ...getAnimationOptions(euiTheme), center: { eles }, - fit: { eles, padding: getNodeHeight(theme) }, + fit: { eles, padding: getNodeHeight(euiTheme) }, }); } } diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape.tsx index 8535c483529a..eacd67e6dabe 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape.tsx @@ -17,7 +17,7 @@ import React, { useRef, useState, } from 'react'; -import { useTheme } from '../../../hooks/use_theme'; +import { useEuiTheme } from '@elastic/eui'; import { useTraceExplorerEnabledSetting } from '../../../hooks/use_trace_explorer_enabled_setting'; import { getCytoscapeOptions } from './cytoscape_options'; import { useCytoscapeEventHandlers } from './use_cytoscape_event_handlers'; @@ -57,13 +57,13 @@ function useCytoscape(options: cytoscape.CytoscapeOptions) { } function CytoscapeComponent({ children, elements, height, serviceName, style }: CytoscapeProps) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const isTraceExplorerEnabled = useTraceExplorerEnabledSetting(); const [ref, cy] = useCytoscape({ - ...getCytoscapeOptions(theme, isTraceExplorerEnabled), + ...getCytoscapeOptions(euiTheme, isTraceExplorerEnabled), elements, }); - useCytoscapeEventHandlers({ cy, serviceName, theme }); + useCytoscapeEventHandlers({ cy, serviceName, euiTheme }); // Add items from the elements prop to the cytoscape collection and remove // items that no longer are in the list, then trigger an event to notify diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape_options.ts b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape_options.ts index af0befbc0616..fa6fdbce3c76 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape_options.ts +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/cytoscape_options.ts @@ -7,7 +7,7 @@ import cytoscape from 'cytoscape'; import { CSSProperties } from 'react'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; +import type { EuiThemeComputed } from '@elastic/eui'; import { ServiceAnomalyStats } from '../../../../common/anomaly_detection'; import { SERVICE_NAME, SPAN_DESTINATION_SERVICE_RESOURCE } from '../../../../common/es_fields/apm'; import { @@ -26,21 +26,21 @@ function getServiceAnomalyStats(el: cytoscape.NodeSingular) { } function getBorderColorFn( - theme: EuiTheme + euiTheme: EuiThemeComputed ): cytoscape.Css.MapperFunction { return (el: cytoscape.NodeSingular) => { const hasAnomalyDetectionJob = el.data('serviceAnomalyStats') !== undefined; const anomalyStats = getServiceAnomalyStats(el); if (hasAnomalyDetectionJob) { return getServiceHealthStatusColor( - theme, + euiTheme, anomalyStats?.healthStatus ?? ServiceHealthStatus.unknown ); } if (el.hasClass('primary') || el.selected()) { - return theme.eui.euiColorPrimary; + return euiTheme.colors.primary; } - return theme.eui.euiColorMediumShade; + return euiTheme.colors.mediumShade; }; } @@ -79,10 +79,10 @@ function getBorderWidth(el: cytoscape.NodeSingular) { // @ts-expect-error `documentMode` is not recognized as a valid property of `document`. const isIE11 = !!window.MSInputMethodContext && !!document.documentMode; -export const getAnimationOptions = (theme: EuiTheme): cytoscape.AnimationOptions => ({ - duration: parseInt(theme.eui.euiAnimSpeedNormal, 10), +export const getAnimationOptions = (euiTheme: EuiThemeComputed): cytoscape.AnimationOptions => ({ + duration: euiTheme.animation.normal ? parseInt(euiTheme.animation.normal, 10) : 0, // @ts-expect-error The cubic-bezier options here are not recognized by the cytoscape types - easing: theme.eui.euiAnimSlightBounce, + easing: euiTheme.animation.bounce, }); const zIndexNode = 200; @@ -90,14 +90,18 @@ const zIndexEdge = 100; const zIndexEdgeHighlight = 110; const zIndexEdgeHover = 120; -export const getNodeHeight = (theme: EuiTheme): number => parseInt(theme.eui.euiSizeXXL, 10); +export const getNodeHeight = (euiTheme: EuiThemeComputed): number => + parseInt(euiTheme.size.xxl, 10); function isService(el: cytoscape.NodeSingular) { return el.data(SERVICE_NAME) !== undefined; } -const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.Stylesheet[] => { - const lineColor = theme.eui.euiColorMediumShade; +const getStyle = ( + euiTheme: EuiThemeComputed, + isTraceExplorerEnabled: boolean +): cytoscape.Stylesheet[] => { + const lineColor = euiTheme.colors.mediumShade; return [ { selector: 'core', @@ -107,46 +111,46 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S { selector: 'node', style: { - 'background-color': theme.eui.euiColorGhost, + 'background-color': euiTheme.colors.backgroundBasePlain, // The DefinitelyTyped definitions don't specify that a function can be // used here. 'background-image': (el: cytoscape.NodeSingular) => iconForNode(el), 'background-height': (el: cytoscape.NodeSingular) => (isService(el) ? '60%' : '40%'), 'background-width': (el: cytoscape.NodeSingular) => (isService(el) ? '60%' : '40%'), - 'border-color': getBorderColorFn(theme), + 'border-color': getBorderColorFn(euiTheme), 'border-style': getBorderStyle, 'border-width': getBorderWidth, color: (el: cytoscape.NodeSingular) => el.hasClass('primary') || el.selected() - ? theme.eui.euiColorPrimaryText - : theme.eui.euiTextColor, + ? euiTheme.colors.textPrimary + : euiTheme.colors.textParagraph, // theme.euiFontFamily doesn't work here for some reason, so we're just // specifying a subset of the fonts for the label text. 'font-family': 'Inter UI, Segoe UI, Helvetica, Arial, sans-serif', - 'font-size': theme.eui.euiFontSizeS, + 'font-size': euiTheme.size.s, ghost: 'yes', 'ghost-offset-x': 0, 'ghost-offset-y': 2, 'ghost-opacity': 0.15, - height: getNodeHeight(theme), + height: getNodeHeight(euiTheme), label: (el: cytoscape.NodeSingular) => isService(el) ? el.data(SERVICE_NAME) : el.data('label') || el.data(SPAN_DESTINATION_SERVICE_RESOURCE), - 'min-zoomed-font-size': parseInt(theme.eui.euiSizeS, 10), + 'min-zoomed-font-size': parseInt(euiTheme.size.s, 10), 'overlay-opacity': 0, shape: (el: cytoscape.NodeSingular) => isService(el) ? (isIE11 ? 'rectangle' : 'ellipse') : 'diamond', - 'text-background-color': theme.eui.euiColorPrimary, + 'text-background-color': euiTheme.colors.primary, 'text-background-opacity': (el: cytoscape.NodeSingular) => el.hasClass('primary') || el.selected() ? 0.1 : 0, - 'text-background-padding': theme.eui.euiSizeXS, + 'text-background-padding': euiTheme.size.xs, 'text-background-shape': 'roundrectangle', - 'text-margin-y': parseInt(theme.eui.euiSizeS, 10), + 'text-margin-y': parseInt(euiTheme.size.s, 10), 'text-max-width': '200px', 'text-valign': 'bottom', 'text-wrap': 'ellipsis', - width: theme.eui.euiSizeXXL, + width: euiTheme.size.xxl, 'z-index': zIndexNode, }, }, @@ -162,7 +166,7 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S // fairly new. // // @ts-expect-error - 'target-distance-from-node': isIE11 ? undefined : theme.eui.euiSizeXS, + 'target-distance-from-node': isIE11 ? undefined : euiTheme.size.xs, width: 1, 'source-arrow-shape': 'none', 'z-index': zIndexEdge, @@ -175,8 +179,8 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S 'source-arrow-color': lineColor, 'target-arrow-shape': isIE11 ? 'none' : 'triangle', // @ts-expect-error - 'source-distance-from-node': isIE11 ? undefined : parseInt(theme.eui.euiSizeXS, 10), - 'target-distance-from-node': isIE11 ? undefined : parseInt(theme.eui.euiSizeXS, 10), + 'source-distance-from-node': isIE11 ? undefined : parseInt(euiTheme.size.xs, 10), + 'target-distance-from-node': isIE11 ? undefined : parseInt(euiTheme.size.xs, 10), }, }, { @@ -190,9 +194,9 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S style: { width: 4, 'z-index': zIndexEdgeHover, - 'line-color': theme.eui.euiColorDarkShade, - 'source-arrow-color': theme.eui.euiColorDarkShade, - 'target-arrow-color': theme.eui.euiColorDarkShade, + 'line-color': euiTheme.colors.darkShade, + 'source-arrow-color': euiTheme.colors.darkShade, + 'target-arrow-color': euiTheme.colors.darkShade, }, }, ...(isTraceExplorerEnabled @@ -202,9 +206,9 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S style: { width: 4, 'z-index': zIndexEdgeHover, - 'line-color': theme.eui.euiColorDarkShade, - 'source-arrow-color': theme.eui.euiColorDarkShade, - 'target-arrow-color': theme.eui.euiColorDarkShade, + 'line-color': euiTheme.colors.darkShade, + 'source-arrow-color': euiTheme.colors.darkShade, + 'target-arrow-color': euiTheme.colors.darkShade, }, }, ] @@ -219,9 +223,9 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S selector: 'edge.highlight', style: { width: 4, - 'line-color': theme.eui.euiColorPrimary, - 'source-arrow-color': theme.eui.euiColorPrimary, - 'target-arrow-color': theme.eui.euiColorPrimary, + 'line-color': euiTheme.colors.primary, + 'source-arrow-color': euiTheme.colors.primary, + 'target-arrow-color': euiTheme.colors.primary, 'z-index': zIndexEdgeHighlight, }, }, @@ -230,32 +234,35 @@ const getStyle = (theme: EuiTheme, isTraceExplorerEnabled: boolean): cytoscape.S // The CSS styles for the div containing the cytoscape element. Makes a // background grid of dots. -export const getCytoscapeDivStyle = (theme: EuiTheme, status: FETCH_STATUS): CSSProperties => ({ +export const getCytoscapeDivStyle = ( + euiTheme: EuiThemeComputed, + status: FETCH_STATUS +): CSSProperties => ({ background: `linear-gradient( 90deg, - ${theme.eui.euiPageBackgroundColor} - calc(${theme.eui.euiSizeL} - calc(${theme.eui.euiSizeXS} / 2)), + ${euiTheme.colors.backgroundBasePlain} + calc(${euiTheme.size.l} - calc(${euiTheme.size.xs} / 2)), transparent 1% ) center, linear-gradient( - ${theme.eui.euiPageBackgroundColor} - calc(${theme.eui.euiSizeL} - calc(${theme.eui.euiSizeXS} / 2)), + ${euiTheme.colors.backgroundBasePlain} + calc(${euiTheme.size.l} - calc(${euiTheme.size.xs} / 2)), transparent 1% ) center, -${theme.eui.euiColorLightShade}`, - backgroundSize: `${theme.eui.euiSizeL} ${theme.eui.euiSizeL}`, +${euiTheme.colors.lightShade}`, + backgroundSize: `${euiTheme.size.l} ${euiTheme.size.l}`, cursor: `${status === FETCH_STATUS.LOADING ? 'wait' : 'grab'}`, marginTop: 0, }); export const getCytoscapeOptions = ( - theme: EuiTheme, + euiTheme: EuiThemeComputed, isTraceExplorerEnabled: boolean ): cytoscape.CytoscapeOptions => ({ boxSelectionEnabled: false, maxZoom: 3, minZoom: 0.2, - style: getStyle(theme, isTraceExplorerEnabled), + style: getStyle(euiTheme, isTraceExplorerEnabled), }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.tsx index 7d419baecc9e..9de1e5486141 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.tsx @@ -6,26 +6,22 @@ */ import React, { useContext, useEffect, useState } from 'react'; -import { EuiCallOut, EuiLink } from '@elastic/eui'; +import { EuiCallOut, EuiLink, useEuiTheme } from '@elastic/eui'; +import styled from '@emotion/styled'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; import { CytoscapeContext } from './cytoscape'; -import { useTheme } from '../../../hooks/use_theme'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; -const EmptyBannerContainer = euiStyled.div` - margin: ${({ theme }) => theme.eui.euiSizeS}; +const EmptyBannerContainer = styled.div` + margin: ${({ theme }) => theme.euiTheme.size.s}; /* Add some extra margin so it displays to the right of the controls. */ - left: calc( - ${({ theme }) => theme.eui.euiSizeXXL} + - ${({ theme }) => theme.eui.euiSizeS} - ); + left: calc(${({ theme }) => theme.euiTheme.size.xxl} + ${({ theme }) => theme.euiTheme.size.s}); position: absolute; z-index: 1; `; export function EmptyBanner() { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const cy = useContext(CytoscapeContext); const [nodeCount, setNodeCount] = useState(0); const { docLinks } = useApmPluginContext().core; @@ -51,7 +47,7 @@ export function EmptyBanner() { // Since we're absolutely positioned, we need to get the full width and // subtract the space for controls and margins. - const width = cy.width() - parseInt(theme.eui.euiSizeXXL, 10) - parseInt(theme.eui.euiSizeL, 10); + const width = cy.width() - parseInt(euiTheme.size.xxl, 10) - parseInt(euiTheme.size.l, 10); return ( diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/index.tsx index 113be5407c07..7d6bcbe69cfa 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/index.tsx @@ -6,14 +6,13 @@ */ import { usePerformanceContext } from '@kbn/ebt-tools'; -import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, EuiPanel } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, EuiPanel, useEuiTheme } from '@elastic/eui'; import React, { ReactNode } from 'react'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { isActivePlatinumLicense } from '../../../../common/license_check'; import { invalidLicenseMessage, SERVICE_MAP_TIMEOUT_ERROR } from '../../../../common/service_map'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { useLicenseContext } from '../../../context/license/use_license_context'; -import { useTheme } from '../../../hooks/use_theme'; import { LicensePrompt } from '../../shared/license_prompt'; import { Controls } from './controls'; import { Cytoscape } from './cytoscape'; @@ -103,7 +102,7 @@ export function ServiceMap({ end: string; serviceGroupId?: string; }) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const license = useLicenseContext(); const serviceName = useServiceName(); const { config } = useApmPluginContext(); @@ -200,7 +199,7 @@ export function ServiceMap({ elements={data.elements} height={heightWithPadding} serviceName={serviceName} - style={getCytoscapeDivStyle(theme, status)} + style={getCytoscapeDivStyle(euiTheme, status)} > {serviceName && } diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/anomaly_detection.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/anomaly_detection.tsx index 307887148e3e..562093976177 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/anomaly_detection.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/anomaly_detection.tsx @@ -5,10 +5,18 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem, EuiHealth, EuiIconTip, EuiTitle } from '@elastic/eui'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiHealth, + EuiIconTip, + EuiTitle, + useEuiFontSize, + useEuiTheme, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { getSeverity, ServiceAnomalyStats } from '../../../../../common/anomaly_detection'; import { getServiceHealthStatus, @@ -16,32 +24,31 @@ import { } from '../../../../../common/service_health_status'; import { TRANSACTION_REQUEST } from '../../../../../common/transaction_types'; import { asDuration, asInteger } from '../../../../../common/utils/formatters'; -import { useTheme } from '../../../../hooks/use_theme'; import { MLSingleMetricLink } from '../../../shared/links/machine_learning_links/mlsingle_metric_link'; import { popoverWidth } from '../cytoscape_options'; -const HealthStatusTitle = euiStyled(EuiTitle)` +const HealthStatusTitle = styled(EuiTitle)` display: inline; text-transform: uppercase; `; -const VerticallyCentered = euiStyled.div` +const VerticallyCentered = styled.div` display: flex; align-items: center; `; -const SubduedText = euiStyled.span` - color: ${({ theme }) => theme.eui.euiTextSubduedColor}; +const SubduedText = styled.span` + color: ${({ theme }) => theme.euiTheme.colors.textSubdued}; `; -const EnableText = euiStyled.section` - color: ${({ theme }) => theme.eui.euiTextSubduedColor}; +const EnableText = styled.section` + color: ${({ theme }) => theme.euiTheme.colors.textSubdued}; line-height: 1.4; - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; + font-size: ${() => useEuiFontSize('s').fontSize}; width: ${popoverWidth}px; `; -export const ContentLine = euiStyled.section` +export const ContentLine = styled.section` line-height: 2; `; @@ -50,7 +57,7 @@ interface Props { serviceAnomalyStats: ServiceAnomalyStats | undefined; } export function AnomalyDetection({ serviceName, serviceAnomalyStats }: Props) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const anomalyScore = serviceAnomalyStats?.anomalyScore; const severity = getSeverity(anomalyScore); @@ -76,7 +83,7 @@ export function AnomalyDetection({ serviceName, serviceAnomalyStats }: Props) { - + {ANOMALY_DETECTION_SCORE_METRIC} diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/externals_list_contents.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/externals_list_contents.tsx index 523a4e1ea415..a81df94c3d6f 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/externals_list_contents.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/externals_list_contents.tsx @@ -12,7 +12,7 @@ import { EuiFlexItem, } from '@elastic/eui'; import React, { Fragment } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { NodeDataDefinition } from 'cytoscape'; import { ContentsProps } from '.'; import { @@ -22,7 +22,7 @@ import { } from '../../../../../common/es_fields/apm'; import { ExternalConnectionNode } from '../../../../../common/service_map'; -const ExternalResourcesList = euiStyled.section` +const ExternalResourcesList = styled.section` max-height: 360px; overflow: auto; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/index.tsx index a66f77909072..827ea59015f2 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/index.tsx @@ -13,6 +13,7 @@ import { EuiTitle, EuiToolTip, EuiIcon, + useEuiTheme, } from '@elastic/eui'; import cytoscape from 'cytoscape'; import React, { @@ -27,7 +28,6 @@ import React, { import { i18n } from '@kbn/i18n'; import { SERVICE_NAME, SPAN_TYPE } from '../../../../../common/es_fields/apm'; import { Environment } from '../../../../../common/environment_rt'; -import { useTheme } from '../../../../hooks/use_theme'; import { useTraceExplorerEnabledSetting } from '../../../../hooks/use_trace_explorer_enabled_setting'; import { CytoscapeContext } from '../cytoscape'; import { getAnimationOptions, popoverWidth } from '../cytoscape_options'; @@ -83,7 +83,7 @@ interface PopoverProps { } export function Popover({ focusedServiceName, environment, kuery, start, end }: PopoverProps) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const cy = useContext(CytoscapeContext); const [selectedElement, setSelectedElement] = useState< cytoscape.NodeSingular | cytoscape.EdgeSingular | undefined @@ -164,12 +164,12 @@ export function Popover({ focusedServiceName, environment, kuery, start, end }: event.preventDefault(); if (cy) { cy.animate({ - ...getAnimationOptions(theme), + ...getAnimationOptions(euiTheme), center: { eles: cy.getElementById(selectedElementId) }, }); } }, - [cy, selectedElementId, theme] + [cy, selectedElementId, euiTheme] ); const isAlreadyFocused = focusedServiceName === selectedElementId; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/popover.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/popover.test.tsx index 2bafca33d06f..1e8f1f7b5d0e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/popover.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/popover.test.tsx @@ -6,16 +6,17 @@ */ import { composeStories } from '@storybook/testing-react'; -import { render, screen, waitFor } from '@testing-library/react'; +import { screen, waitFor } from '@testing-library/react'; import React from 'react'; import * as stories from './popover.stories'; +import { renderWithTheme } from '../../../../utils/test_helpers'; const { Dependency, ExternalsList, Resource, Service } = composeStories(stories); describe('Popover', () => { describe('with dependency data', () => { it('renders a dependency link', async () => { - render(); + renderWithTheme(); await waitFor(() => { expect(screen.getByRole('link', { name: /Dependency Details/i })).toBeInTheDocument(); @@ -25,7 +26,7 @@ describe('Popover', () => { describe('with externals list data', () => { it('renders an externals list', async () => { - render(); + renderWithTheme(); await waitFor(() => { expect(screen.getByText(/813-mam-392.mktoresp.com:443/)).toBeInTheDocument(); @@ -35,7 +36,7 @@ describe('Popover', () => { describe('with resource data', () => { it('renders with no buttons', async () => { - render(); + renderWithTheme(); await waitFor(() => { expect(screen.queryByRole('link')).not.toBeInTheDocument(); @@ -45,7 +46,7 @@ describe('Popover', () => { describe('with service data', () => { it('renders contents for a service', async () => { - render(); + renderWithTheme(); await waitFor(() => { expect(screen.getByRole('link', { name: /service details/i })).toBeInTheDocument(); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/resource_contents.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/resource_contents.tsx index fb1414382ed5..272a5e97dfd1 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/resource_contents.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/popover/resource_contents.tsx @@ -8,18 +8,18 @@ import { EuiDescriptionListDescription, EuiDescriptionListTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { NodeDataDefinition } from 'cytoscape'; import type { ContentsProps } from '.'; import { SPAN_SUBTYPE, SPAN_TYPE } from '../../../../../common/es_fields/apm'; -const ItemRow = euiStyled.div` +const ItemRow = styled.div` line-height: 2; `; -const SubduedDescriptionListTitle = euiStyled(EuiDescriptionListTitle)` +const SubduedDescriptionListTitle = styled(EuiDescriptionListTitle)` &&& { - color: ${({ theme }) => theme.eui.euiTextSubduedColor}; + color: ${({ theme }) => theme.euiTheme.colors.textSubdued}; } `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx index 31604d893401..c7df75312c79 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx @@ -8,24 +8,25 @@ import { renderHook } from '@testing-library/react'; import cytoscape from 'cytoscape'; import dagre from 'cytoscape-dagre'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; import { useUiTracker } from '@kbn/observability-shared-plugin/public'; import { useCytoscapeEventHandlers } from './use_cytoscape_event_handlers'; import lodash from 'lodash'; +import type { EuiThemeComputed } from '@elastic/eui'; jest.mock('@kbn/observability-shared-plugin/public'); cytoscape.use(dagre); -const theme = { - eui: { avatarSizing: { l: { size: 10 } } }, -} as unknown as EuiTheme; +const euiTheme = { + size: { avatarSizing: { l: { size: 10 } } }, + animation: { normal: '1s' }, +} as unknown as EuiThemeComputed; describe('useCytoscapeEventHandlers', () => { describe('when cytoscape is undefined', () => { it('runs', () => { expect(() => { - renderHook(() => useCytoscapeEventHandlers({ cy: undefined, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy: undefined, euiTheme })); }).not.toThrowError(); }); }); @@ -45,7 +46,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as cytoscape.CollectionReturnValue), } as unknown as cytoscape.CollectionReturnValue); - renderHook(() => useCytoscapeEventHandlers({ serviceName: 'test', cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ serviceName: 'test', cy, euiTheme })); cy.trigger('custom:data'); expect(cy.getElementById('test').hasClass('primary')).toEqual(true); @@ -66,7 +67,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as cytoscape.CollectionReturnValue), } as unknown as cytoscape.CollectionReturnValue); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.trigger('custom:data'); expect(run).toHaveBeenCalled(); @@ -85,7 +86,7 @@ describe('useCytoscapeEventHandlers', () => { const edge = cy.getElementById('test'); const style = jest.spyOn(edge, 'style'); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.trigger('layoutstop'); expect(style).toHaveBeenCalledWith('control-point-distances', [-0, 0]); @@ -97,7 +98,7 @@ describe('useCytoscapeEventHandlers', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); const node = cy.getElementById('test'); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); node.trigger('drag'); expect(node.data('hasBeenDragged')).toEqual(true); @@ -110,7 +111,7 @@ describe('useCytoscapeEventHandlers', () => { }); const node = cy.getElementById('test'); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); node.trigger('drag'); expect(node.data('hasBeenDragged')).toEqual(true); @@ -126,7 +127,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('dragfree'); expect(container.style.cursor).toEqual('pointer'); @@ -140,7 +141,7 @@ describe('useCytoscapeEventHandlers', () => { }); const node = cy.getElementById('test'); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); node.trigger('mouseover'); expect(node.hasClass('hover')).toEqual(true); @@ -153,7 +154,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('mouseover'); expect(container.style.cursor).toEqual('pointer'); @@ -168,7 +169,7 @@ describe('useCytoscapeEventHandlers', () => { return fn; }); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('mouseover'); expect(trackApmEvent).toHaveBeenCalledWith({ @@ -184,7 +185,7 @@ describe('useCytoscapeEventHandlers', () => { }); const node = cy.getElementById('test'); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); node.trigger('mouseout'); expect(node.hasClass('hover')).toEqual(false); @@ -197,7 +198,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('mouseout'); expect(container.style.cursor).toEqual('grab'); @@ -218,7 +219,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('mouseover'); expect(container.style.cursor).toEqual('default'); @@ -235,7 +236,7 @@ describe('useCytoscapeEventHandlers', () => { return fn; }); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('select'); expect(trackApmEvent).toHaveBeenCalledWith({ @@ -258,7 +259,7 @@ describe('useCytoscapeEventHandlers', () => { useCytoscapeEventHandlers({ serviceName: 'test', cy, - theme, + euiTheme, }) ); cy.getElementById('test').trigger('unselect'); @@ -275,7 +276,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.trigger('tapstart'); expect(container.style.cursor).toEqual('grabbing'); @@ -289,7 +290,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('tapstart'); expect(container.style.cursor).toEqual('grab'); @@ -305,7 +306,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.trigger('tapend'); expect(container.style.cursor).toEqual('grab'); @@ -319,7 +320,7 @@ describe('useCytoscapeEventHandlers', () => { } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('tapend'); expect(container.style.cursor).toEqual('pointer'); @@ -334,7 +335,7 @@ describe('useCytoscapeEventHandlers', () => { jest.spyOn(Storage.prototype, 'getItem').mockReturnValueOnce('true'); const debug = jest.spyOn(window.console, 'debug').mockReturnValueOnce(undefined); - renderHook(() => useCytoscapeEventHandlers({ cy, theme })); + renderHook(() => useCytoscapeEventHandlers({ cy, euiTheme })); cy.getElementById('test').trigger('select'); expect(debug).toHaveBeenCalled(); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.ts b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.ts index e40ee3e80eaa..fdf607c340fe 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.ts +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.ts @@ -8,8 +8,8 @@ import cytoscape from 'cytoscape'; import { debounce } from 'lodash'; import { useEffect } from 'react'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; import { useUiTracker } from '@kbn/observability-shared-plugin/public'; +import type { EuiThemeComputed } from '@elastic/eui'; import { getAnimationOptions, getNodeHeight } from './cytoscape_options'; /* @@ -39,13 +39,13 @@ function applyCubicBezierStyles(edges: cytoscape.EdgeCollection) { function getLayoutOptions({ fit = false, nodeHeight, - theme, + euiTheme, }: { fit?: boolean; nodeHeight: number; - theme: EuiTheme; + euiTheme: EuiThemeComputed; }): cytoscape.LayoutOptions { - const animationOptions = getAnimationOptions(theme); + const animationOptions = getAnimationOptions(euiTheme); return { animationDuration: animationOptions.duration, @@ -82,16 +82,16 @@ function resetConnectedEdgeStyle(cytoscapeInstance: cytoscape.Core, node?: cytos export function useCytoscapeEventHandlers({ cy, serviceName, - theme, + euiTheme, }: { cy?: cytoscape.Core; serviceName?: string; - theme: EuiTheme; + euiTheme: EuiThemeComputed; }) { const trackApmEvent = useUiTracker({ app: 'apm' }); useEffect(() => { - const nodeHeight = getNodeHeight(theme); + const nodeHeight = getNodeHeight(euiTheme); const dataHandler: cytoscape.EventHandler = (event, fit) => { if (serviceName) { @@ -111,7 +111,7 @@ export function useCytoscapeEventHandlers({ event.cy .elements('[!hasBeenDragged]') .difference('node:selected') - .layout(getLayoutOptions({ fit, nodeHeight, theme })) + .layout(getLayoutOptions({ fit, nodeHeight, euiTheme })) .run(); }; @@ -216,5 +216,5 @@ export function useCytoscapeEventHandlers({ cy.removeListener('tapend', undefined, tapendHandler); } }; - }, [cy, serviceName, trackApmEvent, theme]); + }, [cy, serviceName, trackApmEvent, euiTheme]); } diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview.test.tsx index 98cdc1e65c3a..71974cfbe75b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview.test.tsx @@ -6,10 +6,11 @@ */ import { composeStories } from '@storybook/testing-react'; -import { render, screen } from '@testing-library/react'; +import { screen } from '@testing-library/react'; import React from 'react'; import * as stories from './service_overview.stories'; import * as useAdHocApmDataView from '../../../hooks/use_adhoc_apm_data_view'; +import { renderWithTheme } from '../../../utils/test_helpers'; const { Example } = composeStories(stories); @@ -32,7 +33,7 @@ describe('ServiceOverview', () => { jest.clearAllMocks(); }); it('renders', async () => { - render(); + renderWithTheme(); expect(await screen.findByRole('heading', { name: 'Latency' })).toBeInTheDocument(); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx index f2682b2cce2d..bd9ade55866e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem, EuiSkeletonText } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiSkeletonText, useEuiTheme } from '@elastic/eui'; import { CloudProvider, getAgentIcon, getCloudProviderIcon } from '@kbn/custom-icons'; import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; @@ -35,7 +35,6 @@ import { } from '../../../../../common/es_fields/infra_metrics'; import { isPending } from '../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../hooks/use_theme'; import { APIReturnType } from '../../../../services/rest/create_call_apm_api'; import { KeyValueFilterList } from '../../../shared/key_value_filter_list'; import { pushNewItemToKueryBar } from '../../../shared/kuery_bar/utils'; @@ -89,7 +88,7 @@ const cloudDetailsKeys = [ ]; export function InstanceDetails({ serviceName, serviceNodeName, kuery }: Props) { - const theme = useTheme(); + const { colorMode } = useEuiTheme(); const history = useHistory(); const { data, status } = useInstanceDetailsFetcher({ @@ -132,6 +131,8 @@ export function InstanceDetails({ serviceName, serviceNodeName, kuery }: Props) }); const containerType = data.kubernetes?.pod?.name ? 'Kubernetes' : 'Docker'; + + const isDarkMode = colorMode === 'DARK'; return ( @@ -140,7 +141,7 @@ export function InstanceDetails({ serviceName, serviceNodeName, kuery }: Props) title={i18n.translate('xpack.apm.serviceOverview.instanceTable.details.serviceTitle', { defaultMessage: 'Service', })} - icon={getAgentIcon(data.agent?.name, theme.darkMode)} + icon={getAgentIcon(data.agent?.name, isDarkMode)} keyValueList={serviceDetailsKeyValuePairs} onClickFilter={addKueryBarFilter} /> diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/settings/agent_configurations/list/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/settings/agent_configurations/list/index.tsx index ae36d8b0434d..ddd74716ceef 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/settings/agent_configurations/list/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/settings/agent_configurations/list/index.tsx @@ -13,6 +13,7 @@ import { EuiHealth, EuiToolTip, RIGHT_ALIGNMENT, + useEuiTheme, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; @@ -22,7 +23,6 @@ import { APIReturnType } from '../../../../../services/rest/create_call_apm_api' import { getOptionLabel } from '../../../../../../common/agent_configuration/all_option'; import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; import { FETCH_STATUS } from '../../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../../hooks/use_theme'; import { LoadingStatePrompt } from '../../../../shared/loading_state_prompt'; import { ITableColumn, ManagedTable } from '../../../../shared/managed_table'; import { TimestampTooltip } from '../../../../shared/timestamp_tooltip'; @@ -40,7 +40,7 @@ interface Props { export function AgentConfigurationList({ status, configurations, refetch }: Props) { const { core } = useApmPluginContext(); const canSave = core.application.capabilities.apm['settings:save']; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const [configToBeDeleted, setConfigToBeDeleted] = useState(null); const apmRouter = useApmRouter(); @@ -110,7 +110,7 @@ export function AgentConfigurationList({ status, configurations, refetch }: Prop { field: 'applied_by_agent', align: 'center', - width: theme.eui.euiSizeXL, + width: euiTheme.size.xl, name: '', sortable: true, render: (_, { applied_by_agent: appliedByAgent }) => ( @@ -125,7 +125,7 @@ export function AgentConfigurationList({ status, configurations, refetch }: Prop }) } > - + ), }, @@ -172,12 +172,14 @@ export function AgentConfigurationList({ status, configurations, refetch }: Prop ...(canSave ? [ { - width: theme.eui.euiSizeXL, + width: euiTheme.size.xl, name: '', render: (config: Config) => ( ( setConfigToBeDeleted(config)} /> diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/delete_button.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/delete_button.tsx index 02ef3b97222b..564381f78a4a 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/delete_button.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/delete_button.tsx @@ -5,13 +5,12 @@ * 2.0. */ -import { EuiButtonEmpty } from '@elastic/eui'; +import { EuiButtonEmpty, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { NotificationsStart } from '@kbn/core/public'; import React, { useState } from 'react'; import { callApmApi } from '../../../../../services/rest/create_call_apm_api'; import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; -import { useTheme } from '../../../../../hooks/use_theme'; interface Props { onDelete: () => void; @@ -21,7 +20,7 @@ interface Props { export function DeleteButton({ onDelete, customLinkId }: Props) { const [isDeleting, setIsDeleting] = useState(false); const { toasts } = useApmPluginContext().core.notifications; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return ( {i18n.translate('xpack.apm.settings.customLink.delete', { defaultMessage: 'Delete', diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/storage_explorer/summary_stats.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/storage_explorer/summary_stats.tsx index bd76025d9606..30053480eb4e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/storage_explorer/summary_stats.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/storage_explorer/summary_stats.tsx @@ -204,7 +204,7 @@ function SummaryMetric({ css={css` ${xlFontSize} font-weight: ${euiTheme.font.weight.bold}; - color: ${euiTheme.colors.text}; + color: ${euiTheme.colors.textParagraph}; `} > {value} diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/top_traces_overview/trace_list.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/top_traces_overview/trace_list.tsx index 9b3d54d4efad..74461fcb7920 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/top_traces_overview/trace_list.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/top_traces_overview/trace_list.tsx @@ -5,12 +5,12 @@ * 2.0. */ -import { EuiIcon, EuiToolTip, RIGHT_ALIGNMENT } from '@elastic/eui'; +import { EuiIcon, EuiToolTip, RIGHT_ALIGNMENT, useEuiFontSize } from '@elastic/eui'; import { usePerformanceContext } from '@kbn/ebt-tools'; import { TypeOf } from '@kbn/typed-react-router-config'; import { i18n } from '@kbn/i18n'; import React, { useEffect, useMemo } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { ApmRoutes } from '../../routing/apm_route_config'; import { asMillisecondDuration, asTransactionRate } from '../../../../common/utils/formatters'; import { useApmParams } from '../../../hooks/use_apm_params'; @@ -25,8 +25,8 @@ import { ServiceLink } from '../../shared/links/apm/service_link'; import { TruncateWithTooltip } from '../../shared/truncate_with_tooltip'; import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; -const StyledTransactionLink = euiStyled(TransactionDetailLink)` - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; +const StyledTransactionLink = styled(TransactionDetailLink)` + font-size: ${() => useEuiFontSize('s').fontSize}; ${truncate('100%')}; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/index.tsx index 74b3975335c9..b1d1b0f8d745 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/index.tsx @@ -9,7 +9,7 @@ import { EuiEmptyPrompt } from '@elastic/eui'; import React from 'react'; import { i18n } from '@kbn/i18n'; import { Redirect } from 'react-router-dom'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { getRedirectToTransactionDetailPageUrl } from './get_redirect_to_transaction_detail_page_url'; @@ -18,7 +18,7 @@ import { useApmParams } from '../../../hooks/use_apm_params'; import { useTimeRange } from '../../../hooks/use_time_range'; import { ApmPluginStartDeps } from '../../../plugin'; -const CentralizedContainer = euiStyled.div` +const CentralizedContainer = styled.div` height: 100%; display: flex; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts index 66f346f36a5f..25acce3e5679 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts @@ -7,6 +7,7 @@ import { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; +import { useEuiTheme } from '@elastic/eui'; import { DEFAULT_PERCENTILE_THRESHOLD } from '../../../../../common/correlations/constants'; import { EVENT_OUTCOME } from '../../../../../common/es_fields/apm'; import { EventOutcome } from '../../../../../common/event_outcome'; @@ -16,11 +17,10 @@ import { useFetcher, FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { isErrorMessage } from '../../correlations/utils/is_error_message'; import { useFetchParams } from '../../correlations/use_fetch_params'; import { getTransactionDistributionChartData } from '../../correlations/get_transaction_distribution_chart_data'; -import { useTheme } from '../../../../hooks/use_theme'; export const useTransactionDistributionChartData = () => { const params = useFetchParams(); - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const { core: { notifications }, diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/accordion_waterfall.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/accordion_waterfall.tsx index a6520f964c7b..41d11ba74e2e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/accordion_waterfall.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/accordion_waterfall.tsx @@ -7,20 +7,19 @@ import { EuiAccordion, - EuiAccordionProps, EuiFlexGroup, EuiFlexItem, EuiIcon, EuiText, EuiToolTip, + useEuiTheme, } from '@elastic/eui'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; import { transparentize } from 'polished'; import React, { useEffect, useRef } from 'react'; import { WindowScroller, AutoSizer } from 'react-virtualized'; import { areEqual, ListChildComponentProps, VariableSizeList as List } from 'react-window'; +import { css } from '@emotion/react'; import { asBigNumber } from '../../../../../../../common/utils/formatters'; -import { useTheme } from '../../../../../../hooks/use_theme'; import { Margins } from '../../../../../shared/charts/timeline'; import { IWaterfallNodeFlatten, @@ -53,38 +52,6 @@ interface WaterfallNodeProps extends WaterfallProps { const ACCORDION_HEIGHT = 48; -const StyledAccordion = euiStyled(EuiAccordion).withConfig({ - shouldForwardProp: (prop) => !['marginLeftLevel', 'hasError'].includes(prop), -})< - EuiAccordionProps & { - marginLeftLevel: number; - hasError: boolean; - } ->` - - border-top: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - - ${(props) => { - const borderLeft = props.hasError - ? `2px solid ${props.theme.eui.euiColorDanger};` - : `1px solid ${props.theme.eui.euiColorLightShade};`; - return `.button_${props.id} { - width: 100%; - height: ${ACCORDION_HEIGHT}px; - margin-left: ${props.marginLeftLevel}px; - border-left: ${borderLeft} - &:hover { - background-color: ${props.theme.eui.euiColorLightestShade}; - } - }`; - }} - - .accordion__buttonContent { - width: 100%; - height: 100%; - } -`; - export function AccordionWaterfall({ maxLevelOpen, showCriticalPath, @@ -176,7 +143,7 @@ const VirtualRow = React.memo( ); const WaterfallNode = React.memo((props: WaterfallNodeProps) => { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const { duration, waterfallItemId, onClickWaterfallItem, timelineMargins, node } = props; const { criticalPathSegmentsById, getErrorCount, updateTreeNode, showCriticalPath } = useWaterfallContext(); @@ -190,7 +157,7 @@ const WaterfallNode = React.memo((props: WaterfallNodeProps) => { ?.filter((segment) => segment.self) .map((segment) => ({ id: segment.item.id, - color: theme.eui.euiColorAccent, + color: euiTheme.colors.accent, left: (segment.offset - node.item.offset - node.item.skew) / node.item.duration, width: segment.duration / node.item.duration, })); @@ -203,14 +170,14 @@ const WaterfallNode = React.memo((props: WaterfallNodeProps) => { onClickWaterfallItem(node.item, flyoutDetailTab); }; + const hasError = node.item.doc.event?.outcome === 'failure'; + return ( - @@ -243,6 +210,24 @@ const WaterfallNode = React.memo((props: WaterfallNodeProps) => { initialIsOpen forceState={node.expanded ? 'open' : 'closed'} onToggle={toggleAccordion} + css={css` + border-top: ${euiTheme.border.thin}; + .button_${node.item.id} { + width: 100%; + height: ${ACCORDION_HEIGHT}px; + margin-left: ${marginLeftLevel}px; + border-left: ${hasError + ? `${euiTheme.border.width.thick} solid ${euiTheme.colors.danger};` + : `${euiTheme.border.thin};`}; + &:hover { + background-color: ${euiTheme.colors.lightestShade}; + } + } + .accordion__buttonContent { + width: 100%; + height: 100%; + } + `} /> ); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/failure_badge.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/failure_badge.tsx index 29dd5ffde654..91f60fd9df84 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/failure_badge.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/failure_badge.tsx @@ -6,18 +6,17 @@ */ import React from 'react'; -import { EuiBadge, EuiToolTip } from '@elastic/eui'; +import { EuiBadge, EuiToolTip, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { EventOutcome } from '../../../../../../../typings/es_schemas/raw/fields/event_outcome'; -import { useTheme } from '../../../../../../hooks/use_theme'; -const ResetLineHeight = euiStyled.span` +const ResetLineHeight = styled.span` line-height: initial; `; export function FailureBadge({ outcome }: { outcome?: EventOutcome }) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); if (outcome !== 'failure') { return null; @@ -30,7 +29,11 @@ export function FailureBadge({ outcome }: { outcome?: EventOutcome }) { defaultMessage: 'event.outcome = failure', })} > - failure + + {i18n.translate('xpack.apm.failure_badge.label', { + defaultMessage: 'failure', + })} + ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/index.tsx index dbdc877742e1..56a5367a4cfa 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/index.tsx @@ -5,14 +5,13 @@ * 2.0. */ -import { EuiButtonEmpty, EuiCallOut } from '@elastic/eui'; +import { EuiButtonEmpty, EuiCallOut, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { History } from 'history'; import React, { useMemo, useState } from 'react'; import { useHistory } from 'react-router-dom'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { css } from '@emotion/react'; -import { useTheme } from '../../../../../../hooks/use_theme'; import { VerticalLinesContainer, TimelineAxisContainer, @@ -24,7 +23,7 @@ import { AccordionWaterfall } from './accordion_waterfall'; import { WaterfallFlyout } from './waterfall_flyout'; import { IWaterfall, IWaterfallItem } from './waterfall_helpers/waterfall_helpers'; -const Container = euiStyled.div` +const Container = styled.div` transition: 0.1s padding ease; position: relative; `; @@ -48,8 +47,8 @@ const toggleFlyout = ({ }); }; -const WaterfallItemsContainer = euiStyled.div` - border-bottom: 1px solid ${({ theme }) => theme.eui.euiColorMediumShade}; +const WaterfallItemsContainer = styled.div` + border-bottom: 1px solid ${({ theme }) => theme.euiTheme.colors.mediumShade}; `; interface Props { @@ -90,7 +89,7 @@ const MAX_DEPTH_OPEN_LIMIT = 2; export function Waterfall({ waterfall, waterfallItemId, showCriticalPath }: Props) { const history = useHistory(); - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const [isAccordionOpen, setIsAccordionOpen] = useState(true); const { duration } = waterfall; @@ -134,16 +133,16 @@ export function Waterfall({ waterfall, waterfallItemId, showCriticalPath }: Prop display: flex; position: sticky; top: var(--euiFixedHeadersOffset, 0); - z-index: ${theme.eui.euiZLevel2}; - background-color: ${theme.eui.euiColorEmptyShade}; - border-bottom: 1px solid ${theme.eui.euiColorMediumShade}; + z-index: ${euiTheme.levels.content}; + background-color: ${euiTheme.colors.emptyShade}; + border-bottom: 1px solid ${euiTheme.colors.mediumShade}; `} > { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/responsive_flyout.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/responsive_flyout.tsx index 16a80ce09efd..3c3440b7833c 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/responsive_flyout.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/responsive_flyout.tsx @@ -5,10 +5,21 @@ * 2.0. */ -import { EuiFlyout } from '@elastic/eui'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import React from 'react'; +import { EuiFlyout, EuiFlyoutProps } from '@elastic/eui'; +import styled, { type StyledComponent } from '@emotion/styled'; -export const ResponsiveFlyout = euiStyled(EuiFlyout)` +// The return type of this component needs to be specified because the inferred +// return type depends on types that are not exported from EUI. You get a TS4023 +// error if the return type is not specified. +export const ResponsiveFlyout: StyledComponent = styled( + ({ + className, + ...flyoutProps + }: { + className?: string; + } & EuiFlyoutProps) => +)` width: 100%; @media (min-width: 800px) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/index.tsx index e4c9f0cf2816..f412df0b099b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/index.tsx @@ -21,7 +21,7 @@ import { EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { isEmpty } from 'lodash'; import React, { Fragment } from 'react'; @@ -80,10 +80,10 @@ function getSpanTypes(span: Span) { }; } -const ContainerWithMarginRight = euiStyled.div` +const ContainerWithMarginRight = styled.div` /* add margin to all direct descendants */ & > * { - margin-right: ${({ theme }) => theme.eui.euiSizeXS}; + margin-right: ${({ theme }) => theme.euiTheme.size.xs}; } `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/truncate_height_section.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/truncate_height_section.tsx index 6416b6f24cf6..214cc8841b2c 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/truncate_height_section.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/span_flyout/truncate_height_section.tsx @@ -8,10 +8,10 @@ import { EuiIcon, EuiLink } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { Fragment, ReactNode, useEffect, useRef, useState } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; -const ToggleButtonContainer = euiStyled.div` - margin-top: ${({ theme }) => theme.eui.euiSizeS} +const ToggleButtonContainer = styled.div` + margin-top: ${({ theme }) => theme.euiTheme.size.s} user-select: none; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/waterfall_item.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/waterfall_item.tsx index 11d0f9bba929..296c98705294 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/waterfall_item.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall/waterfall_item.tsx @@ -5,11 +5,10 @@ * 2.0. */ -import { EuiBadge, EuiIcon, EuiText, EuiTitle, EuiToolTip } from '@elastic/eui'; +import { EuiBadge, EuiIcon, EuiText, EuiTitle, EuiToolTip, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { ReactNode, useRef, useEffect, useState } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; -import { useTheme } from '../../../../../../hooks/use_theme'; +import styled from '@emotion/styled'; import { isMobileAgentName, isRumAgentName } from '../../../../../../../common/agent_name'; import { TRACE_ID, TRANSACTION_ID } from '../../../../../../../common/es_fields/apm'; import { asDuration } from '../../../../../../../common/utils/formatters'; @@ -37,68 +36,68 @@ interface IBarStyleProps { color: string; } -const Container = euiStyled.div` +const Container = styled.div` position: relative; display: block; user-select: none; - padding-top: ${({ theme }) => theme.eui.euiSizeS}; - padding-bottom: ${({ theme }) => theme.eui.euiSizeM}; + padding-top: ${({ theme }) => theme.euiTheme.size.s}; + padding-bottom: ${({ theme }) => theme.euiTheme.size.m}; margin-right: ${(props) => props.timelineMargins.right}px; margin-left: ${(props) => props.hasToggle ? props.timelineMargins.left - 30 // fix margin if there is a toggle - : props.timelineMargins.left}px ; + : props.timelineMargins.left}px; background-color: ${({ isSelected, theme }) => - isSelected ? theme.eui.euiColorLightestShade : 'initial'}; + isSelected ? theme.euiTheme.colors.lightestShade : 'initial'}; cursor: pointer; &:hover { - background-color: ${({ theme }) => theme.eui.euiColorLightestShade}; + background-color: ${({ theme }) => theme.euiTheme.colors.lightestShade}; } `; -const ItemBar = euiStyled.div` +const ItemBar = styled.div` box-sizing: border-box; position: relative; - height: ${({ theme }) => theme.eui.euiSize}; + height: ${({ theme }) => theme.euiTheme.size.base}; min-width: 2px; background-color: ${(props) => props.color}; `; -const ItemText = euiStyled.span` +const ItemText = styled.span` position: absolute; right: 0; display: flex; align-items: center; - height: ${({ theme }) => theme.eui.euiSizeL}; + height: ${({ theme }) => theme.euiTheme.size.l}; max-width: 100%; /* add margin to all direct descendants */ & > * { - margin-right: ${({ theme }) => theme.eui.euiSizeS}; + margin-right: ${({ theme }) => theme.euiTheme.size.s}; white-space: nowrap; } `; -const CriticalPathItemBar = euiStyled.div` +const CriticalPathItemBar = styled.div` box-sizing: border-box; position: relative; - height: ${({ theme }) => theme.eui.euiSizeS}; - top : ${({ theme }) => theme.eui.euiSizeS}; + height: ${({ theme }) => theme.euiTheme.size.s}; + top: ${({ theme }) => theme.euiTheme.size.s}; min-width: 2px; background-color: transparent; display: flex; flex-direction: row; `; -const CriticalPathItemSegment = euiStyled.div<{ +const CriticalPathItemSegment = styled.div<{ left: number; width: number; color: string; }>` box-sizing: border-box; position: absolute; - height: ${({ theme }) => theme.eui.euiSizeS}; + height: ${({ theme }) => theme.euiTheme.size.s}; left: ${(props) => props.left * 100}%; width: ${(props) => props.width * 100}%; min-width: 2px; @@ -311,7 +310,7 @@ function RelatedErrors({ errorCount: number; }) { const apmRouter = useApmRouter(); - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const { query } = useAnyOfApmParams( '/services/{serviceName}/transactions/view', '/mobile-services/{serviceName}/transactions/view', @@ -348,7 +347,7 @@ function RelatedErrors({
e.stopPropagation()}> {i18n.translate('xpack.apm.waterfall.errorCount', { diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx index 4a46d708bb82..e14f185e2f6f 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx @@ -6,9 +6,9 @@ */ import { composeStories } from '@storybook/testing-react'; -import { render, waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import React from 'react'; -import { disableConsoleWarning } from '../../../../../utils/test_helpers'; +import { disableConsoleWarning, renderWithTheme } from '../../../../../utils/test_helpers'; import * as stories from './waterfall_container.stories'; const { Example } = composeStories(stories); @@ -25,7 +25,7 @@ describe('WaterfallContainer', () => { }); it('expands and contracts the accordion', async () => { - const { getAllByRole } = render(); + const { getAllByRole } = renderWithTheme(); const buttons = await waitFor(() => getAllByRole('button')); const parentItem = buttons[1]; const childItem = buttons[2]; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_link/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_link/index.tsx index 74ad3ffbe3d1..d05085f0b823 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/transaction_link/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/transaction_link/index.tsx @@ -7,14 +7,15 @@ import { EuiEmptyPrompt } from '@elastic/eui'; import React from 'react'; +import { i18n } from '@kbn/i18n'; import { Redirect } from 'react-router-dom'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { getRedirectToTransactionDetailPageUrl } from '../trace_link/get_redirect_to_transaction_detail_page_url'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useTimeRange } from '../../../hooks/use_time_range'; -const CentralizedContainer = euiStyled.div` +const CentralizedContainer = styled.div` height: 100%; display: flex; `; @@ -67,7 +68,16 @@ export function TransactionLink() { return ( - Fetching transaction...

} /> + + {i18n.translate('xpack.apm.transactionLink.h2.fetchingTransactionLabel', { + defaultMessage: 'Fetching transaction...', + })} + + } + /> ); } diff --git a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/agent_instructions_accordion.tsx b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/agent_instructions_accordion.tsx index bd87c7b61631..4889f33b3f0d 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/agent_instructions_accordion.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/agent_instructions_accordion.tsx @@ -16,7 +16,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { ComponentType } from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { Markdown } from '@kbn/shared-ux-markdown'; import { AgentIcon } from '@kbn/custom-icons'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_policy_form/settings_form/form_row_setting.tsx b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_policy_form/settings_form/form_row_setting.tsx index 00e6c0265fdf..20d018e27362 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_policy_form/settings_form/form_row_setting.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_policy_form/settings_form/form_row_setting.tsx @@ -15,7 +15,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { CodeEditor } from '@kbn/code-editor'; import { FormRowOnChange } from '.'; import { SettingsRow } from '../typings'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/apm_header_action_menu/anomaly_detection_setup_link.tsx b/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/apm_header_action_menu/anomaly_detection_setup_link.tsx index 8d7091e17a4a..2441dd7893cd 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/apm_header_action_menu/anomaly_detection_setup_link.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/apm_header_action_menu/anomaly_detection_setup_link.tsx @@ -7,7 +7,7 @@ import { EuiLoadingSpinner } from '@elastic/eui'; import { IconType } from '@elastic/eui'; -import { EuiHeaderLink, EuiIcon, EuiToolTip } from '@elastic/eui'; +import { EuiHeaderLink, EuiIcon, EuiToolTip, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { AnomalyDetectionSetupState } from '../../../../../common/anomaly_detection/get_anomaly_detection_setup_state'; @@ -18,7 +18,6 @@ import { import { useAnomalyDetectionJobsContext } from '../../../../context/anomaly_detection_jobs/use_anomaly_detection_jobs_context'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useApmParams } from '../../../../hooks/use_apm_params'; -import { useTheme } from '../../../../hooks/use_theme'; import { getLegacyApmHref } from '../../../shared/links/apm/apm_link'; export function AnomalyDetectionSetupLink() { @@ -29,12 +28,12 @@ export function AnomalyDetectionSetupLink() { const { core } = useApmPluginContext(); const { basePath } = core.http; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const { anomalyDetectionSetupState } = useAnomalyDetectionJobsContext(); let tooltipText: string = ''; - let color: 'warning' | 'text' | 'success' | 'danger' = 'text'; + let color: 'warning' | 'text' | 'accentSecondary' | 'danger' = 'text'; let icon: IconType | undefined; if (anomalyDetectionSetupState === AnomalyDetectionSetupState.Failure) { @@ -51,7 +50,7 @@ export function AnomalyDetectionSetupLink() { tooltipText = getNoJobsMessage(anomalyDetectionSetupState, environment); icon = 'machineLearningApp'; } else if (anomalyDetectionSetupState === AnomalyDetectionSetupState.UpgradeableJobs) { - color = 'success'; + color = 'accentSecondary'; tooltipText = i18n.translate('xpack.apm.anomalyDetectionSetup.upgradeableJobsText', { defaultMessage: 'Updates available for existing anomaly detection jobs.', }); @@ -74,7 +73,7 @@ export function AnomalyDetectionSetupLink() { data-test-subj="apmAnomalyDetectionHeaderLink" > {pre} - {ANOMALY_DETECTION_LINK_LABEL} + {ANOMALY_DETECTION_LINK_LABEL} ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/index.tsx index 69ea154538d6..2b709e207747 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/routing/app_root/index.tsx @@ -7,7 +7,7 @@ import { PerformanceContextProvider } from '@kbn/ebt-tools'; import { APP_WRAPPER_CLASS } from '@kbn/core/public'; -import { KibanaContextProvider, useDarkMode } from '@kbn/kibana-react-plugin/public'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app'; import { Storage } from '@kbn/kibana-utils-plugin/public'; import { @@ -16,9 +16,7 @@ import { } from '@kbn/observability-shared-plugin/public'; import { Route } from '@kbn/shared-ux-router'; import { RouteRenderer, RouterProvider } from '@kbn/typed-react-router-config'; -import { euiDarkVars, euiLightVars } from '@kbn/ui-theme'; import React from 'react'; -import { DefaultTheme, ThemeProvider } from 'styled-components'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { KibanaEnvironmentContextProvider } from '../../../context/kibana_environment_context/kibana_environment_context'; import { AnomalyDetectionJobsContextProvider } from '../../../context/anomaly_detection_jobs/anomaly_detection_jobs_context'; @@ -84,11 +82,9 @@ export function ApmAppRoot({ - - - - - + + + @@ -128,19 +124,3 @@ function MountApmHeaderActionMenu() { ); } - -export function ApmThemeProvider({ children }: { children: React.ReactNode }) { - const darkMode = useDarkMode(false); - - return ( - ({ - ...outerTheme, - eui: darkMode ? euiDarkVars : euiLightVars, - darkMode, - })} - > - {children} - - ); -} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/breakdown_chart/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/breakdown_chart/index.tsx index 8103f729f375..e0ad710a14d9 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/breakdown_chart/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/breakdown_chart/index.tsx @@ -21,7 +21,7 @@ import { Tooltip, LegendValue, } from '@elastic/charts'; -import { EuiIcon } from '@elastic/eui'; +import { EuiIcon, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import moment from 'moment'; import React from 'react'; @@ -36,7 +36,6 @@ import { import { Coordinate, TimeSeries } from '../../../../../typings/timeseries'; import { useChartPointerEventContext } from '../../../../context/chart_pointer_event/use_chart_pointer_event_context'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../hooks/use_theme'; import { unit } from '../../../../utils/style'; import { ChartContainer } from '../chart_container'; import { isTimeseriesEmpty, onBrushEnd } from '../helper/helper'; @@ -74,7 +73,7 @@ export function BreakdownChart({ const { query: { rangeFrom, rangeTo }, } = useAnyOfApmParams('/services/{serviceName}', '/mobile-services/{serviceName}'); - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const { start, end } = useTimeRange({ rangeFrom, rangeTo }); const min = moment.utc(start).valueOf(); @@ -82,7 +81,7 @@ export function BreakdownChart({ const xFormatter = niceTimeFormatter([min, max]); - const annotationColor = theme.eui.euiColorSuccess; + const annotationColor = euiTheme.colors.accentSecondary; const isEmpty = isTimeseriesEmpty(timeseries); diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/duration_distribution_chart/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/duration_distribution_chart/index.tsx index 1a88bf8b48c0..65f22d78adf9 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/duration_distribution_chart/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/duration_distribution_chart/index.tsx @@ -25,7 +25,7 @@ import { TickFormatter, } from '@elastic/charts'; -import { euiPaletteColorBlind } from '@elastic/eui'; +import { euiPaletteColorBlind, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -37,7 +37,6 @@ import type { HistogramItem } from '../../../../../common/correlations/types'; import { DEFAULT_PERCENTILE_THRESHOLD } from '../../../../../common/correlations/constants'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../hooks/use_theme'; import { ChartContainer } from '../chart_container'; @@ -109,7 +108,7 @@ export function DurationDistributionChart({ eventType, }: DurationDistributionChartProps) { const chartThemes = useChartThemes(); - const euiTheme = useTheme(); + const { euiTheme } = useEuiTheme(); const markerPercentile = DEFAULT_PERCENTILE_THRESHOLD; const annotationsDataValues: LineAnnotationDatum[] = [ @@ -188,7 +187,7 @@ export function DurationDistributionChart({ }, tickLabel: { fontSize: 10, - fill: euiTheme.eui.euiColorMediumShade, + fill: euiTheme.colors.mediumShade, padding: 0, }, }, @@ -207,8 +206,8 @@ export function DurationDistributionChart({ id="rect_annotation_1" style={{ strokeWidth: 1, - stroke: euiTheme.eui.euiColorLightShade, - fill: euiTheme.eui.euiColorLightShade, + stroke: euiTheme.colors.lightShade, + fill: euiTheme.colors.lightShade, opacity: 0.9, }} hideTooltips={true} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_chart_anomaly_timeseries.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_chart_anomaly_timeseries.tsx index 56b61cb02d8b..74179489aceb 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_chart_anomaly_timeseries.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_chart_anomaly_timeseries.tsx @@ -7,11 +7,11 @@ import { i18n } from '@kbn/i18n'; import { rgba } from 'polished'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; import { getSeverity } from '@kbn/ml-anomaly-utils/get_severity'; import { ML_ANOMALY_SEVERITY } from '@kbn/ml-anomaly-utils/anomaly_severity'; import { ML_ANOMALY_THRESHOLD } from '@kbn/ml-anomaly-utils/anomaly_threshold'; import type { AreaSeriesStyle, RecursivePartial } from '@elastic/charts'; +import type { EuiThemeComputed } from '@elastic/eui'; import { getSeverityColor } from '../../../../../common/anomaly_detection'; import { ServiceAnomalyTimeseries } from '../../../../../common/anomaly_detection/service_anomaly_timeseries'; import { APMChartSpec } from '../../../../../typings/timeseries'; @@ -21,11 +21,11 @@ export const expectedBoundsTitle = i18n.translate('xpack.apm.comparison.expected }); export function getChartAnomalyTimeseries({ anomalyTimeseries, - theme, + euiTheme, anomalyTimeseriesColor, }: { anomalyTimeseries?: ServiceAnomalyTimeseries; - theme: EuiTheme; + euiTheme: EuiThemeComputed; anomalyTimeseriesColor?: string; }): | { @@ -48,7 +48,7 @@ export function getChartAnomalyTimeseries({ opacity: 0, }, }, - color: anomalyTimeseriesColor ?? rgba(theme.eui.euiColorVis1, 0.5), + color: anomalyTimeseriesColor ?? rgba(euiTheme.colors.vis.euiColorVis1, 0.5), yAccessors: ['y1'], y0Accessors: ['y0'], data: anomalyTimeseries.bounds, diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx index f12f367eab8e..8e0c24162f2a 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx @@ -6,13 +6,12 @@ */ import { TooltipInfo } from '@elastic/charts'; -import { EuiIcon } from '@elastic/eui'; +import { EuiIcon, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { APIReturnType } from '../../../../services/rest/create_call_apm_api'; import { getServiceNodeName } from '../../../../../common/service_nodes'; import { asTransactionRate, TimeFormatter } from '../../../../../common/utils/formatters'; -import { useTheme } from '../../../../hooks/use_theme'; type ServiceInstanceMainStatistics = APIReturnType<'GET /internal/apm/services/{serviceName}/service_overview_instances/main_statistics'>; @@ -92,7 +91,7 @@ function MultipleInstanceCustomTooltip({ latencyFormatter, values, }: TooltipInfo & { latencyFormatter: TimeFormatter }) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return ( <> @@ -127,10 +126,7 @@ function MultipleInstanceCustomTooltip({ >
-
+
{latencyLabel} {latencyFormatter(latency).formatted}
@@ -142,10 +138,7 @@ function MultipleInstanceCustomTooltip({ >
-
+
{throughputLabel} {asTransactionRate(throughput)}
@@ -166,7 +159,7 @@ function MultipleInstanceCustomTooltip({ */ export function CustomTooltip(props: TooltipInfo & { latencyFormatter: TimeFormatter }) { const { values } = props; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return (
@@ -175,7 +168,7 @@ export function CustomTooltip(props: TooltipInfo & { latencyFormatter: TimeForma ) : ( )} -
+
{clickToFilterDescription}
diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx index fec3fc4cfe2d..6e5ce28e8cd2 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx @@ -19,7 +19,7 @@ import { TooltipType, Tooltip, } from '@elastic/charts'; -import { EuiPanel, EuiTitle } from '@elastic/eui'; +import { EuiPanel, EuiTitle, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { useHistory } from 'react-router-dom'; @@ -28,7 +28,6 @@ import { usePreviousPeriodLabel } from '../../../../hooks/use_previous_period_te import { SERVICE_NODE_NAME } from '../../../../../common/es_fields/apm'; import { asTransactionRate, getDurationFormatter } from '../../../../../common/utils/formatters'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; -import { useTheme } from '../../../../hooks/use_theme'; import { APIReturnType } from '../../../../services/rest/create_call_apm_api'; import * as urlHelpers from '../../links/url_helpers'; import { ChartContainer } from '../chart_container'; @@ -54,7 +53,7 @@ export function InstancesLatencyDistributionChart({ const history = useHistory(); const hasData = items.length > 0; - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const chartThemes = useChartThemes(); const maxLatency = Math.max(...items.map((item) => item.latency ?? 0)); @@ -130,7 +129,7 @@ export function InstancesLatencyDistributionChart({ locale={i18n.getLocale()} /> @@ -156,13 +155,13 @@ export function InstancesLatencyDistributionChart({ xScaleType={ScaleType.Linear} yAccessors={[(item) => item.latency]} yScaleType={ScaleType.Linear} - color={theme.eui.euiColorMediumShade} + color={euiTheme.colors.mediumShade} bubbleSeriesStyle={{ point: { shape: 'square', radius: 4, - fill: theme.eui.euiColorLightestShade, - stroke: theme.eui.euiColorMediumShade, + fill: euiTheme.colors.lightestShade, + stroke: euiTheme.colors.mediumShade, strokeWidth: 2, }, }} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/spark_plot/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/spark_plot/index.tsx index 84e2e6cb056d..b18fd70d0d2c 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/spark_plot/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/spark_plot/index.tsx @@ -16,12 +16,11 @@ import { Settings, Tooltip, } from '@elastic/charts'; -import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiLoadingChart } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiLoadingChart, useEuiTheme } from '@elastic/eui'; import React from 'react'; import { useChartThemes } from '@kbn/observability-shared-plugin/public'; import { i18n } from '@kbn/i18n'; import { Coordinate } from '../../../../../typings/timeseries'; -import { useTheme } from '../../../../hooks/use_theme'; import { unit } from '../../../../utils/style'; import { getComparisonChartTheme } from '../../time_comparison/get_comparison_chart_theme'; @@ -93,7 +92,7 @@ export function SparkPlotItem({ comparisonSeries?: Coordinate[]; comparisonSeriesColor?: string; }) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const defaultChartThemes = useChartThemes(); const comparisonChartTheme = getComparisonChartTheme(); const hasComparisonSeries = !!comparisonSeries?.length; @@ -110,7 +109,7 @@ export function SparkPlotItem({ }; const chartSize = { - height: theme.eui.euiSizeL, + height: euiTheme.size.l, width: compact ? unit * 4 : unit * 5, }; @@ -201,7 +200,7 @@ export function SparkPlotItem({ justifyContent: 'center', }} > - +
); } diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/__snapshots__/timeline.test.tsx.snap b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/__snapshots__/timeline.test.tsx.snap index 2630a6c7862c..09b48cc47b30 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/__snapshots__/timeline.test.tsx.snap +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/__snapshots__/timeline.test.tsx.snap @@ -1,11 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Timeline TimelineAxisContainer should render with data 1`] = ` -.c0 { - position: absolute; - bottom: 0; -} -
+
- .c0 { - display: -webkit-box; - display: -webkit-flex; - display: -ms-flexbox; - display: flex; - -webkit-align-items: center; - -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; - font-size: 14px; - color: #69707d; - cursor: pointer; - opacity: 1; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.c1 { - width: 11px; - height: 11px; - margin-right: 0; - background: #98a2b3; - border-radius: 100%; -} - - +
+
+
- .c0 { - display: -webkit-box; - display: -webkit-flex; - display: -ms-flexbox; - display: flex; - -webkit-align-items: center; - -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; - font-size: 14px; - color: #69707d; - cursor: pointer; - opacity: 1; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.c1 { - width: 11px; - height: 11px; - margin-right: 0; - background: #98a2b3; - border-radius: 100%; -} - - +
+
+
- .c0 { - display: -webkit-box; - display: -webkit-flex; - display: -ms-flexbox; - display: flex; - -webkit-align-items: center; - -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; - font-size: 14px; - color: #69707d; - cursor: pointer; - opacity: 1; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.c1 { - width: 11px; - height: 11px; - margin-right: 0; - background: #98a2b3; - border-radius: 100%; -} - - +
+
@@ -287,70 +210,70 @@ exports[`Timeline VerticalLinesContainer should render with data 1`] = ` transform="translate(0 100)" > ` +const Container = styled.div` display: flex; align-items: center; - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; - color: ${({ theme }) => theme.eui.euiColorDarkShade}; + font-size: ${() => useEuiFontSize('s').fontSize}; + color: ${({ theme }) => theme.euiTheme.colors.darkShade}; cursor: ${(props) => (props.clickable ? 'pointer' : 'initial')}; opacity: ${(props) => (props.disabled ? 0.4 : 1)}; user-select: none; @@ -38,7 +38,7 @@ interface IndicatorProps { const radius = 11; -export const Indicator = euiStyled.span` +export const Indicator = styled.span` width: ${radius}px; height: ${radius}px; margin-right: ${(props) => (props.withMargin ? `${radius / 2}px` : 0)}; @@ -68,8 +68,8 @@ export function Legend({ indicator, ...rest }: Props) { - const theme = useTheme(); - const indicatorColor = color || theme.eui.euiColorVis1; + const { euiTheme } = useEuiTheme(); + const indicatorColor = color || euiTheme.colors.vis.euiColorVis1; return ( - + `; exports[`Marker renders error marker 1`] = ` - - + `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/agent_marker.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/agent_marker.tsx index 37ddfbda58c3..1ee668fb5765 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/agent_marker.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/agent_marker.tsx @@ -5,22 +5,21 @@ * 2.0. */ -import { EuiToolTip } from '@elastic/eui'; +import { EuiToolTip, useEuiTheme } from '@elastic/eui'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { asDuration } from '../../../../../../common/utils/formatters'; -import { useTheme } from '../../../../../hooks/use_theme'; import { AgentMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/marks/get_agent_marks'; import { Legend } from '../legend'; -const NameContainer = euiStyled.div` - border-bottom: 1px solid ${({ theme }) => theme.eui.euiColorMediumShade}; - padding-bottom: ${({ theme }) => theme.eui.euiSizeS}; +const NameContainer = styled.div` + border-bottom: 1px solid ${({ theme }) => theme.euiTheme.colors.mediumShade}; + padding-bottom: ${({ theme }) => theme.euiTheme.size.s}; `; -const TimeContainer = euiStyled.div` - color: ${({ theme }) => theme.eui.euiColorMediumShade}; - padding-top: ${({ theme }) => theme.eui.euiSizeS}; +const TimeContainer = styled.div` + color: ${({ theme }) => theme.euiTheme.colors.mediumShade}; + padding-top: ${({ theme }) => theme.euiTheme.size.s}; `; interface Props { @@ -28,7 +27,7 @@ interface Props { } export function AgentMarker({ mark }: Props) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return ( <> @@ -42,7 +41,7 @@ export function AgentMarker({ mark }: Props) {
} > - + ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.tsx index faff0a073fe6..14b2a277c393 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.tsx @@ -5,13 +5,12 @@ * 2.0. */ -import { EuiPopover, EuiText } from '@elastic/eui'; +import { EuiPopover, EuiText, useEuiTheme } from '@elastic/eui'; import React, { useState } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { TRACE_ID, TRANSACTION_ID } from '../../../../../../common/es_fields/apm'; import { asDuration } from '../../../../../../common/utils/formatters'; import { useLegacyUrlParams } from '../../../../../context/url_params_context/use_url_params'; -import { useTheme } from '../../../../../hooks/use_theme'; import { ErrorMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/marks/get_error_marks'; import { ErrorDetailLink } from '../../../links/apm/error_detail_link'; import { Legend, Shape } from '../legend'; @@ -20,21 +19,21 @@ interface Props { mark: ErrorMark; } -const Popover = euiStyled.div` +const Popover = styled.div` max-width: 280px; `; -const TimeLegend = euiStyled(Legend)` - margin-bottom: ${({ theme }) => theme.eui.euiSize}; +const TimeLegend = styled(Legend)` + margin-bottom: ${({ theme }) => theme.euiTheme.size.base}; `; -const ErrorLink = euiStyled(ErrorDetailLink)` +const ErrorLink = styled(ErrorDetailLink)` display: block; - margin: ${({ theme }) => `${theme.eui.euiSizeS} 0 ${theme.eui.euiSizeS} 0`}; + margin: ${({ theme }) => `${theme.euiTheme.size.s} 0 ${theme.euiTheme.size.s} 0`}; overflow-wrap: break-word; `; -const Button = euiStyled(Legend)` +const Button = styled(Legend)` height: 20px; display: flex; align-items: flex-end; @@ -51,7 +50,7 @@ function truncateMessage(errorMessage?: string) { } export function ErrorMarker({ mark }: Props) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const { urlParams } = useLegacyUrlParams(); const [isPopoverOpen, showPopover] = useState(false); @@ -61,7 +60,7 @@ export function ErrorMarker({ mark }: Props) {
} + indicator={
@
} /> {label} @@ -76,7 +76,7 @@ export function TimelineAxis({ plotValues, marks = [], topTraceDuration }: Timel key="topTrace" x={topTraceDurationPosition} y={0} - fill={theme.eui.euiTextColor} + fill={euiTheme.colors.textParagraph} textAnchor="middle" > {tickFormatter(topTraceDuration).formatted} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/vertical_lines.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/vertical_lines.tsx index 96ab6a51e49f..1f2a929084be 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/vertical_lines.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/vertical_lines.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { useTheme } from '../../../../hooks/use_theme'; +import { useEuiTheme } from '@elastic/eui'; import { Mark } from '../../../app/transaction_details/waterfall_with_summary/waterfall_container/marks'; import { PlotValues } from './plot_utils'; @@ -21,7 +21,7 @@ export function VerticalLines({ topTraceDuration, plotValues, marks = [] }: Vert const markTimes = marks.filter((mark) => mark.verticalLine).map(({ offset }) => offset); - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); const tickPositions = tickValues.reduce((positions, tick) => { const position = xScale(tick); @@ -53,7 +53,7 @@ export function VerticalLines({ topTraceDuration, plotValues, marks = [] }: Vert x2={position} y1={0} y2="100%" - stroke={theme.eui.euiColorLightestShade} + stroke={euiTheme.colors.lightestShade} /> ))} {markPositions.map((position) => ( @@ -63,7 +63,7 @@ export function VerticalLines({ topTraceDuration, plotValues, marks = [] }: Vert x2={position} y1={0} y2="100%" - stroke={theme.eui.euiColorMediumShade} + stroke={euiTheme.colors.mediumShade} /> ))} {Number.isFinite(topTraceDurationPosition) && ( @@ -73,7 +73,7 @@ export function VerticalLines({ topTraceDuration, plotValues, marks = [] }: Vert x2={topTraceDurationPosition} y1={0} y2="100%" - stroke={theme.eui.euiColorMediumShade} + stroke={euiTheme.colors.mediumShade} /> )} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart.tsx index 7b90aeb3ee03..5f08befb46a3 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart.tsx @@ -25,7 +25,7 @@ import { Tooltip, SettingsSpec, } from '@elastic/charts'; -import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiSpacer } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiSpacer, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { ReactElement } from 'react'; import { useHistory } from 'react-router-dom'; @@ -33,7 +33,6 @@ import { useChartThemes } from '@kbn/observability-shared-plugin/public'; import { isExpectedBoundsComparison } from '../time_comparison/get_comparison_options'; import { useChartPointerEventContext } from '../../../context/chart_pointer_event/use_chart_pointer_event_context'; -import { useTheme } from '../../../hooks/use_theme'; import { unit } from '../../../utils/style'; import { ChartContainer } from './chart_container'; import { @@ -75,11 +74,11 @@ export function TimeseriesChart({ }: TimeseriesChartProps) { const history = useHistory(); const { chartRef, updatePointerEvent } = useChartPointerEventContext(); - const theme = useTheme(); + const { euiTheme, colorMode } = useEuiTheme(); const chartThemes = useChartThemes(); const anomalyChartTimeseries = getChartAnomalyTimeseries({ anomalyTimeseries, - theme, + euiTheme, anomalyTimeseriesColor: anomalyTimeseries?.color, }); const isEmpty = isTimeseriesEmpty(timeseries); @@ -115,12 +114,13 @@ export function TimeseriesChart({ } : undefined; - const endZoneColor = theme.darkMode ? theme.eui.euiColorLightShade : theme.eui.euiColorDarkShade; + const isDarkMode = colorMode === 'DARK'; + const endZoneColor = isDarkMode ? euiTheme.colors.lightShade : euiTheme.colors.darkShade; const endZoneRectAnnotationStyle: Partial = { stroke: endZoneColor, fill: endZoneColor, strokeWidth: 0, - opacity: theme.darkMode ? 0.6 : 0.2, + opacity: isDarkMode ? 0.6 : 0.2, }; function getChartType(type: string) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart_with_context.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart_with_context.tsx index e9ec46610fe2..5f08e7375788 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart_with_context.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeseries_chart_with_context.tsx @@ -13,7 +13,7 @@ import { YDomainRange, } from '@elastic/charts'; import React from 'react'; -import { EuiIcon } from '@elastic/eui'; +import { EuiIcon, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { asAbsoluteDateTime } from '../../../../common/utils/formatters'; import { useAnnotationsContext } from '../../../context/annotations/use_annotations_context'; @@ -25,7 +25,6 @@ import { FETCH_STATUS } from '../../../hooks/use_fetcher'; import { unit } from '../../../utils/style'; import { getTimeZone } from './helper/timezone'; import { TimeseriesChart } from './timeseries_chart'; -import { useTheme } from '../../../hooks/use_theme'; interface AnomalyTimeseries extends ServiceAnomalyTimeseries { color?: string; @@ -69,8 +68,8 @@ export function TimeseriesChartWithContext({ } = useAnyOfApmParams('/services', '/dependencies/*', '/services/{serviceName}'); const { core } = useApmPluginContext(); const timeZone = getTimeZone(core.uiSettings); - const theme = useTheme(); - const annotationColor = theme.eui.euiColorSuccess; + const { euiTheme } = useEuiTheme(); + const annotationColor = euiTheme.colors.accentSecondary; const { annotations } = useAnnotationsContext(); const timeseriesAnnotations = [ diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/transaction_charts/ml_header.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/transaction_charts/ml_header.tsx index 814dfd3d7798..e25803c98622 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/transaction_charts/ml_header.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/transaction_charts/ml_header.tsx @@ -9,7 +9,7 @@ import { EuiFlexItem, EuiIconTip, EuiText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; import { useAnyOfApmParams } from '../../../../hooks/use_apm_params'; import { MLSingleMetricLink } from '../../links/machine_learning_links/mlsingle_metric_link'; @@ -19,14 +19,14 @@ interface Props { mlJobId?: string; } -const ShiftedIconWrapper = euiStyled.span` +const ShiftedIconWrapper = styled.span` padding-right: 5px; position: relative; top: -1px; display: inline-block; `; -const ShiftedEuiText = euiStyled(EuiText)` +const ShiftedEuiText = styled(EuiText)` position: relative; top: 5px; `; @@ -45,7 +45,9 @@ export function MLHeader({ hasValidMlLicense, mlJobId }: Props) { const hasKuery = !isEmpty(kuery); const icon = hasKuery ? ( `${theme.eui.euiSizeS} ${theme.eui.euiSizeS} 0 ${theme.eui.euiSizeS}`}; + margin: ${({ theme }) => + `${theme.euiTheme.size.s} ${theme.euiTheme.size.s} 0 ${theme.euiTheme.size.s}`}; .descriptionList__title, .descriptionList__description { margin-top: 0; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/key_value_table/formatted_value.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/key_value_table/formatted_value.tsx index 1b1c5c3c59a7..a3baef9a802b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/key_value_table/formatted_value.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/key_value_table/formatted_value.tsx @@ -7,11 +7,11 @@ import { isBoolean, isNumber, isObject } from 'lodash'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; -const EmptyValue = euiStyled.span` - color: ${({ theme }) => theme.eui.euiColorMediumShade}; +const EmptyValue = styled.span` + color: ${({ theme }) => theme.euiTheme.colors.mediumShade}; text-align: left; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestion.js b/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestion.js index 841b74a37a40..625b19f92342 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestion.js +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestion.js @@ -7,72 +7,73 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; -import { EuiIcon } from '@elastic/eui'; +import styled from '@emotion/styled'; +import { EuiIcon, useEuiFontSize } from '@elastic/eui'; import { unit } from '../../../../utils/style'; import { tint } from 'polished'; function getIconColor(type, theme) { switch (type) { case 'field': - return theme.eui.euiColorVis7; + return theme.euiTheme.colors.vis.euiColorVis7; case 'value': - return theme.eui.euiColorVis0; + return theme.euiTheme.colors.vis.euiColorVis0; case 'operator': - return theme.eui.euiColorVis1; + return theme.euiTheme.colors.vis.euiColorVis1; case 'conjunction': - return theme.eui.euiColorVis3; + return theme.euiTheme.colors.vis.euiColorVis3; case 'recentSearch': - return theme.eui.euiColorMediumShade; + return theme.euiTheme.colors.mediumShade; } } -const Description = euiStyled.div` - color: ${({ theme }) => theme.eui.euiColorDarkShade}; +const Description = styled.div` + color: ${({ theme }) => theme.euiTheme.colors.darkShade}; p { display: inline; span { - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; - color: ${({ theme }) => theme.eui.euiColorFullShade}; - padding: 0 ${({ theme }) => theme.eui.euiSizeXS}; + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; + color: ${({ theme }) => theme.euiTheme.colors.fullShade}; + padding: 0 ${({ theme }) => theme.euiTheme.size.xs}; display: inline-block; } } `; -const ListItem = euiStyled.li` - font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; - height: ${({ theme }) => theme.eui.euiSizeXL}; +const ListItem = styled.li` + font-size: ${() => useEuiFontSize('xs').fontSize}; + height: ${({ theme }) => theme.euiTheme.size.xl}; align-items: center; display: flex; - background: ${({ selected, theme }) => (selected ? theme.eui.euiColorLightestShade : 'initial')}; + background: ${({ selected, theme }) => + selected ? theme.euiTheme.colors.lightestShade : 'initial'}; cursor: pointer; - border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + border-radius: ${({ theme }) => theme.euiTheme.border.radius.small}; ${Description} { p span { background: ${({ selected, theme }) => - selected ? theme.eui.euiColorEmptyShade : theme.eui.euiColorLightestShade}; + selected ? theme.euiTheme.colors.emptyShade : theme.euiTheme.colors.lightestShade}; } } `; -const Icon = euiStyled.div` - flex: 0 0 ${({ theme }) => theme.eui.euiSizeXL}; +const Icon = styled.div` + flex: 0 0 ${({ theme }) => theme.euiTheme.size.xl}; background: ${({ type, theme }) => tint(0.9, getIconColor(type, theme))}; color: ${({ type, theme }) => getIconColor(type, theme)}; width: 100%; height: 100%; text-align: center; - line-height: ${({ theme }) => theme.eui.euiSizeXL}; + line-height: ${({ theme }) => theme.euiTheme.size.xl}; `; -const TextValue = euiStyled.div` +const TextValue = styled.div` flex: 0 0 ${unit * 16}px; - color: ${({ theme }) => theme.eui.euiColorDarkestShade}; - padding: 0 ${({ theme }) => theme.eui.euiSizeS}; + color: ${({ theme }) => theme.euiTheme.colors.darkestShade}; + padding: 0 ${({ theme }) => theme.euiTheme.size.s}; `; function getEuiIconType(type) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestions.js b/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestions.js index 1cedd94a86be..3c07b8f608ba 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestions.js +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/kuery_bar/typeahead/suggestions.js @@ -9,18 +9,22 @@ import { isEmpty } from 'lodash'; import { tint } from 'polished'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { unit } from '../../../../utils/style'; import Suggestion from './suggestion'; -const List = euiStyled.ul` +const List = styled.ul` width: 100%; - border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; - box-shadow: 0 ${({ theme }) => - `${theme.eui.euiSizeXS} ${theme.eui.euiSizeXL} ${tint(0.9, theme.eui.euiColorFullShade)}`}; + border: 1px solid ${({ theme }) => theme.euiTheme.colors.lightShade}; + border-radius: ${({ theme }) => theme.euiTheme.border.radius.small}; + box-shadow: 0 + ${({ theme }) => + `${theme.euiTheme.size.xs} ${theme.euiTheme.size.xl} ${tint( + 0.9, + theme.euiTheme.colors.fullShade + )}`}; position: absolute; - background: ${({ theme }) => theme.eui.euiColorEmptyShade}; + background: ${({ theme }) => theme.euiTheme.colors.emptyShade}; z-index: 10; left: 0; max-height: ${unit * 20}px; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_link/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_link/index.tsx index 4baf94c6f055..b6d7d1789fac 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_link/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_link/index.tsx @@ -8,7 +8,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiLink, EuiText } from '@elastic/eui'; import { AgentIcon } from '@kbn/custom-icons'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { TypeOf } from '@kbn/typed-react-router-config'; import React from 'react'; import { isMobileAgentName } from '../../../../../../common/agent_name'; @@ -21,7 +21,9 @@ import { PopoverTooltip } from '../../../popover_tooltip'; import { TruncateWithTooltip } from '../../../truncate_with_tooltip'; import { MaxGroupsMessage, OTHER_SERVICE_NAME } from '../max_groups_message'; -const StyledLink = euiStyled(EuiLink)`${truncate('100%')};`; +const StyledLink = styled(EuiLink)` + ${truncate('100%')}; +`; function formatString(value?: string | null) { return value || NOT_AVAILABLE_LABEL; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/links/dependency_link.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/links/dependency_link.tsx index 696f987ea2b6..d202c1cb770b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/links/dependency_link.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/links/dependency_link.tsx @@ -8,19 +8,21 @@ import { EuiFlexGroup, EuiFlexItem, EuiLink } from '@elastic/eui'; import { TypeOf } from '@kbn/typed-react-router-config'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useApmRouter } from '../../../hooks/use_apm_router'; import { truncate } from '../../../utils/style'; import { ApmRoutes } from '../../routing/apm_route_config'; import { SpanIcon } from '../span_icon'; -const StyledLink = euiStyled(EuiLink)`${truncate('100%')};`; +const StyledLink = styled(EuiLink)` + ${truncate('100%')}; +`; interface Props { query: TypeOf['query']; subtype?: string; type?: string; - onClick?: React.ComponentProps['onClick']; + onClick?: React.MouseEventHandler; } export function DependencyLink({ query, subtype, type, onClick }: Props) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/overview_table_container/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/overview_table_container/index.tsx index c77c3e7cc7a9..8c2f62f7998b 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/overview_table_container/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/overview_table_container/index.tsx @@ -6,7 +6,7 @@ */ import React, { ReactNode } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useBreakpoints } from '../../../hooks/use_breakpoints'; /** @@ -24,7 +24,7 @@ const tableHeight = 282; * * Hide the empty message when we don't yet have any items and are still not initiated. */ -const OverviewTableContainerDiv = euiStyled.div<{ +const OverviewTableContainerDiv = styled.div<{ fixedHeight?: boolean; isEmptyAndNotInitiated: boolean; shouldUseMobileLayout: boolean; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/service_icons/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/service_icons/index.tsx index e6780927e755..a7c4b2311508 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/service_icons/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/service_icons/index.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { CloudProvider, @@ -14,7 +14,6 @@ import { getServerlessIcon, } from '@kbn/custom-icons'; import React, { ReactChild, useState } from 'react'; -import { useTheme } from '../../../hooks/use_theme'; import { ContainerType } from '../../../../common/service_metadata'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { CloudDetails } from './cloud_details'; @@ -81,7 +80,8 @@ export interface PopoverItem { export function ServiceIcons({ start, end, serviceName, environment }: Props) { const [selectedIconPopover, setSelectedIconPopover] = useState(); - const theme = useTheme(); + const { colorMode } = useEuiTheme(); + const isDarkMode = colorMode === 'DARK'; const { data: icons, status: iconsFetchStatus } = useFetcher( (callApmApi) => { @@ -122,7 +122,7 @@ export function ServiceIcons({ start, end, serviceName, environment }: Props) { { key: 'service', icon: { - type: getAgentIcon(icons?.agentName, theme.darkMode) || 'node', + type: getAgentIcon(icons?.agentName, isDarkMode) || 'node', }, isVisible: !!icons?.agentName, title: i18n.translate('xpack.apm.serviceIcons.service', { @@ -133,7 +133,7 @@ export function ServiceIcons({ start, end, serviceName, environment }: Props) { { key: 'opentelemetry', icon: { - type: getAgentIcon('opentelemetry', theme.darkMode), + type: getAgentIcon('opentelemetry', isDarkMode), }, isVisible: !!icons?.agentName && isOpenTelemetryAgentName(icons.agentName), title: i18n.translate('xpack.apm.serviceIcons.opentelemetry', { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/cause_stacktrace.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/cause_stacktrace.tsx index 549509dc96f5..d36a5bf42216 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/cause_stacktrace.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/cause_stacktrace.tsx @@ -8,29 +8,29 @@ import { EuiAccordion, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { Stacktrace } from '.'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; -const Accordion = euiStyled(EuiAccordion)` - border-top: ${({ theme }) => theme.eui.euiBorderThin}; - margin-top: ${({ theme }) => theme.eui.euiSizeS}; +const Accordion = styled(EuiAccordion)` + border-top: ${({ theme }) => theme.euiTheme.border.thin}; + margin-top: ${({ theme }) => theme.euiTheme.size.s}; `; -const CausedByContainer = euiStyled('h5')` - padding: ${({ theme }) => theme.eui.euiSizeS} 0; +const CausedByContainer = styled('h5')` + padding: ${({ theme }) => theme.euiTheme.size.s} 0; `; -const CausedByHeading = euiStyled('span')` - color: ${({ theme }) => theme.eui.euiTextSubduedColor}; +const CausedByHeading = styled('span')` + color: ${({ theme }) => theme.euiTheme.colors.textSubdued}; display: block; - font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; - font-weight: ${({ theme }) => theme.eui.euiFontWeightBold}; + font-size: ${({ theme }) => theme.euiTheme.size.xs}; + font-weight: ${({ theme }) => theme.euiTheme.font.weight.bold}; text-transform: uppercase; `; -const FramesContainer = euiStyled('div')` - padding-left: ${({ theme }) => theme.eui.euiSizeM}; +const FramesContainer = styled('div')` + padding-left: ${({ theme }) => theme.euiTheme.size.m}; `; function CausedBy({ message }: { message: string }) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/context.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/context.tsx index 3abd57773365..a79b5529d2cd 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/context.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/context.tsx @@ -13,66 +13,66 @@ import javascript from 'react-syntax-highlighter/dist/cjs/languages/hljs/javascr import python from 'react-syntax-highlighter/dist/cjs/languages/hljs/python'; import ruby from 'react-syntax-highlighter/dist/cjs/languages/hljs/ruby'; import xcode from 'react-syntax-highlighter/dist/cjs/styles/hljs/xcode'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { StackframeWithLineContext } from '../../../../typings/es_schemas/raw/fields/stackframe'; SyntaxHighlighter.registerLanguage('javascript', javascript); SyntaxHighlighter.registerLanguage('python', python); SyntaxHighlighter.registerLanguage('ruby', ruby); -const ContextContainer = euiStyled.div` +const ContextContainer = styled.div` position: relative; - border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + border-radius: ${({ theme }) => theme.euiTheme.border.radius.small}; `; const LINE_HEIGHT = 18; -const LineHighlight = euiStyled.div<{ lineNumber: number }>` +const LineHighlight = styled.div<{ lineNumber: number }>` position: absolute; width: 100%; height: ${LINE_HEIGHT}px; top: ${(props) => props.lineNumber * LINE_HEIGHT}px; pointer-events: none; - background-color: ${({ theme }) => tint(0.9, theme.eui.euiColorWarning)}; + background-color: ${({ theme }) => tint(0.9, theme.euiTheme.colors.warning)}; `; -const LineNumberContainer = euiStyled.div<{ isLibraryFrame: boolean }>` +const LineNumberContainer = styled.div<{ isLibraryFrame: boolean }>` position: absolute; top: 0; left: 0; - border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + border-radius: ${({ theme }) => theme.euiTheme.border.radius.small}; background: ${({ isLibraryFrame, theme }) => - isLibraryFrame ? theme.eui.euiColorEmptyShade : theme.eui.euiColorLightestShade}; + isLibraryFrame ? theme.euiTheme.colors.emptyShade : theme.euiTheme.colors.lightestShade}; `; -const LineNumber = euiStyled.div<{ highlight: boolean }>` +const LineNumber = styled.div<{ highlight: boolean }>` position: relative; min-width: 42px; - padding-left: ${({ theme }) => theme.eui.euiSizeS}; - padding-right: ${({ theme }) => theme.eui.euiSizeXS}; - color: ${({ theme }) => theme.eui.euiColorMediumShade}; + padding-left: ${({ theme }) => theme.euiTheme.size.s}; + padding-right: ${({ theme }) => theme.euiTheme.size.xs}; + color: ${({ theme }) => theme.euiTheme.colors.mediumShade}; line-height: ${LINE_HEIGHT}px; text-align: right; - border-right: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; + border-right: ${({ theme }) => theme.euiTheme.border.thin}; background-color: ${({ highlight, theme }) => - highlight ? tint(0.9, theme.eui.euiColorWarning) : null}; + highlight ? tint(0.9, theme.euiTheme.colors.warning) : null}; &:last-of-type { - border-radius: 0 0 0 ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + border-radius: 0 0 0 ${({ theme }) => theme.euiTheme.border.radius.small}; } `; -const LineContainer = euiStyled.div` +const LineContainer = styled.div` overflow: auto; margin: 0 0 0 42px; padding: 0; - background-color: ${({ theme }) => theme.eui.euiColorEmptyShade}; + background-color: ${({ theme }) => theme.euiTheme.colors.emptyShade}; &:last-of-type { - border-radius: 0 0 ${({ theme }) => theme.eui.euiBorderRadiusSmall} 0; + border-radius: 0 0 ${({ theme }) => theme.euiTheme.border.radius.small} 0; } `; -const Line = euiStyled.pre` +const Line = styled.pre` // Override all styles margin: 0; color: inherit; @@ -84,7 +84,7 @@ const Line = euiStyled.pre` line-height: ${LINE_HEIGHT}px; `; -const Code = euiStyled.code` +const Code = styled.code` position: relative; padding: 0; margin: 0; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/frame_heading.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/frame_heading.tsx index 00aac84b8373..734ac85cf40e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/frame_heading.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/frame_heading.tsx @@ -6,7 +6,8 @@ */ import React, { ComponentType } from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; +import { useEuiFontSize } from '@elastic/eui'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { CSharpFrameHeadingRenderer, @@ -18,21 +19,21 @@ import { PhpFrameHeadingRenderer, } from './frame_heading_renderers'; -const FileDetails = euiStyled.div` - color: ${({ theme }) => theme.eui.euiColorDarkShade}; +const FileDetails = styled.div` + color: ${({ theme }) => theme.euiTheme.colors.darkShade}; line-height: 1.5; /* matches the line-hight of the accordion container button */ padding: 2px 0; - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; + font-size: ${({ theme }) => useEuiFontSize('s').fontSize}; `; -const LibraryFrameFileDetail = euiStyled.span` - color: ${({ theme }) => theme.eui.euiColorDarkShade}; +const LibraryFrameFileDetail = styled.span` + color: ${({ theme }) => theme.euiTheme.colors.darkShade}; word-break: break-word; `; -const AppFrameFileDetail = euiStyled.span` - color: ${({ theme }) => theme.eui.euiColorFullShade}; +const AppFrameFileDetail = styled.span` + color: ${({ theme }) => theme.euiTheme.colors.fullShade}; word-break: break-word; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/library_stacktrace.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/library_stacktrace.tsx index 8c9bc4e5cdd4..b5fe38b6eb66 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/library_stacktrace.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/library_stacktrace.tsx @@ -8,12 +8,12 @@ import { EuiAccordion } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { Stackframe as StackframeComponent } from './stackframe'; -const LibraryStacktraceAccordion = euiStyled(EuiAccordion)` - margin: ${({ theme }) => theme.eui.euiSizeXS} 0; +const LibraryStacktraceAccordion = styled(EuiAccordion)` + margin: ${({ theme }) => theme.euiTheme.size.xs} 0; `; interface Props { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/stackframe.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/stackframe.tsx index 61692b3dbf96..1180b1c9ed05 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/stackframe.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/stackframe.tsx @@ -7,7 +7,7 @@ import { EuiAccordion } from '@elastic/eui'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { Stackframe as StackframeType, StackframeWithLineContext, @@ -16,18 +16,18 @@ import { Context } from './context'; import { FrameHeading } from './frame_heading'; import { Variables } from './variables'; -const ContextContainer = euiStyled.div<{ isLibraryFrame: boolean }>` +const ContextContainer = styled.div<{ isLibraryFrame: boolean }>` position: relative; - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; - border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; + font-size: ${({ theme }) => theme.euiTheme.size.s}; + border: 1px solid ${({ theme }) => theme.euiTheme.colors.lightShade}; + border-radius: ${({ theme }) => theme.euiTheme.border.radius.small}; background: ${({ isLibraryFrame, theme }) => - isLibraryFrame ? theme.eui.euiColorEmptyShade : theme.eui.euiColorLightestShade}; + isLibraryFrame ? theme.euiTheme.colors.emptyShade : theme.euiTheme.colors.lightestShade}; `; // Indent the non-context frames the same amount as the accordion control -const NoContextFrameHeadingWrapper = euiStyled.div` +const NoContextFrameHeadingWrapper = styled.div` margin-left: 28px; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/variables.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/variables.tsx index 5dc9a8a5073b..e59d6e9bc5c1 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/variables.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/stacktrace/variables.tsx @@ -8,16 +8,16 @@ import { EuiAccordion } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { KeyValueTable } from '../key_value_table'; import { flattenObject } from '../../../../common/utils/flatten_object'; -const VariablesContainer = euiStyled.div` - background: ${({ theme }) => theme.eui.euiColorEmptyShade}; - border-radius: 0 0 ${({ theme }) => - `${theme.eui.euiBorderRadiusSmall} ${theme.eui.euiBorderRadiusSmall}`}; - padding: ${({ theme }) => `${theme.eui.euiSizeS} ${theme.eui.euiSizeM}`}; +const VariablesContainer = styled.div` + background: ${({ theme }) => theme.euiTheme.colors.emptyShade}; + border-radius: 0 0 + ${({ theme }) => `${theme.euiTheme.border.radius.small} ${theme.euiTheme.border.radius.small}`}; + padding: ${({ theme }) => `${theme.euiTheme.size.s} ${theme.euiTheme.size.m}`}; `; interface Props { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap index f8799874408e..61921adf2741 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap @@ -24,9 +24,9 @@ exports[`StickyProperties should render entire component 1`] = ` + url.full - + } delay="regular" display="inlineBlock" @@ -43,9 +43,9 @@ exports[`StickyProperties should render entire component 1`] = ` display="inlineBlock" position="top" > - + https://www.elastic.co/test - + + http.request.method - + } delay="regular" display="inlineBlock" @@ -91,9 +91,9 @@ exports[`StickyProperties should render entire component 1`] = ` + error.exception.handled - + } delay="regular" display="inlineBlock" @@ -121,9 +121,9 @@ exports[`StickyProperties should render entire component 1`] = ` + user.id - + } delay="regular" display="inlineBlock" diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/index.tsx index f620c97984ca..024f05e493a2 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/index.tsx @@ -5,10 +5,10 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, useEuiFontSize } from '@elastic/eui'; import { EuiToolTip } from '@elastic/eui'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { truncate } from '../../../utils/style'; export interface IStickyProperty { @@ -19,14 +19,14 @@ export interface IStickyProperty { truncated?: boolean; } -const TooltipFieldName = euiStyled.span` - font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; +const TooltipFieldName = styled.span` + font-family: ${({ theme }) => theme.euiTheme.font.familyCode}; `; -const PropertyLabel = euiStyled.div` - margin-bottom: ${({ theme }) => theme.eui.euiSizeS}; - font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; - color: ${({ theme }) => theme.eui.euiColorMediumShade}; +const PropertyLabel = styled.div` + margin-bottom: ${({ theme }) => theme.euiTheme.size.s}; + font-size: ${() => useEuiFontSize('xs').fontSize}; + color: ${({ theme }) => theme.euiTheme.colors.mediumShade}; span { cursor: help; @@ -35,13 +35,13 @@ const PropertyLabel = euiStyled.div` PropertyLabel.displayName = 'PropertyLabel'; const propertyValueLineHeight = 1.2; -const PropertyValue = euiStyled.div` +const PropertyValue = styled.div` display: inline-block; line-height: ${propertyValueLineHeight}; `; PropertyValue.displayName = 'PropertyValue'; -const PropertyValueTruncated = euiStyled.span` +const PropertyValueTruncated = styled.span` display: inline-block; line-height: ${propertyValueLineHeight}; ${truncate('100%')}; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx index 02289485e12d..09effede911f 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx @@ -56,7 +56,7 @@ describe('StickyProperties', () => { const wrapper = shallow() .find('PropertyValue') - .dive() + .render() .text(); expect(wrapper).toEqual('1337'); diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/error_count_summary_item_badge.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/error_count_summary_item_badge.tsx index 9de373d2189e..2eb502feb99e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/error_count_summary_item_badge.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/error_count_summary_item_badge.tsx @@ -7,18 +7,17 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { EuiBadge } from '@elastic/eui'; -import { useTheme } from '../../../hooks/use_theme'; +import { EuiBadge, useEuiTheme } from '@elastic/eui'; interface Props { count: number; } export function ErrorCountSummaryItemBadge({ count }: Props) { - const theme = useTheme(); + const { euiTheme } = useEuiTheme(); return ( - + {i18n.translate('xpack.apm.transactionDetails.errorCount', { defaultMessage: '{errorCount, number} {errorCount, plural, one {Error} other {Errors}}', values: { errorCount: count }, diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/http_info_summary_item.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/http_info_summary_item.test.tsx index 6091a6ff8c73..2d5e1cfeb41e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/http_info_summary_item.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/http_info_summary_item.test.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { shallow, mount } from 'enzyme'; import { HttpInfoSummaryItem } from '.'; import * as exampleTransactions from '../__fixtures__/transactions'; -import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; +import { EuiThemeProvider } from '@elastic/eui'; describe('HttpInfoSummaryItem', () => { describe('render', () => { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/index.tsx index 7eee907d0526..5732c426e261 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/http_info_summary_item/index.tsx @@ -8,15 +8,15 @@ import { EuiBadge, EuiToolTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { truncate, unit } from '../../../../utils/style'; import { HttpStatusBadge } from '../http_status_badge'; -const HttpInfoBadge = euiStyled(EuiBadge)` - margin-right: ${({ theme }) => theme.eui.euiSizeXS}; +const HttpInfoBadge = styled(EuiBadge)` + margin-right: ${({ theme }) => theme.euiTheme.size.xs}; `; -const Url = euiStyled('span')` +const Url = styled('span')` display: inline-block; vertical-align: bottom; ${truncate(unit * 24)}; @@ -27,7 +27,7 @@ interface HttpInfoProps { url: string; } -const Span = euiStyled('span')` +const Span = styled('span')` white-space: nowrap; `; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/user_agent_summary_item.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/user_agent_summary_item.tsx index dcfaae3f9b25..9a2f3e041bf1 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/summary/user_agent_summary_item.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/summary/user_agent_summary_item.tsx @@ -6,15 +6,15 @@ */ import React from 'react'; -import { EuiToolTip } from '@elastic/eui'; +import { EuiToolTip, useEuiFontSize } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { UserAgent } from '../../../../typings/es_schemas/raw/fields/user_agent'; type UserAgentSummaryItemProps = UserAgent; -const Version = euiStyled('span')` - font-size: ${({ theme }) => theme.eui.euiFontSizeS}; +const Version = styled('span')` + font-size: ${() => useEuiFontSize('s').fontSize}; `; export function UserAgentSummaryItem({ name, version }: UserAgentSummaryItemProps) { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.test.tsx index a8caf4685020..9fffd11600c8 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.test.tsx @@ -8,7 +8,6 @@ import { render } from '@testing-library/react'; import React, { ReactNode } from 'react'; import { MemoryRouter } from 'react-router-dom'; -import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; import { expectTextsInDocument, expectTextsNotInDocument } from '../../../utils/test_helpers'; import { TimeComparison } from '.'; import * as urlHelpers from '../links/url_helpers'; @@ -24,6 +23,7 @@ import type { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plug import { merge } from 'lodash'; import type { ApmMlJob } from '../../../../common/anomaly_detection/apm_ml_job'; import { FETCH_STATUS } from '../../../hooks/use_fetcher'; +import { EuiThemeProvider } from '@elastic/eui'; const ML_AD_JOBS = { jobs: [ diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.tsx index 54894b3f536c..57e3fa94b5ba 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/time_comparison/index.tsx @@ -9,7 +9,7 @@ import { EuiCheckbox, EuiSelect } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useMemo } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { useUiTracker } from '@kbn/observability-shared-plugin/public'; import { useApmRouter } from '../../../hooks/use_apm_router'; import { useEnvironmentsContext } from '../../../context/environments_context/use_environments_context'; @@ -21,12 +21,12 @@ import { useTimeRange } from '../../../hooks/use_time_range'; import * as urlHelpers from '../links/url_helpers'; import { getComparisonOptions, TimeRangeComparisonEnum } from './get_comparison_options'; -const PrependContainer = euiStyled.div` +const PrependContainer = styled.div` display: flex; justify-content: center; align-items: center; - background-color: ${({ theme }) => theme.eui.euiFormInputGroupLabelBackground}; - padding: 0 ${({ theme }) => theme.eui.euiSizeM}; + background-color: ${({ theme }) => theme.euiTheme.colors.backgroundBaseFormsPrepend}; + padding: 0 ${({ theme }) => theme.euiTheme.size.m}; `; export function TimeComparison() { diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/transaction_type_select.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/transaction_type_select.tsx index 292aaaed816a..f6e2a1a52b53 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/transaction_type_select.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/transaction_type_select.tsx @@ -8,7 +8,7 @@ import { EuiSelect } from '@elastic/eui'; import React, { FormEvent, useCallback } from 'react'; import { useHistory } from 'react-router-dom'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { useApmServiceContext } from '../../context/apm_service/use_apm_service_context'; import { useBreakpoints } from '../../hooks/use_breakpoints'; import * as urlHelpers from './links/url_helpers'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/truncate_with_tooltip/index.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/truncate_with_tooltip/index.tsx index 5e1c450e336d..02e04ed09803 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/truncate_with_tooltip/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/truncate_with_tooltip/index.tsx @@ -7,12 +7,12 @@ import { EuiToolTip } from '@elastic/eui'; import React from 'react'; -import { euiStyled } from '@kbn/kibana-react-plugin/common'; +import styled from '@emotion/styled'; import { truncate } from '../../../utils/style'; const tooltipAnchorClassname = '_apm_truncate_tooltip_anchor_'; -const TooltipWrapper = euiStyled.div` +const TooltipWrapper = styled.div` width: 100%; .${tooltipAnchorClassname} { width: 100% !important; @@ -20,7 +20,7 @@ const TooltipWrapper = euiStyled.div` } `; -const ContentWrapper = euiStyled.div` +const ContentWrapper = styled.div` ${truncate('100%')} `; diff --git a/x-pack/plugins/observability_solution/apm/public/embeddable/embeddable_context.tsx b/x-pack/plugins/observability_solution/apm/public/embeddable/embeddable_context.tsx index 43ccf990257b..8458a4c9d446 100644 --- a/x-pack/plugins/observability_solution/apm/public/embeddable/embeddable_context.tsx +++ b/x-pack/plugins/observability_solution/apm/public/embeddable/embeddable_context.tsx @@ -9,7 +9,6 @@ import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { KibanaThemeProvider } from '@kbn/react-kibana-context-theme'; import { ApmPluginContext, ApmPluginContextValue } from '../context/apm_plugin/apm_plugin_context'; import { createCallApmApi } from '../services/rest/create_call_apm_api'; -import { ApmThemeProvider } from '../components/routing/app_root'; import { ChartPointerEventContextProvider } from '../context/chart_pointer_event/chart_pointer_event_context'; import { EmbeddableDeps } from './types'; import { TimeRangeMetadataContextProvider } from '../context/time_range_metadata/time_range_metadata_context'; @@ -54,19 +53,17 @@ export function ApmEmbeddableContext({ - - - - {children} - - - + + + {children} + + diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_entity_centric_experience_setting.tsx b/x-pack/plugins/observability_solution/apm/public/hooks/use_entity_centric_experience_setting.tsx index 32e68c40788f..e5290bb25dbb 100644 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_entity_centric_experience_setting.tsx +++ b/x-pack/plugins/observability_solution/apm/public/hooks/use_entity_centric_experience_setting.tsx @@ -13,7 +13,7 @@ export function useEntityCentricExperienceSetting() { const isEntityCentricExperienceEnabled = core.uiSettings.get( entityCentricExperience, - true + false ); return { isEntityCentricExperienceEnabled }; diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_theme.tsx b/x-pack/plugins/observability_solution/apm/public/hooks/use_theme.tsx deleted file mode 100644 index 8c18ac38efc3..000000000000 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_theme.tsx +++ /dev/null @@ -1,15 +0,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 { useContext } from 'react'; -import { ThemeContext } from 'styled-components'; -import { EuiTheme } from '@kbn/kibana-react-plugin/common'; - -export function useTheme(): EuiTheme { - const theme = useContext(ThemeContext); - return theme; -} diff --git a/x-pack/plugins/observability_solution/apm/public/tutorial/config_agent/index.tsx b/x-pack/plugins/observability_solution/apm/public/tutorial/config_agent/index.tsx index cd10f07f2475..129f15a3355c 100644 --- a/x-pack/plugins/observability_solution/apm/public/tutorial/config_agent/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/tutorial/config_agent/index.tsx @@ -8,7 +8,7 @@ import { EuiLoadingSpinner } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { HttpStart } from '@kbn/core/public'; import React, { useEffect, useMemo, useState } from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { APIReturnType } from '../../services/rest/create_call_apm_api'; import { AgentConfigInstructions } from './agent_config_instructions'; import { getPolicyOptions, PolicyOption } from './get_policy_options'; diff --git a/x-pack/plugins/observability_solution/apm/public/tutorial/tutorial_fleet_instructions/index.tsx b/x-pack/plugins/observability_solution/apm/public/tutorial/tutorial_fleet_instructions/index.tsx index 8924999f4821..6796c6576ab0 100644 --- a/x-pack/plugins/observability_solution/apm/public/tutorial/tutorial_fleet_instructions/index.tsx +++ b/x-pack/plugins/observability_solution/apm/public/tutorial/tutorial_fleet_instructions/index.tsx @@ -18,7 +18,7 @@ import { import { i18n } from '@kbn/i18n'; import { HttpStart } from '@kbn/core/public'; import React, { useEffect, useState } from 'react'; -import styled from 'styled-components'; +import styled from '@emotion/styled'; import { APIReturnType } from '../../services/rest/create_call_apm_api'; interface Props { diff --git a/x-pack/plugins/observability_solution/apm/public/utils/test_helpers.tsx b/x-pack/plugins/observability_solution/apm/public/utils/test_helpers.tsx index 76a6b868300c..a5d6f6782908 100644 --- a/x-pack/plugins/observability_solution/apm/public/utils/test_helpers.tsx +++ b/x-pack/plugins/observability_solution/apm/public/utils/test_helpers.tsx @@ -18,8 +18,8 @@ import moment from 'moment'; import { Moment } from 'moment-timezone'; import React from 'react'; import { MemoryRouter } from 'react-router-dom'; -import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { EuiThemeProvider } from '@elastic/eui'; import { MockApmPluginContextWrapper } from '../context/apm_plugin/mock_apm_plugin_context'; import { UrlParamsProvider } from '../context/url_params_context/url_params_context'; @@ -112,17 +112,13 @@ export function expectTextsInDocument(output: any, texts: string[]) { }); } -export function renderWithTheme( - component: React.ReactNode, - params?: any, - { darkMode = false } = {} -) { - return render({component}, params); +export function renderWithTheme(component: React.ReactNode, params?: any) { + return render({component}, params); } -export function mountWithTheme(tree: React.ReactElement, { darkMode = false } = {}) { +export function mountWithTheme(tree: React.ReactElement) { function WrappingThemeProvider(props: any) { - return {props.children}; + return {props.children}; } return mount(tree, { diff --git a/x-pack/plugins/observability_solution/infra/emotion.d.ts b/x-pack/plugins/observability_solution/infra/emotion.d.ts deleted file mode 100644 index 213178080e53..000000000000 --- a/x-pack/plugins/observability_solution/infra/emotion.d.ts +++ /dev/null @@ -1,14 +0,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 '@emotion/react'; -import type { UseEuiTheme } from '@elastic/eui'; - -declare module '@emotion/react' { - // eslint-disable-next-line @typescript-eslint/no-empty-interface - export interface Theme extends UseEuiTheme {} -} diff --git a/x-pack/plugins/observability_solution/infra/public/alerting/log_threshold/components/alert_details_app_section/components/threhsold_chart/create_lens_definition.ts b/x-pack/plugins/observability_solution/infra/public/alerting/log_threshold/components/alert_details_app_section/components/threhsold_chart/create_lens_definition.ts index ab3bc5f72bbf..a6feb02a2bc6 100644 --- a/x-pack/plugins/observability_solution/infra/public/alerting/log_threshold/components/alert_details_app_section/components/threhsold_chart/create_lens_definition.ts +++ b/x-pack/plugins/observability_solution/infra/public/alerting/log_threshold/components/alert_details_app_section/components/threhsold_chart/create_lens_definition.ts @@ -78,7 +78,7 @@ function createBaseLensDefinition( yConfig: [ { forAccessor: '607b2253-ed20-4f0a-bf62-07a1f846cca4', - color: '#6092c0', + color: euiTheme.colors.vis.euiColorVis2, }, ], }, diff --git a/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/__snapshots__/alert_details_app_section.test.tsx.snap b/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/__snapshots__/alert_details_app_section.test.tsx.snap index af8a5b3d8e0a..0df66d4c3dca 100644 --- a/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/__snapshots__/alert_details_app_section.test.tsx.snap +++ b/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/__snapshots__/alert_details_app_section.test.tsx.snap @@ -17,7 +17,7 @@ Array [ "type": "manual", }, Object { - "color": "#F04E9833", + "color": "rgba(189,39,30,0.2)", "id": "metric_threshold_active_alert_range_annotation", "key": Object { "endTimestamp": "2024-06-13T07:00:33.381Z", diff --git a/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/alert_details_app_section.tsx b/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/alert_details_app_section.tsx index 8f3e22c5b8a8..b23bfe38d1d3 100644 --- a/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/alert_details_app_section.tsx +++ b/x-pack/plugins/observability_solution/infra/public/alerting/metric_threshold/components/alert_details_app_section.tsx @@ -18,7 +18,6 @@ import { transparentize, useEuiTheme, } from '@elastic/eui'; -import chroma from 'chroma-js'; import { RuleConditionChart, TopAlert } from '@kbn/observability-plugin/public'; import { ALERT_END, ALERT_START, ALERT_EVALUATION_VALUES, ALERT_GROUP } from '@kbn/rule-data-utils'; @@ -90,7 +89,7 @@ export function AlertDetailsAppSection({ alert, rule }: AppSectionProps) { timestamp: alertStart!, endTimestamp: alertEnd ?? moment().toISOString(), }, - color: chroma(transparentize('#F04E981A', 0.2)).hex().toUpperCase(), + color: transparentize(euiTheme.colors.danger, 0.2), id: `metric_threshold_${alertEnd ? 'recovered' : 'active'}_alert_range_annotation`, }; diff --git a/x-pack/plugins/observability_solution/infra/public/components/log_stream/log_stream_react_embeddable.tsx b/x-pack/plugins/observability_solution/infra/public/components/log_stream/log_stream_react_embeddable.tsx index 43382cf37203..f5fee9d94ea0 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/log_stream/log_stream_react_embeddable.tsx +++ b/x-pack/plugins/observability_solution/infra/public/components/log_stream/log_stream_react_embeddable.tsx @@ -142,8 +142,8 @@ const DeprecationCallout = () => { target="_blank" > {i18n.translate( - 'xpack.infra.logsStreamEmbeddable.deprecationWarningDescription.savedSearchesLinkLabel', - { defaultMessage: 'saved searches' } + 'xpack.infra.logsStreamEmbeddable.deprecationWarningDescription.discoverSessionsLinkLabel', + { defaultMessage: 'Discover sessions' } )} ), diff --git a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/density_chart.tsx b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/density_chart.tsx index 5f42d19d035d..d45fe0c3c42c 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/density_chart.tsx +++ b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/density_chart.tsx @@ -11,6 +11,7 @@ import { max } from 'lodash'; import * as React from 'react'; import styled from '@emotion/styled'; import { LogEntriesSummaryBucket } from '@kbn/logs-shared-plugin/common'; +import { COLOR_MODES_STANDARD } from '@elastic/eui'; interface DensityChartProps { buckets: LogEntriesSummaryBucket[]; @@ -66,14 +67,14 @@ export const DensityChart: React.FC = ({ const DensityChartPositiveBackground = styled.rect` fill: ${(props) => - props.theme.colorMode === 'DARK' + props.theme.colorMode === COLOR_MODES_STANDARD.dark ? props.theme.euiTheme.colors.lightShade : props.theme.euiTheme.colors.lightestShade}; `; const PositiveAreaPath = styled.path` fill: ${(props) => - props.theme.colorMode === 'DARK' + props.theme.colorMode === COLOR_MODES_STANDARD.dark ? props.theme.euiTheme.colors.mediumShade : props.theme.euiTheme.colors.lightShade}; `; diff --git a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/log_minimap.tsx b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/log_minimap.tsx index fcd57e98b07d..a2c1121ff2ba 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/log_minimap.tsx +++ b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/log_minimap.tsx @@ -14,6 +14,7 @@ import { import { scaleLinear } from 'd3-scale'; import moment from 'moment'; import * as React from 'react'; +import { COLOR_MODES_STANDARD } from '@elastic/eui'; import { DensityChart } from './density_chart'; import { HighlightedInterval } from './highlighted_interval'; import { SearchMarkers } from './search_markers'; @@ -166,7 +167,7 @@ const TimeCursor = styled.line` pointer-events: none; stroke-width: 1px; stroke: ${(props) => - props.theme.colorMode === 'DARK' + props.theme.colorMode === COLOR_MODES_STANDARD.dark ? props.theme.euiTheme.colors.darkestShade : props.theme.euiTheme.colors.darkShade}; `; diff --git a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/time_ruler.tsx b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/time_ruler.tsx index 1223e014fe9e..59e94333e94e 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/time_ruler.tsx +++ b/x-pack/plugins/observability_solution/infra/public/components/logging/log_minimap/time_ruler.tsx @@ -8,7 +8,7 @@ import { scaleTime } from 'd3-scale'; import * as React from 'react'; import styled from '@emotion/styled'; -import { useEuiFontSize } from '@elastic/eui'; +import { COLOR_MODES_STANDARD, useEuiFontSize } from '@elastic/eui'; import { useKibanaTimeZoneSetting } from '../../../hooks/use_kibana_time_zone_setting'; import { getTimeLabelFormat } from './time_label_formatter'; @@ -69,7 +69,7 @@ const TimeRulerTickLabel = styled.text` const TimeRulerGridLine = styled.line` stroke: ${(props) => - props.theme.colorMode === 'DARK' + props.theme.colorMode === COLOR_MODES_STANDARD.dark ? props.theme.euiTheme.colors.darkestShade : props.theme.euiTheme.colors.darkShade}; stroke-opacity: 0.5; diff --git a/x-pack/plugins/observability_solution/infra/public/hooks/use_entity_centric_experience_setting.tsx b/x-pack/plugins/observability_solution/infra/public/hooks/use_entity_centric_experience_setting.tsx index 1cbc4680405e..1ac6eed88f2a 100644 --- a/x-pack/plugins/observability_solution/infra/public/hooks/use_entity_centric_experience_setting.tsx +++ b/x-pack/plugins/observability_solution/infra/public/hooks/use_entity_centric_experience_setting.tsx @@ -11,7 +11,7 @@ import { useKibanaContextForPlugin } from './use_kibana'; export function useEntityCentricExperienceSetting() { const { uiSettings } = useKibanaContextForPlugin().services; - const isEntityCentricExperienceEnabled = uiSettings.get(entityCentricExperience, true); + const isEntityCentricExperienceEnabled = uiSettings.get(entityCentricExperience); return { isEntityCentricExperienceEnabled }; } diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx index 0697b05205fe..a40bab58d70f 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import moment from 'moment'; import { first, last } from 'lodash'; -import { EuiLoadingChart, EuiText, EuiEmptyPrompt, EuiButton } from '@elastic/eui'; +import { EuiLoadingChart, EuiText, EuiEmptyPrompt, EuiButton, useEuiTheme } from '@elastic/eui'; import { Axis, Chart, @@ -56,7 +56,7 @@ export const Timeline: React.FC = ({ interval, yAxisFormatter, isVisible const { metric, nodeType, accountId, region } = useWaffleOptionsContext(); const { currentTime, jumpToTime, stopAutoReload } = useWaffleTimeContext(); const { filterQueryAsJson } = useWaffleFiltersContext(); - + const { euiTheme } = useEuiTheme(); const chartTheme = useTimelineChartTheme(); const { loading, error, startTime, endTime, timeseries, reload } = useTimeline( @@ -238,7 +238,11 @@ export const Timeline: React.FC = ({ interval, yAxisFormatter, isVisible @@ -261,7 +265,7 @@ export const Timeline: React.FC = ({ interval, yAxisFormatter, isVisible dataValues={generateAnnotationData( anomalies.map((a) => [a.startTime, a.influencers]) )} - style={{ fill: '#D36086' }} + style={{ fill: euiTheme.colors.backgroundFilledAccent }} /> )} i18n.translate('xpack.infra.logStreamEmbeddable.description', { defaultMessage: - 'Add a table of live streaming logs. For a more efficient experience, we recommend using the Discover Page to create a saved search instead of using Log stream.', + 'Add a table of live streaming logs. For a more efficient experience, we recommend using the Discover Page to create a saved Discover session instead of using Log stream.', }), getIconType: () => 'logsApp', isCompatible: async ({ embeddable }) => { diff --git a/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.test.ts b/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.test.ts index 75048ac22a6a..4a1466b698c7 100644 --- a/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.test.ts +++ b/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.test.ts @@ -35,13 +35,13 @@ describe('getDataStreamTypes', () => { jest.clearAllMocks(); }); - it('should return only metrics when entityCentriExperienceEnabled is false and hasMetricsData is true', async () => { + it('should return only metrics when entityCentricExperienceEnabled is false and hasMetricsData is true', async () => { (getHasMetricsData as jest.Mock).mockResolvedValue(true); const params = { entityId: 'entity123', entityType: 'host' as EntityType, - entityCentriExperienceEnabled: false, + entityCentricExperienceEnabled: false, infraMetricsClient, obsEsClient, entityManagerClient, @@ -58,13 +58,13 @@ describe('getDataStreamTypes', () => { }); }); - it('should return an empty array when entityCentriExperienceEnabled is false and hasMetricsData is false', async () => { + it('should return an empty array when entityCentricExperienceEnabled is false and hasMetricsData is false', async () => { (getHasMetricsData as jest.Mock).mockResolvedValue(false); const params = { entityId: 'entity123', entityType: 'container' as EntityType, - entityCentriExperienceEnabled: false, + entityCentricExperienceEnabled: false, infraMetricsClient, obsEsClient, entityManagerClient, @@ -75,7 +75,7 @@ describe('getDataStreamTypes', () => { expect(result).toEqual([]); }); - it('should return metrics and entity source_data_stream types when entityCentriExperienceEnabled is true and has entity data', async () => { + it('should return metrics and entity source_data_stream types when entityCentricExperienceEnabled is true and has entity data', async () => { (getHasMetricsData as jest.Mock).mockResolvedValue(true); (getLatestEntity as jest.Mock).mockResolvedValue({ sourceDataStreamType: ['logs', 'metrics'], @@ -84,7 +84,7 @@ describe('getDataStreamTypes', () => { const params = { entityId: 'entity123', entityType: 'host' as EntityType, - entityCentriExperienceEnabled: true, + entityCentricExperienceEnabled: true, infraMetricsClient, obsEsClient, entityManagerClient, @@ -104,14 +104,14 @@ describe('getDataStreamTypes', () => { }); }); - it('should return only metrics when entityCentriExperienceEnabled is true but entity data is undefined', async () => { + it('should return only metrics when entityCentricExperienceEnabled is true but entity data is undefined', async () => { (getHasMetricsData as jest.Mock).mockResolvedValue(true); (getLatestEntity as jest.Mock).mockResolvedValue(undefined); const params = { entityId: 'entity123', entityType: 'host' as EntityType, - entityCentriExperienceEnabled: true, + entityCentricExperienceEnabled: true, infraMetricsClient, obsEsClient, entityManagerClient, @@ -131,7 +131,7 @@ describe('getDataStreamTypes', () => { const params = { entityId: 'entity123', entityType: 'host' as EntityType, - entityCentriExperienceEnabled: true, + entityCentricExperienceEnabled: true, infraMetricsClient, obsEsClient, entityManagerClient, diff --git a/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.ts b/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.ts index 4a949de4d0ed..d1cd99be31f9 100644 --- a/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.ts +++ b/x-pack/plugins/observability_solution/infra/server/routes/entities/get_data_stream_types.ts @@ -18,7 +18,7 @@ import { getLatestEntity } from './get_latest_entity'; interface Params { entityId: string; entityType: 'host' | 'container'; - entityCentriExperienceEnabled: boolean; + entityCentricExperienceEnabled: boolean; infraMetricsClient: InfraMetricsClient; obsEsClient: ObservabilityElasticsearchClient; entityManagerClient: EntityClient; @@ -26,7 +26,7 @@ interface Params { } export async function getDataStreamTypes({ - entityCentriExperienceEnabled, + entityCentricExperienceEnabled, entityId, entityManagerClient, entityType, @@ -42,7 +42,7 @@ export async function getDataStreamTypes({ const sourceDataStreams = new Set(hasMetricsData ? [EntityDataStreamType.METRICS] : []); - if (!entityCentriExperienceEnabled) { + if (!entityCentricExperienceEnabled) { return Array.from(sourceDataStreams); } diff --git a/x-pack/plugins/observability_solution/infra/server/routes/entities/index.ts b/x-pack/plugins/observability_solution/infra/server/routes/entities/index.ts index 4056faba9427..9c5c5c4527fe 100644 --- a/x-pack/plugins/observability_solution/infra/server/routes/entities/index.ts +++ b/x-pack/plugins/observability_solution/infra/server/routes/entities/index.ts @@ -54,13 +54,13 @@ export const initEntitiesConfigurationRoutes = (libs: InfraBackendLibs) => { plugin: `@kbn/${METRICS_APP_ID}-plugin`, }); - const entityCentriExperienceEnabled = await coreContext.uiSettings.client.get( + const entityCentricExperienceEnabled = await coreContext.uiSettings.client.get( entityCentricExperience ); try { const sourceDataStreamTypes = await getDataStreamTypes({ - entityCentriExperienceEnabled, + entityCentricExperienceEnabled, entityId, entityManagerClient, entityType, diff --git a/x-pack/plugins/observability_solution/infra/tsconfig.json b/x-pack/plugins/observability_solution/infra/tsconfig.json index dd3e56903ea5..639780d61ae8 100644 --- a/x-pack/plugins/observability_solution/infra/tsconfig.json +++ b/x-pack/plugins/observability_solution/infra/tsconfig.json @@ -9,7 +9,6 @@ "public/**/*", "server/**/*", "types/**/*", - "./emotion.d.ts" ], "kbn_references": [ "@kbn/core", diff --git a/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/alert_count/alert_count.cy.ts b/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/alert_count/alert_count.cy.ts index ac5fa17ecb08..525828de10b1 100644 --- a/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/alert_count/alert_count.cy.ts +++ b/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/alert_count/alert_count.cy.ts @@ -33,10 +33,15 @@ const verifyAlertsTableCount = (alertsCount: string) => { verifyNumber(cy.getByTestSubj('toolbar-alerts-count'), alertsCount); }; -describe('Alert count', () => { +// Temporary skipping those test, will be enabled in the future once we fix them https://github.com/elastic/kibana/issues/204558 +describe.skip('Alert count', () => { beforeEach(() => { cy.loginAsSuperUser(); + cy.updateAdvancedSettings({ + 'observability:entityCentricExperience': true, + }); + cy.intercept('GET', '/internal/entities/managed/enablement', { fixture: 'eem_enabled.json', }).as('getEEMStatus'); @@ -49,6 +54,9 @@ describe('Alert count', () => { }); afterEach(() => { + cy.updateAdvancedSettings({ + 'observability:entityCentricExperience': false, + }); entitiesSynthtrace.clean(); cleanEntityAlerts(); }); diff --git a/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/home.cy.ts b/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/home.cy.ts index c2e7f1232e6a..e86c673c2a6b 100644 --- a/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/home.cy.ts +++ b/x-pack/plugins/observability_solution/inventory/e2e/cypress/e2e/home.cy.ts @@ -11,9 +11,29 @@ import { generateEntities, generateLogs, generateTraces } from './generate_data' const start = '2024-10-16T00:00:00.000Z'; const end = '2024-10-16T00:15:00.000Z'; -describe('Home page', () => { +// Temporary skipping those test, will be enabled in the future once we fix them https://github.com/elastic/kibana/issues/204558 +describe.skip('Home page', () => { beforeEach(() => { cy.loginAsSuperUser(); + cy.updateAdvancedSettings({ + 'observability:entityCentricExperience': true, + }); + }); + + afterEach(() => { + cy.updateAdvancedSettings({ + 'observability:entityCentricExperience': false, + }); + }); + + describe('When the entityCentricExperience FF is disabled', () => { + it('Shows 404', () => { + cy.updateAdvancedSettings({ + 'observability:entityCentricExperience': false, + }); + cy.visitKibana('/app/inventory'); + cy.contains('Application Not Found'); + }); }); describe('When EEM is disabled', () => { diff --git a/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/commands.ts b/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/commands.ts index c3462f8b6ff1..9a260519c760 100644 --- a/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/commands.ts +++ b/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/commands.ts @@ -55,3 +55,17 @@ Cypress.Commands.add( ); } ); + +Cypress.Commands.add('updateAdvancedSettings', (settings: Record) => { + const kibanaUrl = Cypress.env('KIBANA_URL'); + cy.request({ + log: false, + method: 'POST', + url: `${kibanaUrl}/internal/kibana/settings`, + body: { changes: settings }, + headers: { + 'kbn-xsrf': 'e2e_test', + }, + auth: { user: 'elastic', pass: 'changeme' }, + }); +}); diff --git a/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/types.d.ts b/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/types.d.ts index c51b20c3b990..8e49da093612 100644 --- a/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/types.d.ts +++ b/x-pack/plugins/observability_solution/inventory/e2e/cypress/support/types.d.ts @@ -13,6 +13,7 @@ declare namespace Cypress { password: string; }): Cypress.Chainable>; getByTestSubj(selector: string): Chainable>; + updateAdvancedSettings(settings: Record): void; visitKibana(url: string): void; } } diff --git a/x-pack/plugins/observability_solution/inventory/public/plugin.ts b/x-pack/plugins/observability_solution/inventory/public/plugin.ts index 109123859d4c..0d9309d3694f 100644 --- a/x-pack/plugins/observability_solution/inventory/public/plugin.ts +++ b/x-pack/plugins/observability_solution/inventory/public/plugin.ts @@ -57,7 +57,7 @@ export class InventoryPlugin const inventoryAPIClient = createCallInventoryAPI(coreSetup); const isEntityCentricExperienceSettingEnabled = coreSetup.uiSettings.get( 'observability:entityCentricExperience', - true + false ); this.telemetry.setup({ diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/.gitignore b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/.gitignore new file mode 100644 index 000000000000..b88cb2a2003a --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/.gitignore @@ -0,0 +1,2 @@ +.playwright +.env* diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/README.md b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/README.md new file mode 100644 index 000000000000..f2952214127f --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/README.md @@ -0,0 +1,25 @@ +# Observability Onboarding Playwright Tests + +These tests are part of the [Nightly CI workflow](https://github.com/elastic/ensemble/actions/workflows/nightly.yml) and do not run on PRs. + +Playwright tests are only responsible for UI checks and do not automate onboarding flows fully. On the CI, the missing parts (like executing code snippets on the host) are automated by Ensemble stories, but when running locally you need to do those steps manually. + +## Running The Tests Locally + +1. Run ES and Kibana +2. Create a `.env` file in the `./x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/` directory with the following content (adjust the values like Kibana URL according yo your local setup): +```bash +KIBANA_BASE_URL = "http://localhost:5601/ftw" +ELASTICSEARCH_HOST = "http://localhost:9200" +KIBANA_USERNAME = "elastic" +KIBANA_PASSWORD = "changeme" +CLUSTER_ENVIRONMENT = local +ARTIFACTS_FOLDER = ./.playwright +``` +3. Run the `playwright test` +```bash +# Assuming the working directory is the root of the Kibana repo +npx playwright test -c ./x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/playwright.config.ts --project stateful --reporter list --headed +``` +4. Once the test reaches one of the required manual steps, like executing auto-detect command snippet, do the step manually. +5. The test will proceed once the manual step is done. diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/assert_env.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/assert_env.ts new file mode 100644 index 000000000000..6c54cabdc160 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/assert_env.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export function assertEnv(variable: unknown, message: string): asserts variable is string { + if (typeof variable !== 'string') { + throw new Error(message); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/helpers.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/helpers.ts new file mode 100644 index 000000000000..e7c6afaefbd2 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/helpers.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Locator } from '@playwright/test'; +import { HeaderBar } from '../stateful/pom/components/header_bar.component'; +import { SpaceSelector } from '../stateful/pom/components/space_selector.component'; + +type WaitForRes = [locatorIndex: number, locator: Locator]; + +export async function waitForOneOf(locators: Locator[]): Promise { + const res = await Promise.race([ + ...locators.map(async (locator, index): Promise => { + let timedOut = false; + await locator.waitFor({ state: 'visible' }).catch(() => (timedOut = true)); + return [timedOut ? -1 : index, locator]; + }), + ]); + if (res[0] === -1) { + throw new Error('No locator is visible before timeout.'); + } + return res; +} + +export async function spaceSelectorStateful(headerBar: HeaderBar, spaceSelector: SpaceSelector) { + const [index] = await waitForOneOf([headerBar.helpMenuButton(), spaceSelector.spaceSelector()]); + const selector = index === 1; + if (selector) { + await spaceSelector.selectDefault(); + await headerBar.assertHelpMenuButton(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/logger.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/logger.ts new file mode 100644 index 000000000000..92ec2ba6918f --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/lib/logger.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ToolingLog } from '@kbn/tooling-log'; + +export const log: ToolingLog = new ToolingLog({ + level: 'info', + writeTo: process.stdout, +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/playwright.config.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/playwright.config.ts new file mode 100644 index 000000000000..39217999f5a2 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/playwright.config.ts @@ -0,0 +1,102 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import dotenv from 'dotenv'; +import { defineConfig, devices } from '@playwright/test'; +import path from 'path'; +import { log } from './lib/logger'; +import { assertEnv } from './lib/assert_env'; + +const dotEnvPath = process.env.DOTENV_PATH ?? path.join(__dirname, '.env'); + +dotenv.config({ path: dotEnvPath }); + +assertEnv(process.env.ARTIFACTS_FOLDER, 'ARTIFACTS_FOLDER is not defined.'); + +export const STORAGE_STATE = path.join(__dirname, process.env.ARTIFACTS_FOLDER, '.auth/user.json'); + +// eslint-disable-next-line import/no-default-export +export default defineConfig({ + testDir: './', + outputDir: './.playwright', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + // workers: 4, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: [ + ['json'], + ['json', { outputFile: path.join(process.env.ARTIFACTS_FOLDER, 'results.json') }], + ], + /* Timeouts */ + timeout: 400000, + expect: { timeout: 400000 }, + + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL: process.env.KIBANA_BASE_URL, + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + testIdAttribute: 'data-test-subj', + permissions: ['clipboard-read'], + screenshot: 'only-on-failure', + }, + + projects: [ + { + name: 'auth', + testMatch: '*stateful/auth.ts', + use: { + viewport: { width: 1920, height: 1080 }, + launchOptions: { + logger: { + isEnabled: () => true, + log: (name, severity, message) => log.info(`[${severity}] ${name} ${message}`), + }, + }, + }, + }, + { + name: 'stateful', + testMatch: '*stateful/*.spec.ts', + use: { + ...devices['Desktop Chrome'], + viewport: { width: 1920, height: 1200 }, + storageState: STORAGE_STATE, + launchOptions: { + logger: { + isEnabled: () => true, + log: (name, severity, message) => log.info(`[${severity}] ${name} ${message}`), + }, + }, + }, + dependencies: ['auth'], + }, + { + name: 'teardown', + testMatch: 'teardown.setup.ts', + use: { + viewport: { width: 1920, height: 1080 }, + storageState: STORAGE_STATE, + testIdAttribute: 'data-test-subj', + launchOptions: { + logger: { + isEnabled: () => true, + log: (name, severity, message) => log.info(`[${severity}] ${name} ${message}`), + }, + }, + }, + }, + ], +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auth.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auth.ts new file mode 100644 index 000000000000..726085fbabc3 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auth.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { test as ess_auth, expect } from '@playwright/test'; +import { STORAGE_STATE } from '../playwright.config'; +import { waitForOneOf } from '../lib/helpers'; +import { log } from '../lib/logger'; +import { assertEnv } from '../lib/assert_env'; + +const isLocalCluster = process.env.CLUSTER_ENVIRONMENT === 'local'; + +ess_auth('Authentication', async ({ page }) => { + assertEnv(process.env.KIBANA_BASE_URL, 'KIBANA_BASE_URL is not defined.'); + assertEnv(process.env.KIBANA_USERNAME, 'KIBANA_USERNAME is not defined.'); + assertEnv(process.env.KIBANA_PASSWORD, 'KIBANA_PASSWORD is not defined.'); + + await page.goto(process.env.KIBANA_BASE_URL); + log.info(`...waiting for login page elements to appear.`); + if (!isLocalCluster) { + await page.getByRole('button', { name: 'Log in with Elasticsearch' }).click(); + } + await page.getByLabel('Username').fill(process.env.KIBANA_USERNAME); + await page.getByLabel('Password', { exact: true }).click(); + await page.getByLabel('Password', { exact: true }).fill(process.env.KIBANA_PASSWORD); + await page.getByRole('button', { name: 'Log in' }).click(); + + const [index] = await waitForOneOf([ + page.getByTestId('helpMenuButton'), + page.getByText('Select your space'), + page.getByTestId('loginErrorMessage'), + ]); + + const spaceSelector = index === 1; + const isAuthenticated = index === 0; + + if (isAuthenticated) { + await page.context().storageState({ path: STORAGE_STATE }); + } else if (spaceSelector) { + await page.getByRole('link', { name: 'Default' }).click(); + await expect(page.getByTestId('helpMenuButton')).toBeVisible(); + await page.context().storageState({ path: STORAGE_STATE }); + } else { + log.error('Username or password is incorrect.'); + throw new Error('Authentication is failed.'); + } +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auto_detect.spec.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auto_detect.spec.ts new file mode 100644 index 000000000000..cff927a2061c --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/auto_detect.spec.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from './fixtures/base_page'; +import { HostDetailsPage } from './pom/pages/host_details.page'; +import { assertEnv } from '../lib/assert_env'; + +test.beforeEach(async ({ page }) => { + await page.goto(`${process.env.KIBANA_BASE_URL}/app/observabilityOnboarding`); +}); + +test('Auto-detect logs and metrics', async ({ page, onboardingHomePage, autoDetectFlowPage }) => { + assertEnv(process.env.ARTIFACTS_FOLDER, 'ARTIFACTS_FOLDER is not defined.'); + + const fileName = 'code_snippet_logs_auto_detect.sh'; + const outputPath = path.join(__dirname, '..', process.env.ARTIFACTS_FOLDER, fileName); + + await onboardingHomePage.selectHostUseCase(); + await onboardingHomePage.selectAutoDetectWithElasticAgent(); + + await autoDetectFlowPage.assertVisibilityCodeBlock(); + await autoDetectFlowPage.copyToClipboard(); + + const clipboardData = (await page.evaluate('navigator.clipboard.readText()')) as string; + + /** + * Ensemble story watches for the code snippet file + * to be created and then executes it + */ + fs.writeFileSync(outputPath, clipboardData); + + await autoDetectFlowPage.assertReceivedDataIndicator(); + await autoDetectFlowPage.clickAutoDetectSystemIntegrationCTA(); + + /** + * Host Details pages open in a new tab, so it + * needs to be captured using the `popup` event. + */ + const hostDetailsPage = new HostDetailsPage(await page.waitForEvent('popup')); + + /** + * There is a glitch on the Hosts page where it can show "No data" + * screen even though data is available and it can show it with a delay + * after the Hosts page layout was loaded. This workaround waits for + * the No Data screen to be visible, and if so - reloads the page. + * If the No Data screen does not appear, the test can proceed normally. + * Seems like some caching issue with the Hosts page. + */ + try { + await hostDetailsPage.noData().waitFor({ state: 'visible', timeout: 10000 }); + await hostDetailsPage.page.waitForTimeout(2000); + await hostDetailsPage.page.reload(); + } catch { + /* Ignore if "No Data" screen never showed up */ + } + + await hostDetailsPage.clickHostDetailsLogsTab(); + await hostDetailsPage.assertHostDetailsLogsStream(); +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/fixtures/base_page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/fixtures/base_page.ts new file mode 100644 index 000000000000..e10be1d60cc1 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/fixtures/base_page.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { test as base } from '@playwright/test'; +import { HeaderBar } from '../pom/components/header_bar.component'; +import { OnboardingHomePage } from '../pom/pages/onboarding_home.page'; +import { SpaceSelector } from '../pom/components/space_selector.component'; +import { KubernetesOverviewDashboardPage } from '../pom/pages/kubernetes_overview_dashboard.page'; +import { AutoDetectFlowPage } from '../pom/pages/auto_detect_flow.page'; +import { KubernetesEAFlowPage } from '../pom/pages/kubernetes_ea_flow.page'; + +export const test = base.extend<{ + headerBar: HeaderBar; + spaceSelector: SpaceSelector; + onboardingHomePage: OnboardingHomePage; + autoDetectFlowPage: AutoDetectFlowPage; + kubernetesEAFlowPage: KubernetesEAFlowPage; + kubernetesOverviewDashboardPage: KubernetesOverviewDashboardPage; +}>({ + headerBar: async ({ page }, use) => { + await use(new HeaderBar(page)); + }, + + spaceSelector: async ({ page }, use) => { + await use(new SpaceSelector(page)); + }, + + onboardingHomePage: async ({ page }, use) => { + await use(new OnboardingHomePage(page)); + }, + + autoDetectFlowPage: async ({ page }, use) => { + await use(new AutoDetectFlowPage(page)); + }, + + kubernetesEAFlowPage: async ({ page }, use) => { + await use(new KubernetesEAFlowPage(page)); + }, + + kubernetesOverviewDashboardPage: async ({ page }, use) => { + await use(new KubernetesOverviewDashboardPage(page)); + }, +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/kubernetes_ea.spec.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/kubernetes_ea.spec.ts new file mode 100644 index 000000000000..8478630b232f --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/kubernetes_ea.spec.ts @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from './fixtures/base_page'; +import { assertEnv } from '../lib/assert_env'; + +test.beforeEach(async ({ page }) => { + await page.goto(`${process.env.KIBANA_BASE_URL}/app/observabilityOnboarding`); +}); + +test('Kubernetes EA', async ({ + page, + onboardingHomePage, + kubernetesEAFlowPage, + kubernetesOverviewDashboardPage, +}) => { + assertEnv(process.env.ARTIFACTS_FOLDER, 'ARTIFACTS_FOLDER is not defined.'); + + const fileName = 'code_snippet_kubernetes.sh'; + const outputPath = path.join(__dirname, '..', process.env.ARTIFACTS_FOLDER, fileName); + + await onboardingHomePage.selectKubernetesUseCase(); + await onboardingHomePage.selectKubernetesQuickstart(); + + await kubernetesEAFlowPage.assertVisibilityCodeBlock(); + await kubernetesEAFlowPage.copyToClipboard(); + + const clipboardData = (await page.evaluate('navigator.clipboard.readText()')) as string; + /** + * The page waits for the browser window to loose + * focus as a signal to start checking for incoming data + */ + await page.evaluate('window.dispatchEvent(new Event("blur"))'); + + /** + * Ensemble story watches for the code snippet file + * to be created and then executes it + */ + fs.writeFileSync(outputPath, clipboardData); + + await kubernetesEAFlowPage.assertReceivedDataIndicatorKubernetes(); + await kubernetesEAFlowPage.clickKubernetesAgentCTA(); + + await kubernetesOverviewDashboardPage.openNodesInspector(); + /** + * There might be a case that dashboard still does not show + * the data even though it was ingested already. This usually + * happens during in the test when navigation from the onboarding + * flow to the dashboard happens almost immediately. + * Waiting for a few seconds and reloading the page handles + * this case and makes the test a bit more robust. + */ + try { + await kubernetesOverviewDashboardPage.assertNodesNoResultsNotVisible(); + } catch { + await kubernetesOverviewDashboardPage.page.waitForTimeout(2000); + await kubernetesOverviewDashboardPage.page.reload(); + } + await kubernetesOverviewDashboardPage.assetNodesInspectorStatusTableCells(); +}); diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/header_bar.component.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/header_bar.component.ts new file mode 100644 index 000000000000..9165622bf6ce --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/header_bar.component.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { expect, Page } from '@playwright/test'; + +export class HeaderBar { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + public readonly helpMenuButton = () => this.page.getByTestId('helpMenuButton'); + + public async assertHelpMenuButton() { + await expect(this.helpMenuButton(), 'Help menu button').toBeVisible(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/space_selector.component.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/space_selector.component.ts new file mode 100644 index 000000000000..8527141d455a --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/components/space_selector.component.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Page } from '@playwright/test'; + +export class SpaceSelector { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + public readonly spaceSelector = () => this.page.getByText('Select your space'); + private readonly spaceSelectorDefault = () => this.page.getByRole('link', { name: 'Default' }); + + public async selectDefault() { + await this.spaceSelectorDefault().click(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/auto_detect_flow.page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/auto_detect_flow.page.ts new file mode 100644 index 000000000000..b1090b3cf091 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/auto_detect_flow.page.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { expect, Page } from '@playwright/test'; + +export class AutoDetectFlowPage { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + private readonly copyToClipboardButton = () => + this.page.getByTestId('observabilityOnboardingCopyToClipboardButton'); + + private readonly receivedDataIndicator = () => + this.page + .getByTestId('observabilityOnboardingAutoDetectPanelDataReceivedProgressIndicator') + .getByText('Your data is ready to explore!'); + + private readonly autoDetectSystemIntegrationActionLink = () => + this.page.getByTestId( + 'observabilityOnboardingDataIngestStatusActionLink-inventory-host-details' + ); + + private readonly codeBlock = () => + this.page.getByTestId('observabilityOnboardingAutoDetectPanelCodeSnippet'); + + public async copyToClipboard() { + await this.copyToClipboardButton().click(); + } + + public async assertVisibilityCodeBlock() { + await expect(this.codeBlock(), 'Code block should be visible').toBeVisible(); + } + + public async assertReceivedDataIndicator() { + await expect( + this.receivedDataIndicator(), + 'Received data indicator should be visible' + ).toBeVisible(); + } + + public async clickAutoDetectSystemIntegrationCTA() { + await this.autoDetectSystemIntegrationActionLink().click(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/host_details.page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/host_details.page.ts new file mode 100644 index 000000000000..d22b33d85163 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/host_details.page.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { expect, Page } from '@playwright/test'; + +export class HostDetailsPage { + page: Page; + + public readonly hostDetailsLogsTab = () => this.page.getByTestId('infraAssetDetailsLogsTab'); + + private readonly hostDetailsLogsStream = () => this.page.getByTestId('logStream'); + + public readonly noData = () => this.page.getByTestId('kbnNoDataPage'); + + constructor(page: Page) { + this.page = page; + } + + public async clickHostDetailsLogsTab() { + await this.hostDetailsLogsTab().click(); + } + + public async assertHostDetailsLogsStream() { + await expect( + this.hostDetailsLogsStream(), + 'Host details log stream should be visible' + /** + * Using toBeAttached() instead of toBeVisible() because the element + * we're selecting here has a bit weird layout with 0 height and + * overflowing child elements. 0 height makes toBeVisible() fail. + */ + ).toBeAttached(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_ea_flow.page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_ea_flow.page.ts new file mode 100644 index 000000000000..e956de485557 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_ea_flow.page.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { expect, Page } from '@playwright/test'; + +export class KubernetesEAFlowPage { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + private readonly receivedDataIndicatorKubernetes = () => + this.page + .getByTestId('observabilityOnboardingKubernetesPanelDataProgressIndicator') + .getByText('We are monitoring your cluster'); + + private readonly kubernetesAgentExploreDataActionLink = () => + this.page.getByTestId( + 'observabilityOnboardingDataIngestStatusActionLink-kubernetes-f4dc26db-1b53-4ea2-a78b-1bfab8ea267c' + ); + + private readonly codeBlock = () => + this.page.getByTestId('observabilityOnboardingKubernetesPanelCodeSnippet'); + + private readonly copyToClipboardButton = () => + this.page.getByTestId('observabilityOnboardingCopyToClipboardButton'); + + public async assertVisibilityCodeBlock() { + await expect(this.codeBlock(), 'Code block should be visible').toBeVisible(); + } + + public async copyToClipboard() { + await this.copyToClipboardButton().click(); + } + + public async assertReceivedDataIndicatorKubernetes() { + await expect( + this.receivedDataIndicatorKubernetes(), + 'Received data indicator should be visible' + ).toBeVisible(); + } + + public async clickKubernetesAgentCTA() { + await this.kubernetesAgentExploreDataActionLink().click(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_overview_dashboard.page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_overview_dashboard.page.ts new file mode 100644 index 000000000000..9562f0262994 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/kubernetes_overview_dashboard.page.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { expect, Page } from '@playwright/test'; + +export class KubernetesOverviewDashboardPage { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + private readonly nodesPanelHeader = () => this.page.getByTestId('embeddablePanelHeading-Nodes'); + + private readonly nodesInspectorButton = () => + this.page + .getByTestId('embeddablePanelHoverActions-Nodes') + .getByTestId('embeddablePanelAction-openInspector'); + + private readonly nodesInspectorTableNoResults = () => + this.page.getByTestId('inspectorTable').getByText('No items found'); + + private readonly nodesInspectorTableStatusTableCells = () => + this.page.getByTestId('inspectorTable').getByText('Status'); + + public async assertNodesNoResultsNotVisible() { + await expect( + this.nodesInspectorTableNoResults(), + 'Nodes "No results" message should not be visible' + ).toBeHidden(); + } + + public async openNodesInspector() { + await this.nodesPanelHeader().hover(); + await this.nodesInspectorButton().click(); + } + + public async assetNodesInspectorStatusTableCells() { + await expect( + this.nodesInspectorTableStatusTableCells(), + 'Status table cell should exist' + ).toBeVisible(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/onboarding_home.page.ts b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/onboarding_home.page.ts new file mode 100644 index 000000000000..699700149652 --- /dev/null +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/playwright/stateful/pom/pages/onboarding_home.page.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Page } from '@playwright/test'; + +export class OnboardingHomePage { + page: Page; + + constructor(page: Page) { + this.page = page; + } + + private readonly useCaseKubernetes = () => + this.page.getByTestId('observabilityOnboardingUseCaseCard-kubernetes').getByRole('radio'); + + private readonly kubernetesQuickStartCard = () => + this.page.getByTestId('integration-card:kubernetes-quick-start'); + + private readonly useCaseHost = () => + this.page.getByTestId('observabilityOnboardingUseCaseCard-host').getByRole('radio'); + + private readonly autoDetectElasticAgent = () => + this.page.getByTestId('integration-card:auto-detect-logs'); + + public async selectHostUseCase() { + await this.useCaseHost().click(); + } + + public async selectKubernetesUseCase() { + await this.useCaseKubernetes().click(); + } + + public async selectAutoDetectWithElasticAgent() { + await this.autoDetectElasticAgent().click(); + } + + public async selectKubernetesQuickstart() { + await this.kubernetesQuickStartCard().click(); + } +} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/e2e/tsconfig.json b/x-pack/plugins/observability_solution/observability_onboarding/e2e/tsconfig.json index 94d4f2278cb6..a18951aeb8cf 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/e2e/tsconfig.json +++ b/x-pack/plugins/observability_solution/observability_onboarding/e2e/tsconfig.json @@ -14,6 +14,7 @@ "@kbn/cypress-config", "@kbn/observability-onboarding-plugin", "@kbn/ftr-common-functional-services", - "@kbn/ftr-common-functional-ui-services" + "@kbn/ftr-common-functional-ui-services", + "@kbn/tooling-log" ] } diff --git a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/auto_detect/auto_detect_panel.tsx b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/auto_detect/auto_detect_panel.tsx index d12f0cae583f..2891d4c47834 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/auto_detect/auto_detect_panel.tsx +++ b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/auto_detect/auto_detect_panel.tsx @@ -95,7 +95,11 @@ export const AutoDetectPanel: FunctionComponent = () => { {/* Bash syntax highlighting only highlights a few random numbers (badly) so it looks less messy to go with plain text */} - + {command} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/command_snippet.tsx b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/command_snippet.tsx index ac00190fb268..ce22e3182973 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/command_snippet.tsx +++ b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/command_snippet.tsx @@ -63,7 +63,12 @@ export function CommandSnippet({ - + {command} diff --git a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/data_ingest_status.tsx b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/data_ingest_status.tsx index 659c1e5bd7b5..50725e262eb5 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/data_ingest_status.tsx +++ b/x-pack/plugins/observability_solution/observability_onboarding/public/application/quickstart_flows/kubernetes/data_ingest_status.tsx @@ -80,6 +80,7 @@ export function DataIngestStatus({ onboardingId }: Props) { css={css` max-width: 40%; `} + data-test-subj="observabilityOnboardingKubernetesPanelDataProgressIndicator" /> {isTroubleshootingVisible && ( diff --git a/x-pack/plugins/observability_solution/observability_shared/public/hooks/use_chart_theme.tsx b/x-pack/plugins/observability_solution/observability_shared/public/hooks/use_chart_theme.tsx index 1a914e4abcd7..3c06cfa9c712 100644 --- a/x-pack/plugins/observability_solution/observability_shared/public/hooks/use_chart_theme.tsx +++ b/x-pack/plugins/observability_solution/observability_shared/public/hooks/use_chart_theme.tsx @@ -5,13 +5,13 @@ * 2.0. */ -import { LIGHT_THEME, DARK_THEME, PartialTheme, Theme } from '@elastic/charts'; +import { LIGHT_THEME, DARK_THEME, PartialTheme } from '@elastic/charts'; +import { useEuiTheme, COLOR_MODES_STANDARD } from '@elastic/eui'; import { useMemo } from 'react'; -import { useTheme } from './use_theme'; -export function useChartThemes(): { baseTheme: Theme; theme: PartialTheme[] } { - const theme = useTheme(); - const baseTheme = theme.darkMode ? DARK_THEME : LIGHT_THEME; +export function useChartThemes() { + const theme = useEuiTheme(); + const baseTheme = theme.colorMode === COLOR_MODES_STANDARD.dark ? DARK_THEME : LIGHT_THEME; return useMemo(() => { const themeOverrides: PartialTheme = { diff --git a/x-pack/plugins/screenshotting/README.md b/x-pack/plugins/screenshotting/README.md deleted file mode 100644 index 8138be53dc8f..000000000000 --- a/x-pack/plugins/screenshotting/README.md +++ /dev/null @@ -1,156 +0,0 @@ -# Kibana Screenshotting - -This plugin provides functionality to take screenshots of the Kibana pages. -It uses Chromium and Puppeteer underneath to run the browser in headless mode. - -## Capabilities -- Canvas workpads screenshots. -- Dashboards screenshots. -- Expressions screenshots. -- PDF generation. -- Batch screenshotting. - -## Usage - -### Getting started -After listing the `screenshotting` plugin in your dependencies, the plugin will be intitalized on the setup stage. -The intitalization process downloads (if it is not already present) and verifies the Chromium build. - -The start contract exposes a public API to interact with the plugin. -Apart from the actual screenshotting functionality, it also provides a way for self-diagnostics. - -Here is an example of how you can take a screenshot of a Kibana URL. - -```typescript -import { lastValueFrom } from 'rxjs'; -import type { CoreSetup, Plugin } from 'src/core/server'; -import type { ScreenshottingStart } from 'x-pack/plugins/screenshotting/server'; - - -interface StartDeps { - screenshotting: ScreenshottingStart; -} - -class ExamplePlugin implements Plugin { - setup({ http, getStartServices }: CoreSetup) { - const router = http.createRouter(); - - router.get( - { - path: '/api/capture', - validate: { - query: schema.object({ - id: schema.string(), - }), - }, - }, - async (context, request, response) => { - const [, { screenshotting }] = await getStartServices(); - const { metrics, results } = await lastValueFrom( - screenshotting.getScreenshots({ - request, - urls: [`http://localhost/app/canvas#/workpad/workpad-${request.query.id}`], - }) - ); - - return response.ok({ - body: JSON.stringify({ - metrics, - image: results[0]?.screenshots[0]?.data.toString('base64'), - errors: results[0]?.renderErrors, - } as ScreenshottingExpressionResponse), - }); - } - ); - } - - start() {} -} - -export function plugin() { - return new ExamplePlugin(); -} -``` - -### API -Please use automatically generated API reference or generated TypeDoc comments to find the complete documentation. - -#### `getScreenshots(options): Observable` -Takes screenshots of multiple pages or an expression and returns an observable with the screenshotting results. - -The `options` parameter is an object with parameters of the screenshotting session. -Option | Required | Default | Description ---- | :---: | --- | --- -`browserTimezone` | no | _none_ | The browser timezone that will be emulated in the browser instance. This option should be used to keep timezone on server and client in sync. -`expression` | no | _none_ | An expression to capture screenshot of. Mutually exclusive with the `urls` parameter. -`format` | no | `'png'` | An output format. It can either be PDF or PNG. In case of capturing multiple URLs, all the screenshots will be combined into one document for PDF format. For PNG format, an array of screenshots will be returned. -`headers` | no | _none_ | Custom headers to be sent with each request. The headers will be used for authorization. -`input` | no | `undefined` | The expression input. -`layout` | no | `{}` | Page layout parameters describing characteristics of the capturing screenshot (e.g., dimensions, zoom, etc.). -`request` | no | _none_ | Kibana Request reference to extract headers from. -`timeouts` | no | _none_ | Timeouts for each phase of the screenshot. -`timeouts.openUrl` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for the "Loading…" screen to dismiss and find the initial data for the page. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. -`timeouts.renderComplete` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for all visualizations to fetch and render the data. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. -`timeouts.waitForElements` | no | (kibana.yml setting) | The timeout in milliseconds to allow the Chromium browser to wait for all visualization panels to load on the page. If the time is exceeded, a screenshot is captured showing the current page, and the result structure contains an error message. -`urls` | no | `[]` | The list or URL to take screenshots of. Every item can either be a string or a tuple containing a URL and a context. The contextual data can be gathered using the screenshot mode plugin. Mutually exclusive with the `expression` parameter. - -#### `diagnose(flags?: string[]): Observable` -Runs browser diagnostics. -The diagnostic implementation launches Chromium and emits the output in the resulting observable. - -There is a way to override some Chromium command line arguments using the `flags` parameter. - -### Configuration -Option | Default | Description ---- | --- | --- -`xpack.screenshotting.networkPolicy.enabled` | `true` | Capturing a screenshot from a Kibana page involves sending out requests for all the linked web assets. For example, a Markdown visualization can show an image from a remote server. -`xpack.screenshotting.networkPolicy.rules` | Allow http, https, ws, wss, and data. | A policy is specified as an array of objects that describe what to allow or deny based on a host or protocol. If a host or protocol is not specified, the rule matches any host or protocol. -`xpack.screenshotting.browser.autoDownload` | Depends on the `dist` parameter. | Flag to automatically download chromium distribution. -`xpack.screenshotting.browser.chromium.disableSandbox` | Defaults to `false` for all operating systems except Debian and Red Hat Linux, which use `true`. | It is recommended that you research the feasibility of enabling unprivileged user namespaces. An exception is if you are running Kibana in Docker because the container runs in a user namespace with the built-in seccomp/bpf filters. For more information, refer to [Chromium sandbox](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/linux/sandboxing.md). -`xpack.screenshotting.browser.chromium.proxy.enabled` | `false` | Enables the proxy for Chromium to use. -`xpack.screenshotting.browser.chromium.proxy.server` | _none_ | The uri for the proxy server. Providing the username and password for the proxy server via the uri is not supported. -`xpack.screenshotting.browser.chromium.proxy.bypass` | `[]` | An array of hosts that should not go through the proxy server and should use a direct connection instead. Examples of valid entries are "elastic.co", "*.elastic.co", ".elastic.co", ".elastic.co:5601". - -## How It Works -```mermaid -sequenceDiagram - participant User - participant Screenshotting - participant Browser - - User ->> Screenshotting: API call - Screenshotting ->> Browser: Launch browser - activate Browser - Screenshotting ->> Browser: Create page - Screenshotting ->> Browser: Set parameters - Note over Screenshotting,Browser: timezone - - Screenshotting ->> Browser: Open URL - Screenshotting ->> Browser: Set contextual data - Note over Screenshotting,Browser: custom context, screenshot mode flag - Browser ->> Screenshotting: Rendering - - Screenshotting ->> Browser: Wait for visualizations - Note over Screenshotting,Browser: poll for a number of DOM nodes to match
the number of dashboard elements - Screenshotting ->> Browser: Wait for render completion - Note over Screenshotting,Browser: poll for selectors indicating rendering completion - Browser ->> Screenshotting: Page is ready - - Screenshotting ->> Browser: Take screenshot - Browser ->> Screenshotting: Return PNG buffer - Screenshotting ->> User: Return screenshot -``` - -## Testing -### Integration -There is an example plugin that demonstrates integration with the screenshotting plugin. That plugin utilizes expression capturing. - -### Chromium Downloads -To download all Chromium browsers for all platforms and architectures: - -```bash -cd x-pack -npx gulp downloadChromium -``` - -This command is used to provision CI workspaces so that Chromium does not need to be downloaded for every CI run. diff --git a/x-pack/plugins/screenshotting/jest.config.js b/x-pack/plugins/screenshotting/jest.config.js deleted file mode 100644 index a02d667f86a1..000000000000 --- a/x-pack/plugins/screenshotting/jest.config.js +++ /dev/null @@ -1,15 +0,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. - */ - -module.exports = { - preset: '@kbn/test', - rootDir: '../../..', - roots: ['/x-pack/plugins/screenshotting'], - coverageDirectory: '/target/kibana-coverage/jest/x-pack/plugins/screenshotting', - coverageReporters: ['text', 'html'], - collectCoverageFrom: ['/x-pack/plugins/screenshotting/server/**/*.{ts}'], -}; diff --git a/x-pack/plugins/screenshotting/tsconfig.json b/x-pack/plugins/screenshotting/tsconfig.json deleted file mode 100644 index 5e37b84bbf2e..000000000000 --- a/x-pack/plugins/screenshotting/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "outDir": "target/types", - }, - "include": [ - "common/**/*", - "public/**/*", - "server/**/*", - "../../../typings/**/*" - ], - "kbn_references": [ - "@kbn/core", - { "path": "../../../src/setup_node_env/tsconfig.json" }, - "@kbn/expressions-plugin", - "@kbn/screenshot-mode-plugin", - "@kbn/cloud-plugin", - "@kbn/utility-types", - "@kbn/logging", - "@kbn/std", - "@kbn/i18n", - "@kbn/utils", - "@kbn/core-logging-server-mocks", - "@kbn/logging-mocks", - "@kbn/core-http-server", - "@kbn/core-plugins-server", - "@kbn/task-manager-plugin", - "@kbn/screenshotting-server", - ], - "exclude": [ - "target/**/*", - ] -} diff --git a/x-pack/plugins/search_assistant/public/components/nav_control/index.tsx b/x-pack/plugins/search_assistant/public/components/nav_control/index.tsx index a341fdbe8141..f75eff1042eb 100644 --- a/x-pack/plugins/search_assistant/public/components/nav_control/index.tsx +++ b/x-pack/plugins/search_assistant/public/components/nav_control/index.tsx @@ -5,7 +5,7 @@ * 2.0. */ import React, { useEffect, useRef, useState } from 'react'; -import { AssistantAvatar, useAbortableAsync } from '@kbn/observability-ai-assistant-plugin/public'; +import { useAbortableAsync } from '@kbn/observability-ai-assistant-plugin/public'; import { EuiButton, EuiLoadingSpinner, EuiToolTip, useEuiTheme } from '@elastic/eui'; import { css } from '@emotion/react'; import { v4 } from 'uuid'; @@ -19,6 +19,7 @@ import type { CoreStart } from '@kbn/core/public'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { KibanaThemeProvider } from '@kbn/react-kibana-context-theme'; import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app'; +import { AssistantIcon } from '@kbn/ai-assistant-icon'; interface NavControlWithProviderDeps { coreStart: CoreStart; @@ -123,7 +124,7 @@ export function NavControl() { fullWidth={false} minWidth={0} > - {chatService.loading ? : } + {chatService.loading ? : }
{chatService.value && diff --git a/x-pack/plugins/search_assistant/tsconfig.json b/x-pack/plugins/search_assistant/tsconfig.json index 30002038bbc2..f29f624ab46e 100644 --- a/x-pack/plugins/search_assistant/tsconfig.json +++ b/x-pack/plugins/search_assistant/tsconfig.json @@ -28,7 +28,8 @@ "@kbn/licensing-plugin", "@kbn/ml-plugin", "@kbn/share-plugin", - "@kbn/triggers-actions-ui-plugin" + "@kbn/triggers-actions-ui-plugin", + "@kbn/ai-assistant-icon" ], "exclude": [ "target/**/*", diff --git a/x-pack/plugins/search_notebooks/public/components/notebooks_button.tsx b/x-pack/plugins/search_notebooks/public/components/notebooks_button.tsx index 66fc50a03ddd..d71cade82aae 100644 --- a/x-pack/plugins/search_notebooks/public/components/notebooks_button.tsx +++ b/x-pack/plugins/search_notebooks/public/components/notebooks_button.tsx @@ -30,7 +30,7 @@ export const SearchNotebooksButton = ({ if (activeView) { return ( div { padding-bottom: 0; padding-top: 0; @@ -13,4 +9,4 @@ .serverlessSearchCloudDetailsCopyPanel { word-break: break-all; -} \ No newline at end of file +} diff --git a/x-pack/plugins/serverless_search/public/application/components/overview.tsx b/x-pack/plugins/serverless_search/public/application/components/overview.tsx index 678eadb6b5cb..d20706a6aa80 100644 --- a/x-pack/plugins/serverless_search/public/application/components/overview.tsx +++ b/x-pack/plugins/serverless_search/public/application/components/overview.tsx @@ -14,7 +14,6 @@ import { EuiIcon, EuiPageTemplate, EuiPanel, - EuiText, EuiBadge, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -96,9 +95,7 @@ export const ElasticsearchOverview = () => { return ( - - - + { "allowFeatureVisibility": true, "allowSolutionVisibility": true, "enabled": true, - "experimental": Object { - "forceSolutionVisibility": false, - }, "maxSpaces": 1000, } `); @@ -35,9 +32,6 @@ describe('config schema', () => { "allowFeatureVisibility": true, "allowSolutionVisibility": true, "enabled": true, - "experimental": Object { - "forceSolutionVisibility": false, - }, "maxSpaces": 1000, } `); @@ -47,9 +41,6 @@ describe('config schema', () => { "allowFeatureVisibility": true, "allowSolutionVisibility": true, "enabled": true, - "experimental": Object { - "forceSolutionVisibility": false, - }, "maxSpaces": 1000, } `); diff --git a/x-pack/plugins/spaces/server/config.ts b/x-pack/plugins/spaces/server/config.ts index ef6b300d4396..a7c9606e7454 100644 --- a/x-pack/plugins/spaces/server/config.ts +++ b/x-pack/plugins/spaces/server/config.ts @@ -54,13 +54,6 @@ export const ConfigSchema = schema.object({ defaultValue: true, }), }), - experimental: schema.maybe( - offeringBasedSchema({ - traditional: schema.object({ - forceSolutionVisibility: schema.boolean({ defaultValue: false }), - }), - }) - ), }); export function createConfig$(context: PluginInitializerContext) { diff --git a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts index 509de14e2928..fcbc84b0655c 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts @@ -47,7 +47,7 @@ export function initCopyToSpacesApi(deps: ExternalRouteDeps) { tags: ['oas-tag:spaces'], summary: `Copy saved objects between spaces`, description: - 'It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved searches, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.', + 'It also allows you to automatically copy related objects, so when you copy a dashboard, this can automatically copy over the associated visualizations, data views, and saved Discover sessions, as required. You can request to overwrite any objects that already exist in the target space if they share an identifier or you can use the resolve copy saved objects conflicts API to do this on a per-object basis.', }, validate: { body: schema.object( diff --git a/x-pack/plugins/stack_connectors/common/crowdstrike/schema.ts b/x-pack/plugins/stack_connectors/common/crowdstrike/schema.ts index d5d4154f985e..40e58613c69e 100644 --- a/x-pack/plugins/stack_connectors/common/crowdstrike/schema.ts +++ b/x-pack/plugins/stack_connectors/common/crowdstrike/schema.ts @@ -318,16 +318,16 @@ export const CrowdstrikeExecuteRTRResponseSchema = schema.object( schema.string(), schema.object( { - session_id: schema.maybe(schema.string()), - task_id: schema.maybe(schema.string()), - complete: schema.maybe(schema.boolean()), - stdout: schema.maybe(schema.string()), - stderr: schema.maybe(schema.string()), - base_command: schema.maybe(schema.string()), - aid: schema.maybe(schema.string()), - errors: schema.maybe(schema.arrayOf(schema.any())), - query_time: schema.maybe(schema.number()), - offline_queued: schema.maybe(schema.boolean()), + session_id: schema.string(), + task_id: schema.string(), + complete: schema.boolean(), + stdout: schema.string(), + stderr: schema.string(), + base_command: schema.string(), + aid: schema.string(), + errors: schema.arrayOf(schema.any()), + query_time: schema.number(), + offline_queued: schema.boolean(), }, { unknowns: 'allow' } ) @@ -337,9 +337,9 @@ export const CrowdstrikeExecuteRTRResponseSchema = schema.object( ), meta: schema.object( { - query_time: schema.maybe(schema.number()), - powered_by: schema.maybe(schema.string()), - trace_id: schema.maybe(schema.string()), + query_time: schema.number(), + powered_by: schema.string(), + trace_id: schema.string(), }, { unknowns: 'allow' } ), @@ -348,7 +348,5 @@ export const CrowdstrikeExecuteRTRResponseSchema = schema.object( { unknowns: 'allow' } ); -export type CrowdStrikeExecuteRTRResponse = typeof CrowdstrikeExecuteRTRResponseSchema; - // TODO: will be part of a next PR export const CrowdstrikeGetScriptsParamsSchema = schema.any({}); diff --git a/x-pack/plugins/stack_connectors/common/crowdstrike/types.ts b/x-pack/plugins/stack_connectors/common/crowdstrike/types.ts index 3c9cc15ea167..68f8275d7143 100644 --- a/x-pack/plugins/stack_connectors/common/crowdstrike/types.ts +++ b/x-pack/plugins/stack_connectors/common/crowdstrike/types.ts @@ -17,8 +17,8 @@ import { CrowdstrikeGetTokenResponseSchema, CrowdstrikeGetAgentsResponseSchema, RelaxedCrowdstrikeBaseApiResponseSchema, - CrowdstrikeInitRTRResponseSchema, CrowdstrikeInitRTRParamsSchema, + CrowdstrikeExecuteRTRResponseSchema, } from './schema'; export type CrowdstrikeConfig = TypeOf; @@ -35,9 +35,10 @@ export type CrowdstrikeGetAgentOnlineStatusResponse = TypeOf< typeof CrowdstrikeGetAgentOnlineStatusResponseSchema >; export type CrowdstrikeGetTokenResponse = TypeOf; -export type CrowdstrikeInitRTRResponse = TypeOf; export type CrowdstrikeHostActionsParams = TypeOf; export type CrowdstrikeActionParams = TypeOf; export type CrowdstrikeInitRTRParams = TypeOf; + +export type CrowdStrikeExecuteRTRResponse = TypeOf; diff --git a/x-pack/plugins/stack_connectors/common/inference/constants.ts b/x-pack/plugins/stack_connectors/common/inference/constants.ts index b795e54f5d32..c2f2e6713270 100644 --- a/x-pack/plugins/stack_connectors/common/inference/constants.ts +++ b/x-pack/plugins/stack_connectors/common/inference/constants.ts @@ -32,6 +32,9 @@ export enum ServiceProviderKeys { export const INFERENCE_CONNECTOR_ID = '.inference'; export enum SUB_ACTION { + UNIFIED_COMPLETION_ASYNC_ITERATOR = 'unified_completion_async_iterator', + UNIFIED_COMPLETION_STREAM = 'unified_completion_stream', + UNIFIED_COMPLETION = 'unified_completion', COMPLETION = 'completion', RERANK = 'rerank', TEXT_EMBEDDING = 'text_embedding', diff --git a/x-pack/plugins/stack_connectors/common/inference/schema.ts b/x-pack/plugins/stack_connectors/common/inference/schema.ts index 07b51cf9a5aa..c62e9782bb51 100644 --- a/x-pack/plugins/stack_connectors/common/inference/schema.ts +++ b/x-pack/plugins/stack_connectors/common/inference/schema.ts @@ -23,6 +23,176 @@ export const ChatCompleteParamsSchema = schema.object({ input: schema.string(), }); +// subset of OpenAI.ChatCompletionMessageParam https://github.com/openai/openai-node/blob/master/src/resources/chat/completions.ts +const AIMessage = schema.object({ + role: schema.string(), + content: schema.maybe(schema.string()), + name: schema.maybe(schema.string()), + tool_calls: schema.maybe( + schema.arrayOf( + schema.object({ + id: schema.string(), + function: schema.object({ + arguments: schema.maybe(schema.string()), + name: schema.maybe(schema.string()), + }), + type: schema.string(), + }) + ) + ), + tool_call_id: schema.maybe(schema.string()), +}); + +const AITool = schema.object({ + type: schema.string(), + function: schema.object({ + name: schema.string(), + description: schema.maybe(schema.string()), + parameters: schema.maybe(schema.recordOf(schema.string(), schema.any())), + }), +}); + +// subset of OpenAI.ChatCompletionCreateParamsBase https://github.com/openai/openai-node/blob/master/src/resources/chat/completions.ts +export const UnifiedChatCompleteParamsSchema = schema.object({ + body: schema.object({ + messages: schema.arrayOf(AIMessage, { defaultValue: [] }), + model: schema.maybe(schema.string()), + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the chat + * completion. This value can be used to control + * [costs](https://openai.com/api/pricing/) for text generated via API. + * + * This value is now deprecated in favor of `max_completion_tokens`, and is not + * compatible with + * [o1 series models](https://platform.openai.com/docs/guides/reasoning). + */ + max_tokens: schema.maybe(schema.number()), + /** + * Developer-defined tags and values used for filtering completions in the + * [dashboard](https://platform.openai.com/chat-completions). + */ + metadata: schema.maybe(schema.recordOf(schema.string(), schema.string())), + /** + * How many chat completion choices to generate for each input message. Note that + * you will be charged based on the number of generated tokens across all of the + * choices. Keep `n` as `1` to minimize costs. + */ + n: schema.maybe(schema.number()), + /** + * Up to 4 sequences where the API will stop generating further tokens. + */ + stop: schema.maybe( + schema.nullable(schema.oneOf([schema.string(), schema.arrayOf(schema.string())])) + ), + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature: schema.maybe(schema.number()), + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tool and instead generates a message. `auto` means the model can + * pick between generating a message or calling one or more tools. `required` means + * the model must call one or more tools. Specifying a particular tool via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + * + * `none` is the default when no tools are present. `auto` is the default if tools + * are present. + */ + tool_choice: schema.maybe( + schema.oneOf([ + schema.string(), + schema.object({ + type: schema.string(), + function: schema.object({ + name: schema.string(), + }), + }), + ]) + ), + /** + * A list of tools the model may call. Currently, only functions are supported as a + * tool. Use this to provide a list of functions the model may generate JSON inputs + * for. A max of 128 functions are supported. + */ + tools: schema.maybe(schema.arrayOf(AITool)), + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p: schema.maybe(schema.number()), + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user: schema.maybe(schema.string()), + }), + // abort signal from client + signal: schema.maybe(schema.any()), +}); + +export const UnifiedChatCompleteResponseSchema = schema.object({ + id: schema.string(), + choices: schema.arrayOf( + schema.object({ + finish_reason: schema.maybe( + schema.nullable( + schema.oneOf([ + schema.literal('stop'), + schema.literal('length'), + schema.literal('tool_calls'), + schema.literal('content_filter'), + schema.literal('function_call'), + ]) + ) + ), + index: schema.maybe(schema.number()), + message: schema.object({ + content: schema.maybe(schema.nullable(schema.string())), + refusal: schema.maybe(schema.nullable(schema.string())), + role: schema.maybe(schema.string()), + tool_calls: schema.maybe( + schema.arrayOf( + schema.object({ + id: schema.maybe(schema.string()), + index: schema.maybe(schema.number()), + function: schema.maybe( + schema.object({ + arguments: schema.maybe(schema.string()), + name: schema.maybe(schema.string()), + }) + ), + type: schema.maybe(schema.string()), + }), + { defaultValue: [] } + ) + ), + }), + }), + { defaultValue: [] } + ), + created: schema.maybe(schema.number()), + model: schema.maybe(schema.string()), + object: schema.maybe(schema.string()), + usage: schema.maybe( + schema.nullable( + schema.object({ + completion_tokens: schema.maybe(schema.number()), + prompt_tokens: schema.maybe(schema.number()), + total_tokens: schema.maybe(schema.number()), + }) + ) + ), +}); + export const ChatCompleteResponseSchema = schema.arrayOf( schema.object({ result: schema.string(), @@ -66,3 +236,12 @@ export const TextEmbeddingResponseSchema = schema.arrayOf( ); export const StreamingResponseSchema = schema.stream(); + +// Run action schema +export const DashboardActionParamsSchema = schema.object({ + dashboardId: schema.string(), +}); + +export const DashboardActionResponseSchema = schema.object({ + available: schema.boolean(), +}); diff --git a/x-pack/plugins/stack_connectors/common/inference/types.ts b/x-pack/plugins/stack_connectors/common/inference/types.ts index d8b846ce1942..1593429792e0 100644 --- a/x-pack/plugins/stack_connectors/common/inference/types.ts +++ b/x-pack/plugins/stack_connectors/common/inference/types.ts @@ -18,12 +18,19 @@ import { SparseEmbeddingResponseSchema, TextEmbeddingParamsSchema, TextEmbeddingResponseSchema, + UnifiedChatCompleteParamsSchema, + UnifiedChatCompleteResponseSchema, + DashboardActionParamsSchema, + DashboardActionResponseSchema, } from './schema'; import { ConfigProperties } from '../dynamic_config/types'; export type Config = TypeOf; export type Secrets = TypeOf; +export type UnifiedChatCompleteParams = TypeOf; +export type UnifiedChatCompleteResponse = TypeOf; + export type ChatCompleteParams = TypeOf; export type ChatCompleteResponse = TypeOf; @@ -38,6 +45,9 @@ export type TextEmbeddingResponse = TypeOf; export type StreamingResponse = TypeOf; +export type DashboardActionParams = TypeOf; +export type DashboardActionResponse = TypeOf; + export type FieldsConfiguration = Record; export interface InferenceProvider { diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/constants.tsx b/x-pack/plugins/stack_connectors/public/connector_types/inference/constants.tsx index 8427caaf49ff..1b635ca8fe88 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/constants.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/constants.tsx @@ -25,13 +25,27 @@ export const DEFAULT_TEXT_EMBEDDING_BODY = { inputType: 'ingest', }; +export const DEFAULT_UNIFIED_CHAT_COMPLETE_BODY = { + body: { + messages: [ + { + role: 'user', + content: 'Hello world', + }, + ], + }, +}; + export const DEFAULTS_BY_TASK_TYPE: Record = { [SUB_ACTION.COMPLETION]: DEFAULT_CHAT_COMPLETE_BODY, + [SUB_ACTION.UNIFIED_COMPLETION]: DEFAULT_UNIFIED_CHAT_COMPLETE_BODY, + [SUB_ACTION.UNIFIED_COMPLETION_STREAM]: DEFAULT_UNIFIED_CHAT_COMPLETE_BODY, + [SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR]: DEFAULT_UNIFIED_CHAT_COMPLETE_BODY, [SUB_ACTION.RERANK]: DEFAULT_RERANK_BODY, [SUB_ACTION.SPARSE_EMBEDDING]: DEFAULT_SPARSE_EMBEDDING_BODY, [SUB_ACTION.TEXT_EMBEDDING]: DEFAULT_TEXT_EMBEDDING_BODY, }; -export const DEFAULT_TASK_TYPE = 'completion'; +export const DEFAULT_TASK_TYPE = 'unified_completion'; export const DEFAULT_PROVIDER = 'elasticsearch'; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.test.tsx index 76dc50a316e6..b67264674aeb 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.test.tsx @@ -44,8 +44,16 @@ describe('OpenAI action params validation', () => { subActionParams: { input: ['message test'], query: 'foobar' }, }, { - subAction: SUB_ACTION.COMPLETION, - subActionParams: { input: 'message test' }, + subAction: SUB_ACTION.UNIFIED_COMPLETION, + subActionParams: { body: { messages: [{ role: 'user', content: 'What is Elastic?' }] } }, + }, + { + subAction: SUB_ACTION.UNIFIED_COMPLETION_STREAM, + subActionParams: { body: { messages: [{ role: 'user', content: 'What is Elastic?' }] } }, + }, + { + subAction: SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR, + subActionParams: { body: { messages: [{ role: 'user', content: 'What is Elastic?' }] } }, }, { subAction: SUB_ACTION.TEXT_EMBEDDING, @@ -55,6 +63,10 @@ describe('OpenAI action params validation', () => { subAction: SUB_ACTION.SPARSE_EMBEDDING, subActionParams: { input: 'message test' }, }, + { + subAction: SUB_ACTION.COMPLETION, + subActionParams: { input: 'message test' }, + }, ])( 'validation succeeds when params are valid for subAction $subAction', async ({ subAction, subActionParams }) => { @@ -63,19 +75,25 @@ describe('OpenAI action params validation', () => { subActionParams, }; expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { input: [], subAction: [], inputType: [], query: [] }, + errors: { body: [], input: [], subAction: [], inputType: [], query: [] }, }); } ); test('params validation fails when params is a wrong object', async () => { const actionParams = { - subAction: SUB_ACTION.COMPLETION, + subAction: SUB_ACTION.UNIFIED_COMPLETION, subActionParams: { body: 'message {test}' }, }; expect(await actionTypeModel.validateParams(actionParams)).toEqual({ - errors: { input: ['Input is required.'], inputType: [], query: [], subAction: [] }, + errors: { + body: ['Messages is required.'], + inputType: [], + query: [], + subAction: [], + input: [], + }, }); }); @@ -86,6 +104,7 @@ describe('OpenAI action params validation', () => { expect(await actionTypeModel.validateParams(actionParams)).toEqual({ errors: { + body: [], input: [], inputType: [], query: [], @@ -102,6 +121,7 @@ describe('OpenAI action params validation', () => { expect(await actionTypeModel.validateParams(actionParams)).toEqual({ errors: { + body: [], input: [], inputType: [], query: [], @@ -118,6 +138,7 @@ describe('OpenAI action params validation', () => { expect(await actionTypeModel.validateParams(actionParams)).toEqual({ errors: { + body: [], input: ['Input is required.', 'Input does not have a valid Array format.'], inputType: [], query: ['Query is required.'], @@ -134,6 +155,7 @@ describe('OpenAI action params validation', () => { expect(await actionTypeModel.validateParams(actionParams)).toEqual({ errors: { + body: [], input: [], inputType: ['Input type is required.'], query: [], diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.tsx b/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.tsx index e16d03306c16..388da0556801 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/inference.tsx @@ -19,6 +19,7 @@ import { InferenceActionParams, InferenceConnector } from './types'; interface ValidationErrors { subAction: string[]; input: string[]; + body: string[]; // rerank only query: string[]; // text_embedding only @@ -40,14 +41,28 @@ export function getConnectorType(): InferenceConnector { const translations = await import('./translations'); const errors: ValidationErrors = { input: [], + body: [], subAction: [], inputType: [], query: [], }; if ( - subAction === SUB_ACTION.RERANK || + subAction === SUB_ACTION.UNIFIED_COMPLETION || + subAction === SUB_ACTION.UNIFIED_COMPLETION_STREAM || + subAction === SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR + ) { + if ( + !Array.isArray(subActionParams.body.messages) || + !subActionParams.body.messages.length + ) { + errors.body.push(translations.getRequiredMessage('Messages')); + } + } + + if ( subAction === SUB_ACTION.COMPLETION || + subAction === SUB_ACTION.RERANK || subAction === SUB_ACTION.TEXT_EMBEDDING || subAction === SUB_ACTION.SPARSE_EMBEDDING ) { @@ -76,10 +91,13 @@ export function getConnectorType(): InferenceConnector { errors.subAction.push(translations.getRequiredMessage('Action')); } else if ( ![ - SUB_ACTION.COMPLETION, + SUB_ACTION.UNIFIED_COMPLETION, + SUB_ACTION.UNIFIED_COMPLETION_STREAM, + SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR, SUB_ACTION.SPARSE_EMBEDDING, SUB_ACTION.RERANK, SUB_ACTION.TEXT_EMBEDDING, + SUB_ACTION.COMPLETION, ].includes(subAction) ) { errors.subAction.push(translations.INVALID_ACTION); diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/params.test.tsx b/x-pack/plugins/stack_connectors/public/connector_types/inference/params.test.tsx index 49773edc2246..ba094ec64f6b 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/params.test.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/params.test.tsx @@ -15,8 +15,8 @@ describe('Inference Params Fields renders', () => { const { getByTestId } = render( { index={0} /> ); - expect(getByTestId('inferenceInput')).toBeInTheDocument(); - expect(getByTestId('inferenceInput')).toHaveProperty('value', 'What is Elastic?'); + expect(getByTestId('inference-bodyJsonEditor')).toBeInTheDocument(); + expect(getByTestId('bodyJsonEditor')).toHaveProperty( + 'value', + `{\"messages\":[{\"role\":\"user\",\"content\":\"What is Elastic?\"}]}` + ); }); test.each(['openai', 'googleaistudio'])( @@ -76,15 +79,25 @@ describe('Inference Params Fields renders', () => { /> ); expect(editAction).toHaveBeenCalledTimes(2); - expect(editAction).toHaveBeenCalledWith('subAction', SUB_ACTION.COMPLETION, 0); if (provider === 'openai') { + expect(editAction).toHaveBeenCalledWith('subAction', SUB_ACTION.UNIFIED_COMPLETION, 0); expect(editAction).toHaveBeenCalledWith( 'subActionParams', - { input: 'What is Elastic?' }, + { + body: { + messages: [ + { + content: 'Hello world', + role: 'user', + }, + ], + }, + }, 0 ); } if (provider === 'googleaistudio') { + expect(editAction).toHaveBeenCalledWith('subAction', SUB_ACTION.COMPLETION, 0); expect(editAction).toHaveBeenCalledWith( 'subActionParams', { input: 'What is Elastic?' }, diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/params.tsx b/x-pack/plugins/stack_connectors/public/connector_types/inference/params.tsx index c24fff24c33f..be162e70493b 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/params.tsx +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/params.tsx @@ -12,11 +12,13 @@ import { } from '@kbn/triggers-actions-ui-plugin/public'; import { EuiTextArea, EuiFormRow, EuiSpacer, EuiSelect } from '@elastic/eui'; import type { RuleFormParamsErrors } from '@kbn/response-ops-rule-form'; +import { ActionVariable } from '@kbn/alerting-types'; import { ChatCompleteParams, RerankParams, SparseEmbeddingParams, TextEmbeddingParams, + UnifiedChatCompleteParams, } from '../../../common/inference/types'; import { DEFAULTS_BY_TASK_TYPE } from './constants'; import * as i18n from './translations'; @@ -25,28 +27,38 @@ import { InferenceActionConnector, InferenceActionParams } from './types'; const InferenceServiceParamsFields: React.FunctionComponent< ActionParamsProps -> = ({ actionParams, editAction, index, errors, actionConnector }) => { +> = ({ actionParams, editAction, index, errors, actionConnector, messageVariables }) => { const { subAction, subActionParams } = actionParams; - const { taskType } = (actionConnector as unknown as InferenceActionConnector).config; + const { taskType, provider } = (actionConnector as unknown as InferenceActionConnector).config; useEffect(() => { if (!subAction) { - editAction('subAction', taskType, index); + editAction( + 'subAction', + provider === 'openai' && taskType === 'completion' + ? SUB_ACTION.UNIFIED_COMPLETION + : taskType, + index + ); } - }, [editAction, index, subAction, taskType]); + }, [editAction, index, provider, subAction, taskType]); useEffect(() => { if (!subActionParams) { editAction( 'subActionParams', { - ...(DEFAULTS_BY_TASK_TYPE[taskType] ?? {}), + ...(DEFAULTS_BY_TASK_TYPE[ + provider === 'openai' && taskType === 'completion' + ? SUB_ACTION.UNIFIED_COMPLETION + : taskType + ] ?? {}), }, index ); } - }, [editAction, index, subActionParams, taskType]); + }, [editAction, index, provider, subActionParams, taskType]); const editSubActionParams = useCallback( (params: Partial) => { @@ -55,6 +67,28 @@ const InferenceServiceParamsFields: React.FunctionComponent< [editAction, index, subActionParams] ); + if (subAction === SUB_ACTION.UNIFIED_COMPLETION) { + return ( + + ); + } + + if (subAction === SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR) { + return ( + + ); + } + if (subAction === SUB_ACTION.COMPLETION) { return ( ) => void; + messageVariables: ActionVariable[] | undefined; +}> = ({ subActionParams, editSubActionParams, errors, messageVariables }) => { + const { body } = subActionParams ?? {}; + + return ( + <> + { + editSubActionParams({ body: JSON.parse(json) }); + }} + onBlur={() => { + if (!subActionParams.body) { + editSubActionParams({ body: { messages: [] } }); + } + }} + dataTestSubj="inference-bodyJsonEditor" + /> + + ); +}; + const CompletionParamsFields: React.FunctionComponent<{ subActionParams: ChatCompleteParams; errors: RuleFormParamsErrors; diff --git a/x-pack/plugins/stack_connectors/public/connector_types/inference/types.ts b/x-pack/plugins/stack_connectors/public/connector_types/inference/types.ts index 1bd55793bc46..1756e213a1a7 100644 --- a/x-pack/plugins/stack_connectors/public/connector_types/inference/types.ts +++ b/x-pack/plugins/stack_connectors/public/connector_types/inference/types.ts @@ -13,9 +13,16 @@ import { RerankParams, SparseEmbeddingParams, TextEmbeddingParams, + UnifiedChatCompleteParams, } from '../../../common/inference/types'; export type InferenceActionParams = + | { subAction: SUB_ACTION.UNIFIED_COMPLETION_STREAM; subActionParams: UnifiedChatCompleteParams } + | { subAction: SUB_ACTION.UNIFIED_COMPLETION; subActionParams: UnifiedChatCompleteParams } + | { + subAction: SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR; + subActionParams: UnifiedChatCompleteParams; + } | { subAction: SUB_ACTION.COMPLETION; subActionParams: ChatCompleteParams } | { subAction: SUB_ACTION.RERANK; subActionParams: RerankParams } | { subAction: SUB_ACTION.SPARSE_EMBEDDING; subActionParams: SparseEmbeddingParams } diff --git a/x-pack/plugins/stack_connectors/server/connector_types/crowdstrike/crowdstrike.ts b/x-pack/plugins/stack_connectors/server/connector_types/crowdstrike/crowdstrike.ts index 14b38b414eb3..9bc53c58aa19 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/crowdstrike/crowdstrike.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/crowdstrike/crowdstrike.ts @@ -22,6 +22,7 @@ import type { CrowdstrikeGetTokenResponse, CrowdstrikeGetAgentOnlineStatusResponse, RelaxedCrowdstrikeBaseApiResponse, + CrowdStrikeExecuteRTRResponse, } from '../../../common/crowdstrike/types'; import { CrowdstrikeHostActionsParamsSchema, @@ -31,7 +32,6 @@ import { CrowdstrikeRTRCommandParamsSchema, CrowdstrikeExecuteRTRResponseSchema, CrowdstrikeGetScriptsParamsSchema, - CrowdStrikeExecuteRTRResponse, CrowdstrikeApiDoNotValidateResponsesSchema, CrowdstrikeGetTokenResponseSchema, } from '../../../common/crowdstrike/schema'; @@ -292,15 +292,9 @@ export class CrowdstrikeConnector extends SubActionConnector< payload: { command: string; endpoint_ids: string[]; - overwriteUrl?: 'batchExecuteRTR' | 'batchActiveResponderExecuteRTR' | 'batchAdminExecuteRTR'; }, connectorUsageCollector: ConnectorUsageCollector ): Promise => { - // Some commands are only available in specific API endpoints, however there's an additional requirement check for the command's argument - // Eg. runscript command is available with the batchExecuteRTR endpoint, but if it goes with --Raw parameter, it should go to batchAdminExecuteRTR endpoint - // This overwrite value will be coming from kibana response actions api - const csUrl = payload.overwriteUrl ? this.urls[payload.overwriteUrl] : url; - const batchId = await this.crowdStrikeSessionManager.initializeSession( { endpoint_ids: payload.endpoint_ids }, connectorUsageCollector @@ -313,7 +307,7 @@ export class CrowdstrikeConnector extends SubActionConnector< } return await this.crowdstrikeApiRequest( { - url: csUrl, + url, method: 'post', data: { base_command: baseCommand, @@ -335,7 +329,6 @@ export class CrowdstrikeConnector extends SubActionConnector< payload: { command: string; endpoint_ids: string[]; - overwriteUrl?: 'batchActiveResponderExecuteRTR' | 'batchAdminExecuteRTR'; }, connectorUsageCollector: ConnectorUsageCollector ): Promise { @@ -351,7 +344,6 @@ export class CrowdstrikeConnector extends SubActionConnector< payload: { command: string; endpoint_ids: string[]; - overwriteUrl?: 'batchAdminExecuteRTR'; }, connectorUsageCollector: ConnectorUsageCollector ): Promise { diff --git a/x-pack/plugins/stack_connectors/server/connector_types/inference/helpers.ts b/x-pack/plugins/stack_connectors/server/connector_types/inference/helpers.ts new file mode 100644 index 000000000000..7c6bfab9c639 --- /dev/null +++ b/x-pack/plugins/stack_connectors/server/connector_types/inference/helpers.ts @@ -0,0 +1,111 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { last, lastValueFrom, map, merge, Observable, scan, share } from 'rxjs'; +import type { Readable } from 'node:stream'; +import { createParser } from 'eventsource-parser'; +import { UnifiedChatCompleteResponse } from '../../../common/inference/types'; + +// TODO: Extract to the common package with appex-ai +export function eventSourceStreamIntoObservable(readable: Readable) { + return new Observable((subscriber) => { + const parser = createParser({ + onEvent: (event) => { + subscriber.next(event.data); + }, + }); + + async function processStream() { + for await (const chunk of readable) { + parser.feed(chunk.toString()); + } + } + + processStream().then( + () => { + subscriber.complete(); + }, + (error) => { + subscriber.error(error); + } + ); + }); +} + +export function chunksIntoMessage(obs$: Observable) { + const shared$ = obs$.pipe(share()); + + return lastValueFrom( + merge( + shared$, + shared$.pipe( + scan( + (prev, chunk) => { + if (chunk.choices.length > 0 && !chunk.usage) { + prev.choices[0].message.content += chunk.choices[0].message.content ?? ''; + + chunk.choices[0].message.tool_calls?.forEach((toolCall) => { + if (toolCall.index !== undefined) { + const prevToolCallLength = prev.choices[0].message.tool_calls?.length ?? 0; + if (prevToolCallLength - 1 !== toolCall.index) { + if (!prev.choices[0].message.tool_calls) { + prev.choices[0].message.tool_calls = []; + } + prev.choices[0].message.tool_calls.push({ + function: { + name: '', + arguments: '', + }, + id: '', + }); + } + const prevToolCall = prev.choices[0].message.tool_calls[toolCall.index]; + + if (toolCall.function?.name) { + prevToolCall.function.name += toolCall.function?.name; + } + if (toolCall.function?.arguments) { + prevToolCall.function.arguments += toolCall.function?.arguments; + } + if (toolCall.id) { + prevToolCall.id += toolCall.id; + } + if (toolCall.type) { + prevToolCall.type = toolCall.type; + } + } + }); + } else if (chunk.usage) { + prev.usage = chunk.usage; + } + return { ...prev, id: chunk.id, model: chunk.model }; + }, + { + choices: [ + { + message: { + content: '', + role: 'assistant', + }, + }, + ], + object: 'chat.completion', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any + ), + last(), + map((concatenatedChunk): UnifiedChatCompleteResponse => { + // TODO: const validatedToolCalls = validateToolCalls(concatenatedChunk.choices[0].message.tool_calls); + if (concatenatedChunk.choices[0].message.content === '') { + concatenatedChunk.choices[0].message.content = null; + } + return concatenatedChunk; + }) + ) + ) + ); +} diff --git a/x-pack/plugins/stack_connectors/server/connector_types/inference/index.ts b/x-pack/plugins/stack_connectors/server/connector_types/inference/index.ts index 18af48bc18a5..5af6773d15fe 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/inference/index.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/inference/index.ts @@ -161,7 +161,10 @@ export const configValidator = (configObject: Config, validatorServices: Validat ); } - if (!Object.keys(SUB_ACTION).includes(taskType.toUpperCase())) { + if ( + !taskType.includes('completion') && + !Object.keys(SUB_ACTION).includes(taskType.toUpperCase()) + ) { throw new Error( `Task type is not supported${ taskType && taskType.length ? `: ${taskType}` : `` diff --git a/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.test.ts b/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.test.ts index a79bd0360598..4aa28d2952db 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.test.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.test.ts @@ -9,7 +9,7 @@ import { InferenceConnector } from './inference'; import { actionsConfigMock } from '@kbn/actions-plugin/server/actions_config.mock'; import { loggingSystemMock } from '@kbn/core-logging-server-mocks'; import { actionsMock } from '@kbn/actions-plugin/server/mocks'; -import { PassThrough, Transform } from 'stream'; +import { Readable, Transform } from 'stream'; import {} from '@kbn/actions-plugin/server/types'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { InferenceInferenceResponse } from '@elastic/elasticsearch/lib/api/types'; @@ -29,7 +29,7 @@ describe('InferenceConnector', () => { ], }; - describe('performApiCompletion', () => { + describe('performApiUnifiedCompletion', () => { const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser; beforeEach(() => { @@ -60,28 +60,44 @@ describe('InferenceConnector', () => { }); it('uses the completion task_type is supplied', async () => { - const response = await connector.performApiCompletion({ - input: 'What is Elastic?', + const stream = Readable.from([ + `data: {"id":"chatcmpl-AbLKRuRMZCAcMMQdl96KMTUgAfZNg","choices":[{"delta":{"content":" you"},"index":0}],"model":"gpt-4o-2024-08-06","object":"chat.completion.chunk"}\n\n`, + `data: [DONE]\n\n`, + ]); + mockEsClient.transport.request.mockResolvedValue(stream); + + const response = await connector.performApiUnifiedCompletion({ + body: { messages: [{ content: 'What is Elastic?', role: 'user' }] }, }); - expect(mockEsClient.inference.inference).toBeCalledTimes(1); - expect(mockEsClient.inference.inference).toHaveBeenCalledWith( + expect(mockEsClient.transport.request).toBeCalledTimes(1); + expect(mockEsClient.transport.request).toHaveBeenCalledWith( { - inference_id: 'test', - input: 'What is Elastic?', - task_type: 'completion', + body: { + messages: [ + { + content: 'What is Elastic?', + role: 'user', + }, + ], + n: undefined, + }, + method: 'POST', + path: '_inference/completion/test/_unified', }, - { asStream: false } + { asStream: true } ); - expect(response).toEqual(mockResponse.completion); + expect(response.choices[0].message.content).toEqual(' you'); }); it('errors during API calls are properly handled', async () => { // @ts-ignore - mockEsClient.inference.inference = mockError; + mockEsClient.transport.request = mockError; - await expect(connector.performApiCompletion({ input: 'What is Elastic?' })).rejects.toThrow( - 'API Error' - ); + await expect( + connector.performApiUnifiedCompletion({ + body: { messages: [{ content: 'What is Elastic?', role: 'user' }] }, + }) + ).rejects.toThrow('API Error'); }); }); @@ -223,6 +239,7 @@ describe('InferenceConnector', () => { }; beforeEach(() => { + jest.clearAllMocks(); // @ts-ignore mockStream(); }); @@ -238,7 +255,7 @@ describe('InferenceConnector', () => { }, provider: 'elasticsearch', taskType: 'completion', - inferenceId: '', + inferenceId: 'test', taskTypeConfig: {}, }, secrets: { providerSecrets: {} }, @@ -247,13 +264,23 @@ describe('InferenceConnector', () => { }); it('the API call is successful with correct request parameters', async () => { - await connector.performApiCompletionStream({ input: 'Hello world' }); - expect(mockEsClient.inference.inference).toBeCalledTimes(1); - expect(mockEsClient.inference.inference).toHaveBeenCalledWith( + await connector.performApiUnifiedCompletionStream({ + body: { messages: [{ content: 'Hello world', role: 'user' }] }, + }); + expect(mockEsClient.transport.request).toBeCalledTimes(1); + expect(mockEsClient.transport.request).toHaveBeenCalledWith( { - inference_id: '', - input: 'Hello world', - task_type: 'completion', + body: { + messages: [ + { + content: 'Hello world', + role: 'user', + }, + ], + n: undefined, + }, + method: 'POST', + path: '_inference/completion/test/_unified', }, { asStream: true } ); @@ -261,32 +288,42 @@ describe('InferenceConnector', () => { it('signal is properly passed to streamApi', async () => { const signal = jest.fn() as unknown as AbortSignal; - await connector.performApiCompletionStream({ input: 'Hello world', signal }); + await connector.performApiUnifiedCompletionStream({ + body: { messages: [{ content: 'Hello world', role: 'user' }] }, + signal, + }); - expect(mockEsClient.inference.inference).toHaveBeenCalledWith( + expect(mockEsClient.transport.request).toHaveBeenCalledWith( { - inference_id: '', - input: 'Hello world', - task_type: 'completion', + body: { messages: [{ content: 'Hello world', role: 'user' }], n: undefined }, + method: 'POST', + path: '_inference/completion/test/_unified', }, - { asStream: true, signal } + { asStream: true } ); }); it('errors during API calls are properly handled', async () => { // @ts-ignore - mockEsClient.inference.inference = mockError; + mockEsClient.transport.request = mockError; await expect( - connector.performApiCompletionStream({ input: 'What is Elastic?' }) + connector.performApiUnifiedCompletionStream({ + body: { messages: [{ content: 'What is Elastic?', role: 'user' }] }, + }) ).rejects.toThrow('API Error'); }); it('responds with a readable stream', async () => { - const response = await connector.performApiCompletionStream({ - input: 'What is Elastic?', + const stream = Readable.from([ + `data: {"id":"chatcmpl-AbLKRuRMZCAcMMQdl96KMTUgAfZNg","choices":[{"delta":{"content":" you"},"index":0}],"model":"gpt-4o-2024-08-06","object":"chat.completion.chunk"}\n\n`, + `data: [DONE]\n\n`, + ]); + mockEsClient.transport.request.mockResolvedValue(stream); + const response = await connector.performApiUnifiedCompletionStream({ + body: { messages: [{ content: 'What is Elastic?', role: 'user' }] }, }); - expect(response instanceof PassThrough).toEqual(true); + expect(response instanceof Readable).toEqual(true); }); }); }); diff --git a/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.ts b/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.ts index d9aa4bf044e1..d6c9af0e1365 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/inference/inference.ts @@ -6,36 +6,44 @@ */ import { ServiceParams, SubActionConnector } from '@kbn/actions-plugin/server'; - -import { PassThrough, Stream } from 'stream'; -import { IncomingMessage } from 'http'; +import { Stream } from 'openai/streaming'; +import { Readable } from 'stream'; import { AxiosError } from 'axios'; import { InferenceInferenceRequest, InferenceInferenceResponse, - InferenceTaskType, } from '@elastic/elasticsearch/lib/api/types'; +import { ConnectorUsageCollector } from '@kbn/actions-plugin/server/usage'; +import { filter, from, identity, map, mergeMap, Observable, tap } from 'rxjs'; +import OpenAI from 'openai'; +import { ChatCompletionChunk } from 'openai/resources'; import { ChatCompleteParamsSchema, RerankParamsSchema, SparseEmbeddingParamsSchema, TextEmbeddingParamsSchema, + UnifiedChatCompleteParamsSchema, } from '../../../common/inference/schema'; import { Config, Secrets, - ChatCompleteParams, - ChatCompleteResponse, - StreamingResponse, RerankParams, RerankResponse, SparseEmbeddingParams, SparseEmbeddingResponse, TextEmbeddingParams, TextEmbeddingResponse, + UnifiedChatCompleteParams, + UnifiedChatCompleteResponse, + DashboardActionParams, + DashboardActionResponse, + ChatCompleteParams, + ChatCompleteResponse, } from '../../../common/inference/types'; import { SUB_ACTION } from '../../../common/inference/constants'; +import { initDashboard } from '../lib/gen_ai/create_gen_ai_dashboard'; +import { chunksIntoMessage, eventSourceStreamIntoObservable } from './helpers'; export class InferenceConnector extends SubActionConnector { // Not using Axios @@ -60,10 +68,25 @@ export class InferenceConnector extends SubActionConnector { } private registerSubActions() { + // non-streaming unified completion task this.registerSubAction({ - name: SUB_ACTION.COMPLETION, - method: 'performApiCompletion', - schema: ChatCompleteParamsSchema, + name: SUB_ACTION.UNIFIED_COMPLETION, + method: 'performApiUnifiedCompletion', + schema: UnifiedChatCompleteParamsSchema, + }); + + // streaming unified completion task + this.registerSubAction({ + name: SUB_ACTION.UNIFIED_COMPLETION_STREAM, + method: 'performApiUnifiedCompletionStream', + schema: UnifiedChatCompleteParamsSchema, + }); + + // streaming unified completion task for langchain + this.registerSubAction({ + name: SUB_ACTION.UNIFIED_COMPLETION_ASYNC_ITERATOR, + method: 'performApiUnifiedCompletionAsyncIterator', + schema: UnifiedChatCompleteParamsSchema, }); this.registerSubAction({ @@ -85,8 +108,8 @@ export class InferenceConnector extends SubActionConnector { }); this.registerSubAction({ - name: SUB_ACTION.COMPLETION_STREAM, - method: 'performApiCompletionStream', + name: SUB_ACTION.COMPLETION, + method: 'performApiCompletion', schema: ChatCompleteParamsSchema, }); } @@ -96,16 +119,112 @@ export class InferenceConnector extends SubActionConnector { * @param input the text on which you want to perform the inference task. * @signal abort signal */ - public async performApiCompletion({ - input, - signal, - }: ChatCompleteParams & { signal?: AbortSignal }): Promise { - const response = await this.performInferenceApi( - { inference_id: this.inferenceId, input, task_type: 'completion' }, - false, - signal + public async performApiUnifiedCompletion( + params: UnifiedChatCompleteParams + ): Promise { + const res = await this.performApiUnifiedCompletionStream(params); + + const obs$ = from(eventSourceStreamIntoObservable(res as unknown as Readable)).pipe( + filter((line) => !!line && line !== '[DONE]'), + map((line) => { + return JSON.parse(line) as OpenAI.ChatCompletionChunk | { error: { message: string } }; + }), + tap((line) => { + if ('error' in line) { + throw new Error(line.error.message); + } + if ( + 'choices' in line && + line.choices.length && + line.choices[0].finish_reason === 'length' + ) { + throw new Error('createTokenLimitReachedError()'); + } + }), + filter((line): line is OpenAI.ChatCompletionChunk => { + return 'object' in line && line.object === 'chat.completion.chunk'; + }), + mergeMap((chunk): Observable => { + const events: UnifiedChatCompleteResponse[] = []; + events.push({ + choices: chunk.choices.map((c) => ({ + message: { + tool_calls: c.delta.tool_calls?.map((t) => ({ + index: t.index, + id: t.id, + function: t.function, + type: t.type, + })), + content: c.delta.content, + refusal: c.delta.refusal, + role: c.delta.role, + }, + finish_reason: c.finish_reason, + index: c.index, + })), + id: chunk.id, + model: chunk.model, + object: chunk.object, + usage: chunk.usage, + }); + return from(events); + }), + identity + ); + + return chunksIntoMessage(obs$); + } + + /** + * responsible for making a esClient inference method to perform chat completetion task endpoint and returning the service response data + * @param input the text on which you want to perform the inference task. + * @signal abort signal + */ + public async performApiUnifiedCompletionStream(params: UnifiedChatCompleteParams) { + return await this.esClient.transport.request( + { + method: 'POST', + path: `_inference/completion/${this.inferenceId}/_unified`, + body: { ...params.body, n: undefined }, // exclude n param for now, constant is used on the inference API side + }, + { + asStream: true, + } ); - return response.completion!; + } + + /** + * Streamed requests (langchain) + * @param params - the request body + * @returns { + * consumerStream: Stream; the result to be read/transformed on the server and sent to the client via Server Sent Events + * tokenCountStream: Stream; the result for token counting stream + * } + */ + public async performApiUnifiedCompletionAsyncIterator( + params: UnifiedChatCompleteParams & { signal?: AbortSignal }, + connectorUsageCollector: ConnectorUsageCollector + ): Promise<{ + consumerStream: Stream; + tokenCountStream: Stream; + }> { + try { + connectorUsageCollector.addRequestBodyBytes(undefined, params.body); + const res = await this.performApiUnifiedCompletionStream(params); + const controller = new AbortController(); + // splits the stream in two, one is used for the UI and other for token tracking + + const stream = Stream.fromSSEResponse( + { body: res } as unknown as Response, + controller + ); + const teed = stream.tee(); + return { consumerStream: teed[0], tokenCountStream: teed[1] }; + // since we do not use the sub action connector request method, we need to do our own error handling + } catch (e) { + const errorMessage = this.getResponseErrorMessage(e); + throw new Error(errorMessage); + } } /** @@ -198,35 +317,56 @@ export class InferenceConnector extends SubActionConnector { } } - private async streamAPI({ + /** + * responsible for making a esClient inference method to perform chat completetion task endpoint and returning the service response data + * @param input the text on which you want to perform the inference task. + * @signal abort signal + */ + public async performApiCompletion({ input, signal, - }: ChatCompleteParams & { signal?: AbortSignal }): Promise { + }: ChatCompleteParams & { signal?: AbortSignal }): Promise { const response = await this.performInferenceApi( - { inference_id: this.inferenceId, input, task_type: this.taskType as InferenceTaskType }, - true, + { inference_id: this.inferenceId, input, task_type: 'completion' }, + false, signal ); - - return (response as unknown as Stream).pipe(new PassThrough()); + return response.completion!; } /** - * takes input. It calls the streamApi method to make a - * request to the Inference API with the message. It then returns a Transform stream - * that pipes the response from the API through the transformToString function, - * which parses the proprietary response into a string of the response text alone - * @param input A message to be sent to the API - * @signal abort signal + * retrieves a dashboard from the Kibana server and checks if the + * user has the necessary privileges to access it. + * @param dashboardId The ID of the dashboard to retrieve. */ - public async performApiCompletionStream({ - input, - signal, - }: ChatCompleteParams & { signal?: AbortSignal }): Promise { - const res = (await this.streamAPI({ - input, - signal, - })) as unknown as IncomingMessage; - return res; + public async getDashboard({ + dashboardId, + }: DashboardActionParams): Promise { + const privilege = (await this.esClient.transport.request({ + path: '/_security/user/_has_privileges', + method: 'POST', + body: { + index: [ + { + names: ['.kibana-event-log-*'], + allow_restricted_indices: true, + privileges: ['read'], + }, + ], + }, + })) as { has_all_requested: boolean }; + + if (!privilege?.has_all_requested) { + return { available: false }; + } + + const response = await initDashboard({ + logger: this.logger, + savedObjectsClient: this.savedObjectsClient, + dashboardId, + genAIProvider: 'Inference', + }); + + return { available: response.success }; } } diff --git a/x-pack/plugins/task_manager/server/saved_objects/model_versions/task_model_versions.ts b/x-pack/plugins/task_manager/server/saved_objects/model_versions/task_model_versions.ts index 775b3ea2f8ca..a86aed7e358f 100644 --- a/x-pack/plugins/task_manager/server/saved_objects/model_versions/task_model_versions.ts +++ b/x-pack/plugins/task_manager/server/saved_objects/model_versions/task_model_versions.ts @@ -8,6 +8,10 @@ import { SavedObjectsModelVersionMap } from '@kbn/core-saved-objects-server'; import { taskSchemaV1, taskSchemaV2 } from '../schemas/task'; +// IMPORTANT!!! +// When adding new model versions, make sure to manually test +// downgrading to the previous version. This is a gap in our +// automated test coverage so manual testing is needed. export const taskModelVersions: SavedObjectsModelVersionMap = { '1': { changes: [ diff --git a/x-pack/plugins/task_manager/server/saved_objects/schemas/task.test.ts b/x-pack/plugins/task_manager/server/saved_objects/schemas/task.test.ts new file mode 100644 index 000000000000..709e50bc54bf --- /dev/null +++ b/x-pack/plugins/task_manager/server/saved_objects/schemas/task.test.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { validateDuration } from './task'; + +test('allows valid duration', () => { + expect(validateDuration('1s')).toBeUndefined(); + expect(validateDuration('45346s')).toBeUndefined(); + expect(validateDuration('10m')).toBeUndefined(); + expect(validateDuration('30000000h')).toBeUndefined(); + expect(validateDuration('3245d')).toBeUndefined(); +}); + +test('returns error message for invalid duration', () => { + expect(validateDuration('10x')).toBe('string is not a valid duration: 10x'); + expect(validateDuration('PT1M')).toBe('string is not a valid duration: PT1M'); + expect(validateDuration('foo')).toBe('string is not a valid duration: foo'); + expect(validateDuration('1 minute')).toBe('string is not a valid duration: 1 minute'); + expect(validateDuration('1hr')).toBe('string is not a valid duration: 1hr'); +}); diff --git a/x-pack/plugins/task_manager/server/saved_objects/schemas/task.ts b/x-pack/plugins/task_manager/server/saved_objects/schemas/task.ts index 2a6ee5c92198..25b6a1cb079d 100644 --- a/x-pack/plugins/task_manager/server/saved_objects/schemas/task.ts +++ b/x-pack/plugins/task_manager/server/saved_objects/schemas/task.ts @@ -6,6 +6,13 @@ */ import { schema } from '@kbn/config-schema'; +import { isInterval } from '../../lib/intervals'; + +export function validateDuration(duration: string) { + if (!isInterval(duration)) { + return 'string is not a valid duration: ' + duration; + } +} export const taskSchemaV1 = schema.object({ taskType: schema.string(), @@ -15,7 +22,7 @@ export const taskSchemaV1 = schema.object({ runAt: schema.string(), schedule: schema.maybe( schema.object({ - interval: schema.duration(), + interval: schema.string({ validate: validateDuration }), }) ), params: schema.string(), diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.test.ts index d0f1a39f7ced..f6b3d23c2e28 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.test.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.test.ts @@ -37,7 +37,28 @@ describe('getMutedAlerts', () => { Array [ "/internal/alerting/rules/_find", Object { - "body": "{\\"rule_type_ids\\":[\\"foo\\"],\\"fields\\":[\\"id\\",\\"mutedInstanceIds\\"],\\"page\\":1,\\"per_page\\":1}", + "body": "{\\"filter\\":\\"{\\\\\\"type\\\\\\":\\\\\\"function\\\\\\",\\\\\\"function\\\\\\":\\\\\\"is\\\\\\",\\\\\\"arguments\\\\\\":[{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert.id\\\\\\",\\\\\\"isQuoted\\\\\\":false},{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert:foo\\\\\\",\\\\\\"isQuoted\\\\\\":false}]}\\",\\"fields\\":[\\"id\\",\\"mutedInstanceIds\\"],\\"page\\":1,\\"per_page\\":1}", + "signal": undefined, + }, + ] + `); + }); + + test('should call find API with multiple ruleIds', async () => { + const result = await getMutedAlerts(http, { ruleIds: ['foo', 'bar'] }); + + expect(result).toEqual({ + page: 1, + per_page: 10, + total: 0, + data: [], + }); + + expect(http.post.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "/internal/alerting/rules/_find", + Object { + "body": "{\\"filter\\":\\"{\\\\\\"type\\\\\\":\\\\\\"function\\\\\\",\\\\\\"function\\\\\\":\\\\\\"or\\\\\\",\\\\\\"arguments\\\\\\":[{\\\\\\"type\\\\\\":\\\\\\"function\\\\\\",\\\\\\"function\\\\\\":\\\\\\"is\\\\\\",\\\\\\"arguments\\\\\\":[{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert.id\\\\\\",\\\\\\"isQuoted\\\\\\":false},{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert:foo\\\\\\",\\\\\\"isQuoted\\\\\\":false}]},{\\\\\\"type\\\\\\":\\\\\\"function\\\\\\",\\\\\\"function\\\\\\":\\\\\\"is\\\\\\",\\\\\\"arguments\\\\\\":[{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert.id\\\\\\",\\\\\\"isQuoted\\\\\\":false},{\\\\\\"type\\\\\\":\\\\\\"literal\\\\\\",\\\\\\"value\\\\\\":\\\\\\"alert:bar\\\\\\",\\\\\\"isQuoted\\\\\\":false}]}]}\\",\\"fields\\":[\\"id\\",\\"mutedInstanceIds\\"],\\"page\\":1,\\"per_page\\":2}", "signal": undefined, }, ] diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.ts b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.ts index d9baef548daf..4c13c0c7b5ef 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/apis/get_rules_muted_alerts.ts @@ -6,6 +6,7 @@ */ import { HttpStart } from '@kbn/core-http-browser'; +import { nodeBuilder } from '@kbn/es-query'; const INTERNAL_FIND_RULES_URL = '/internal/alerting/rules/_find'; @@ -23,9 +24,12 @@ export const getMutedAlerts = async ( params: { ruleIds: string[] }, signal?: AbortSignal ) => { + const filterNode = nodeBuilder.or( + params.ruleIds.map((id) => nodeBuilder.is('alert.id', `alert:${id}`)) + ); return http.post(INTERNAL_FIND_RULES_URL, { body: JSON.stringify({ - rule_type_ids: params.ruleIds, + filter: JSON.stringify(filterNode), fields: ['id', 'mutedInstanceIds'], page: 1, per_page: params.ruleIds.length, diff --git a/x-pack/plugins/upgrade_assistant/kibana.jsonc b/x-pack/plugins/upgrade_assistant/kibana.jsonc index 55a08297937b..24b328c1294b 100644 --- a/x-pack/plugins/upgrade_assistant/kibana.jsonc +++ b/x-pack/plugins/upgrade_assistant/kibana.jsonc @@ -1,7 +1,9 @@ { "type": "plugin", "id": "@kbn/upgrade-assistant-plugin", - "owner": "@elastic/kibana-management", + "owner": [ + "@elastic/kibana-core" + ], "group": "platform", "visibility": "private", "plugin": { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts index e160ac37a9e3..44aed05b2c82 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts @@ -26,7 +26,6 @@ import { esIndicesStateCheck } from '../es_indices_state_check'; import { versionService } from '../version'; import { ReindexService, reindexServiceFactory } from './reindex_service'; -import { error } from './error'; const asApiResponse = (body: T): TransportResult => ({ @@ -638,12 +637,7 @@ describe('reindexService', () => { index: '.tasks', id: 'xyz', }); - expect(log.warn).toHaveBeenCalledTimes(1); - expect(log.warn).toHaveBeenCalledWith( - error.reindexTaskCannotBeDeleted( - `Could not delete reindexing task xyz, got response "!?"` - ) - ); + expect(log.warn).toHaveBeenCalledTimes(0); // Do not log anything in this case }); it('does not throw if task doc deletion throws', async () => { @@ -672,6 +666,32 @@ describe('reindexService', () => { expect(log.warn).toHaveBeenCalledTimes(1); expect(log.warn).toHaveBeenCalledWith(new Error('FAILED!')); }); + + it.each([401, 403])( + 'does not throw if task doc deletion throws AND does not log due to missing access permission: %d', + async (statusCode) => { + clusterClient.asCurrentUser.tasks.get.mockResponseOnce({ + completed: true, + // @ts-expect-error not full interface + task: { status: { created: 100, total: 100 } }, + }); + + clusterClient.asCurrentUser.count.mockResponseOnce( + // @ts-expect-error not full interface + { + count: 100, + } + ); + const e = new Error(); + Object.defineProperty(e, 'statusCode', { value: statusCode }); + clusterClient.asCurrentUser.delete.mockRejectedValue(e); + + const updatedOp = await service.processNextStep(reindexOp); + expect(updatedOp.attributes.lastCompletedStep).toEqual(ReindexStep.reindexCompleted); + expect(updatedOp.attributes.reindexTaskPercComplete).toEqual(1); + expect(log.warn).toHaveBeenCalledTimes(0); + } + ); }); describe('reindex task is cancelled', () => { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts index ce1f19f6babb..e55b4fce2e4d 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts @@ -309,20 +309,17 @@ export const reindexServiceFactory = ( } try { - // Delete the task from ES .tasks index - const deleteTaskResp = await esClient.delete({ + // Best effort, delete the task from ES .tasks index... + await esClient.delete({ index: '.tasks', id: taskId, }); - if (deleteTaskResp.result !== 'deleted') { - log.warn( - error.reindexTaskCannotBeDeleted( - `Could not delete reindexing task ${taskId}, got response "${deleteTaskResp.result}"` - ) - ); - } } catch (e) { - log.warn(e); + // We explicitly ignore authz related error codes bc we expect this to be + // very common when deleting from .tasks + if (e?.statusCode !== 401 && e?.statusCode !== 403) { + log.warn(e); + } } return reindexOp; diff --git a/x-pack/solutions/observability/plugins/observability/public/application/index.tsx b/x-pack/solutions/observability/plugins/observability/public/application/index.tsx index 3ae624d2f8ea..54b8b4044e64 100644 --- a/x-pack/solutions/observability/plugins/observability/public/application/index.tsx +++ b/x-pack/solutions/observability/plugins/observability/public/application/index.tsx @@ -28,7 +28,7 @@ import { HideableReactQueryDevTools } from './hideable_react_query_dev_tools'; function App() { return ( <> - + {Object.keys(routes).map((key) => { const path = key as keyof typeof routes; const { handler, exact } = routes[path]; diff --git a/x-pack/solutions/observability/plugins/observability/public/components/rule_condition_chart/helpers.ts b/x-pack/solutions/observability/plugins/observability/public/components/rule_condition_chart/helpers.ts index 30663d02cda7..775da2fc1c80 100644 --- a/x-pack/solutions/observability/plugins/observability/public/components/rule_condition_chart/helpers.ts +++ b/x-pack/solutions/observability/plugins/observability/public/components/rule_condition_chart/helpers.ts @@ -18,7 +18,7 @@ export const getLensOperationFromRuleMetric = (metric: GenericMetric): LensOpera const { aggType, field, filter = '' } = metric; let operation: string = aggType; const operationArgs: string[] = []; - const escapedFilter = filter.replace(/'/g, "\\'"); + const escapedFilter = filter.replace(/\\/g, '\\\\').replace(/'/g, "\\'"); if (aggType === Aggregators.RATE) { return { diff --git a/x-pack/solutions/observability/plugins/observability/server/ui_settings.ts b/x-pack/solutions/observability/plugins/observability/server/ui_settings.ts index e5695a3c9034..a68ae28b267f 100644 --- a/x-pack/solutions/observability/plugins/observability/server/ui_settings.ts +++ b/x-pack/solutions/observability/plugins/observability/server/ui_settings.ts @@ -325,7 +325,7 @@ export const uiSettings: Record = { }, }), schema: schema.boolean(), - value: true, + value: false, requiresPageReload: true, type: 'boolean', }, diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/README.mdx b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/README.mdx similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/README.mdx rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/README.mdx diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/babel_with_emotion.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/babel_with_emotion.ts similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/babel_with_emotion.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/babel_with_emotion.ts diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/constants.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/constants.ts similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/constants.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/constants.ts diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/index.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/index.ts similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/index.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/index.ts diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/main.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/main.ts similarity index 89% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/main.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/main.ts index 4e7fca030c2f..2d455283571a 100644 --- a/x-pack/packages/kbn-cloud-security-posture/storybook/config/main.ts +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/main.ts @@ -9,7 +9,7 @@ import { defaultConfig } from '@kbn/storybook'; module.exports = { ...defaultConfig, - stories: ['../../**/*.stories.+(tsx|mdx)'], + stories: ['../**/*.stories.+(tsx|mdx)'], reactOptions: { strictMode: true, }, diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/manager.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/manager.ts similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/manager.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/manager.ts diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/package.json b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/package.json similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/package.json rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/package.json diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/preview.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/preview.ts similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/preview.ts rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/preview.ts diff --git a/x-pack/packages/kbn-cloud-security-posture/storybook/config/styles.css b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/styles.css similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/storybook/config/styles.css rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/styles.css diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/tsconfig.json b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/tsconfig.json new file mode 100644 index 000000000000..6126ec1825c9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node", "@kbn/ambient-storybook-types"] + }, + "include": ["**/*.ts"], + "kbn_references": ["@kbn/storybook"], + "exclude": ["target/**/*"] +} diff --git a/x-pack/packages/kbn-cloud-security-posture/README.md b/x-pack/solutions/security/packages/kbn-cloud-security-posture/README.md similarity index 100% rename from x-pack/packages/kbn-cloud-security-posture/README.md rename to x-pack/solutions/security/packages/kbn-cloud-security-posture/README.md diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/jest.config.js b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/jest.config.js index 0448a8a11bc8..3933698808c1 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/jest.config.js +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/jest.config.js @@ -11,7 +11,7 @@ module.exports = { rootDir: '../../../../../..', transform: { '^.+\\.(js|tsx?)$': - '/x-pack/packages/kbn-cloud-security-posture/storybook/config/babel_with_emotion.ts', + '/x-pack/solutions/security/packages/kbn-cloud-security-posture/.storybook/babel_with_emotion.ts', }, setupFiles: ['jest-canvas-mock'], setupFilesAfterEnv: [ diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx index 081b4ec28c6a..bd57082ba4cb 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx @@ -126,21 +126,46 @@ const useGraphPopovers = ( }; interface GraphInvestigationProps { - dataView: DataView; - eventIds: string[]; - timestamp: string | null; + /** + * The initial state to use for the graph investigation view. + */ + initialState: { + /** + * The data view to use for the graph investigation view. + */ + dataView: DataView; + + /** + * The origin events for the graph investigation view. + */ + originEventIds: Array<{ + /** + * The ID of the origin event. + */ + id: string; + + /** + * A flag indicating whether the origin event is an alert or not. + */ + isAlert: boolean; + }>; + + /** + * The initial timerange for the graph investigation view. + */ + timeRange: TimeRange; + }; } /** * Graph investigation view allows the user to expand nodes and view related entities. */ export const GraphInvestigation: React.FC = memo( - ({ dataView, eventIds, timestamp = new Date().toISOString() }: GraphInvestigationProps) => { + ({ + initialState: { dataView, originEventIds, timeRange: initialTimeRange }, + }: GraphInvestigationProps) => { const [searchFilters, setSearchFilters] = useState(() => []); - const [timeRange, setTimeRange] = useState({ - from: `${timestamp}||-30m`, - to: `${timestamp}||+30m`, - }); + const [timeRange, setTimeRange] = useState(initialTimeRange); const { services: { uiSettings }, @@ -153,7 +178,7 @@ export const GraphInvestigation: React.FC = memo( [...searchFilters], getEsQueryConfig(uiSettings as Parameters[0]) ), - [searchFilters, dataView, uiSettings] + [dataView, searchFilters, uiSettings] ); const { nodeExpandPopover, openPopoverCallback } = useGraphPopovers( @@ -166,7 +191,7 @@ export const GraphInvestigation: React.FC = memo( const { data, refresh, isFetching } = useFetchGraphData({ req: { query: { - eventIds, + originEventIds, esQuery: query, start: timeRange.from, end: timeRange.to, diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.test.tsx b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.test.tsx index e494ff0957ec..da5eaee9bfbf 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.test.tsx +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.test.tsx @@ -33,7 +33,7 @@ describe('useFetchGraphData', () => { return useFetchGraphData({ req: { query: { - eventIds: [], + originEventIds: [], start: '2021-09-01T00:00:00.000Z', end: '2021-09-01T23:59:59.999Z', }, @@ -52,7 +52,7 @@ describe('useFetchGraphData', () => { return useFetchGraphData({ req: { query: { - eventIds: [], + originEventIds: [], start: '2021-09-01T00:00:00.000Z', end: '2021-09-01T23:59:59.999Z', }, @@ -75,7 +75,7 @@ describe('useFetchGraphData', () => { return useFetchGraphData({ req: { query: { - eventIds: [], + originEventIds: [], start: '2021-09-01T00:00:00.000Z', end: '2021-09-01T23:59:59.999Z', }, @@ -98,7 +98,7 @@ describe('useFetchGraphData', () => { return useFetchGraphData({ req: { query: { - eventIds: [], + originEventIds: [], start: '2021-09-01T00:00:00.000Z', end: '2021-09-01T23:59:59.999Z', }, diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.ts index 74cca4693e80..477492a3bbb7 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.ts +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/hooks/use_fetch_graph_data.ts @@ -81,13 +81,13 @@ export const useFetchGraphData = ({ options, }: UseFetchGraphDataParams): UseFetchGraphDataResult => { const queryClient = useQueryClient(); - const { esQuery, eventIds, start, end } = req.query; + const { esQuery, originEventIds, start, end } = req.query; const { services: { http }, } = useKibana(); const QUERY_KEY = useMemo( - () => ['useFetchGraphData', eventIds, start, end, esQuery], - [end, esQuery, eventIds, start] + () => ['useFetchGraphData', originEventIds, start, end, esQuery], + [end, esQuery, originEventIds, start] ); const { isLoading, isError, data, isFetching } = useQuery( diff --git a/packages/kbn-securitysolution-autocomplete/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/README.md similarity index 100% rename from packages/kbn-securitysolution-autocomplete/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/index.ts new file mode 100644 index 000000000000..f3768e8cd37f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/check_empty_value'; +export * from './src/es_field_selector'; +export * from './src/field_value_exists'; +export * from './src/field_value_lists'; +export * from './src/field_value_match'; +export * from './src/field_value_match_any'; +export * from './src/field_value_wildcard'; +export * from './src/filter_field_to_list'; +export * from './src/get_generic_combo_box_props'; +export * from './src/get_operators'; +export * from './src/hooks'; +export * from './src/operator'; +export * from './src/param_is_valid'; +export * from './src/param_contains_space'; + +export { default as autoCompletei18n } from './src/translations'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/jest.config.js new file mode 100644 index 000000000000..7384086c5871 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete'], +}; diff --git a/packages/kbn-securitysolution-autocomplete/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-autocomplete/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/package.json new file mode 100644 index 000000000000..fcce028035c4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-autocomplete", + "version": "1.0.0", + "description": "Security Solution auto complete", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts new file mode 100644 index 000000000000..2372ad727e9f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/autocomplete/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +// Copied from "src/plugins/data/public/mocks.ts" but without any type information +// TODO: Remove this in favor of the data/public/mocks if/when they become available, https://github.com/elastic/kibana/issues/100715 +export const autocompleteStartMock = { + getQuerySuggestions: jest.fn(), + getValueSuggestions: jest.fn(), + hasQuerySuggestions: jest.fn(), +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.ts new file mode 100644 index 000000000000..4f99799bb468 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { checkEmptyValue } from '.'; +import { getField } from '../fields/index.mock'; +import * as i18n from '../translations'; + +describe('check_empty_value', () => { + test('returns no errors if no field has been selected', () => { + const isValid = checkEmptyValue('', undefined, true, false); + + expect(isValid).toBeUndefined(); + }); + + test('returns error string if user has touched a required input and left empty', () => { + const isValid = checkEmptyValue(undefined, getField('@timestamp'), true, true); + + expect(isValid).toEqual(i18n.FIELD_REQUIRED_ERR); + }); + + test('returns no errors if required input is empty but user has not yet touched it', () => { + const isValid = checkEmptyValue(undefined, getField('@timestamp'), true, false); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if user has touched an input that is not required and left empty', () => { + const isValid = checkEmptyValue(undefined, getField('@timestamp'), false, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if user has touched an input that is not required and left empty string', () => { + const isValid = checkEmptyValue('', getField('@timestamp'), false, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns null if input value is not empty string or undefined', () => { + const isValid = checkEmptyValue('hellooo', getField('@timestamp'), false, true); + + expect(isValid).toBeNull(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.ts new file mode 100644 index 000000000000..285c91842f2f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/check_empty_value/index.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewFieldBase } from '@kbn/es-query'; +import * as i18n from '../translations'; + +/** + * Determines if empty value is ok + */ +export const checkEmptyValue = ( + param: string | undefined, + field: DataViewFieldBase | undefined, + isRequired: boolean, + touched: boolean +): string | undefined | null => { + if (isRequired && touched && (param == null || param.trim() === '')) { + return i18n.FIELD_REQUIRED_ERR; + } + + if ( + field == null || + (isRequired && !touched) || + (!isRequired && (param == null || param === '')) + ) { + return undefined; + } + + return null; +}; diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/__snapshots__/index.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/__snapshots__/index.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/__snapshots__/index.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/__snapshots__/index.test.tsx.snap diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.ts new file mode 100644 index 000000000000..743ba33fbbe5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/disabled_types_with_tooltip_text.test.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { disabledTypesWithTooltipText } from '../disabled_types_with_tooltip_text'; + +jest.mock('../../translations', () => ({ + BINARY_TYPE_NOT_SUPPORTED: 'Binary fields are currently unsupported', +})); +describe('disabledTypesWithTooltipText', () => { + it('should return Binary fields are currently unsupported for binary type', () => { + const type = 'binary'; + expect(disabledTypesWithTooltipText[type]).toEqual('Binary fields are currently unsupported'); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx new file mode 100644 index 000000000000..10db3fcce5f5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/index.test.tsx @@ -0,0 +1,142 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { fireEvent, render, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; + +import { EsFieldSelector } from '..'; +import { fields, getField } from '../../fields/index.mock'; + +describe('FieldComponent', () => { + it('should render the component enabled and displays the selected field correctly', () => { + const wrapper = render( + + ); + expect(wrapper.container).toMatchSnapshot(); + const comboBox = wrapper.getByTestId('fieldAutocompleteComboBox'); + const input = within(comboBox).getByRole('combobox'); + expect(input).toHaveAttribute('value', 'machine.os.raw'); + }); + it('should render the component disabled if isDisabled is true', () => { + const wrapper = render( + + ); + expect(wrapper.container).toMatchSnapshot(); + expect(wrapper.getByTestId('fieldAutocompleteComboBox').querySelector('input')).toBeDisabled(); + }); + it('should render the loading spinner if isLoading is true when clicked', () => { + const wrapper = render( + + ); + const fieldAutocompleteComboBox = wrapper.getByTestId('fieldAutocompleteComboBox'); + expect(wrapper.container).toMatchSnapshot(); + fireEvent.click(fieldAutocompleteComboBox); + expect(wrapper.getByRole('progressbar')).toBeInTheDocument(); + }); + it('should allow user to clear values if isClearable is true', () => { + const wrapper = render( + + ); + expect(wrapper.container).toMatchSnapshot(); + expect(wrapper.getByTestId('comboBoxClearButton')).toBeInTheDocument(); + }); + it('should change the selected value', async () => { + const wrapper = render( + + ); + const fieldAutocompleteComboBox = wrapper.getByTestId('comboBoxSearchInput'); + fireEvent.change(fieldAutocompleteComboBox, { target: { value: '_source' } }); + expect(fieldAutocompleteComboBox).toHaveValue('_source'); + }); + + it('it allows custom user input if "acceptsCustomOptions" is "true"', async () => { + const mockOnChange = jest.fn(); + const wrapper = render( + + ); + + const fieldAutocompleteComboBox = wrapper.getByTestId('comboBoxSearchInput'); + fireEvent.change(fieldAutocompleteComboBox, { target: { value: 'custom' } }); + await waitFor(() => + expect(wrapper.getByTestId('fieldAutocompleteComboBox')).toHaveTextContent('custom') + ); + }); +}); diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts similarity index 97% rename from packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts index 942ccbc29c38..1fb07e21fc91 100644 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/__tests__/use_es_field.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { DataViewFieldBase } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts new file mode 100644 index 000000000000..5b24ecb73605 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/disabled_types_with_tooltip_text.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +interface DisabledTypesTextType { + [typeName: string]: string; +} +import * as i18n from '../translations'; + +export const disabledTypesWithTooltipText: DisabledTypesTextType = { + binary: i18n.BINARY_TYPE_NOT_SUPPORTED, +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx new file mode 100644 index 000000000000..8ce7e7ed5507 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/index.tsx @@ -0,0 +1,107 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { EuiComboBox } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; + +import { FieldBaseProps } from './types'; +import { useEsField } from './use_es_field'; + +const AS_PLAIN_TEXT = { asPlainText: true }; + +interface EsFieldSelectorProps extends FieldBaseProps { + isClearable?: boolean; + isDisabled?: boolean; + isLoading?: boolean; + placeholder: string; + acceptsCustomOptions?: boolean; + showMappingConflicts?: boolean; + 'aria-label'?: string; +} + +export function EsFieldSelector({ + fieldInputWidth, + fieldTypeFilter = [], + indexPattern, + isClearable = false, + isDisabled = false, + isLoading = false, + isRequired = false, + onChange, + placeholder, + selectedField, + acceptsCustomOptions = false, + showMappingConflicts = false, + 'aria-label': ariaLabel, +}: EsFieldSelectorProps): JSX.Element { + const { + isInvalid, + comboOptions, + selectedComboOptions, + fieldWidth, + renderFields, + handleTouch, + handleValuesChange, + handleCreateCustomOption, + } = useEsField({ + indexPattern, + fieldTypeFilter, + isRequired, + selectedField, + fieldInputWidth, + showMappingConflicts, + onChange, + }); + + if (acceptsCustomOptions) { + return ( + + ); + } + + return ( + + ); +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.ts new file mode 100644 index 000000000000..e300df89e1c3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/types.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; +import { FieldConflictsInfo } from '@kbn/securitysolution-list-utils'; +import { GetGenericComboBoxPropsReturn } from '../get_generic_combo_box_props'; + +export interface FieldBaseProps { + indexPattern: DataViewBase | undefined; + fieldTypeFilter?: string[]; + isRequired?: boolean; + selectedField?: DataViewFieldBase | undefined; + fieldInputWidth?: number; + showMappingConflicts?: boolean; + onChange: (a: DataViewFieldBase[]) => void; +} + +export interface ComboBoxFields { + availableFields: DataViewField[]; + selectedFields: DataViewField[]; +} + +export interface GetFieldComboBoxPropsReturn extends GetGenericComboBoxPropsReturn { + disabledLabelTooltipTexts: { [label: string]: string }; + mappingConflictsTooltipInfo: { [label: string]: FieldConflictsInfo[] }; +} + +export interface DataViewField extends DataViewFieldBase { + esTypes?: string[]; +} diff --git a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx similarity index 94% rename from packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx index 615571d98960..1d6b84618af3 100644 --- a/packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/es_field_selector/use_es_field.tsx @@ -1,14 +1,11 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ -import React from 'react'; -import { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useMemo, useState } from 'react'; import { EuiComboBoxOptionOption, EuiIcon, diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx new file mode 100644 index 000000000000..9fc10f6ba3bc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.test.tsx @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { mount } from 'enzyme'; + +import { AutocompleteFieldExistsComponent } from '.'; + +describe('AutocompleteFieldExistsComponent', () => { + test('it renders field disabled', () => { + const wrapper = mount(); + + expect( + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox existsComboxBox"] input`) + .prop('disabled') + ).toBeTruthy(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx new file mode 100644 index 000000000000..ccd27f559e12 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_exists/index.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow } from '@elastic/eui'; + +const NO_OPTIONS_FOR_EXIST: EuiComboBoxOptionOption[] = []; + +interface AutocompleteFieldExistsProps { + placeholder: string; + rowLabel?: string; + 'aria-label'?: string; +} + +export const AutocompleteFieldExistsComponent: React.FC = ({ + placeholder, + rowLabel, + 'aria-label': ariaLabel, +}): JSX.Element => ( + + + +); + +AutocompleteFieldExistsComponent.displayName = 'AutocompleteFieldExists'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx new file mode 100644 index 000000000000..30323eba2685 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx @@ -0,0 +1,268 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { mount } from 'enzyme'; +import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; +import { waitFor } from '@testing-library/react'; +import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { getField } from '../fields/index.mock'; +import { AutocompleteFieldListsComponent } from '.'; +import { + getListResponseMock, + getFoundListsBySizeSchemaMock, + DATE_NOW, + IMMUTABLE, + VERSION, +} from '../list_schema/index.mock'; + +// TODO: Once these mocks are available, use them instead of hand mocking, https://github.com/elastic/kibana/issues/100715 +// const mockKibanaHttpService = coreMock.createStart().http; +// import { coreMock } from '../../../../../../../../../../src/core/public/mocks'; +const mockKibanaHttpService = jest.fn(); +const mockShowValueListModal = jest.fn(); +const MockedShowValueListModal = (props: unknown) => { + mockShowValueListModal(props); + return <>; +}; +const mockStart = jest.fn(); +const mockKeywordList: ListSchema = { + ...getListResponseMock(), + id: 'keyword_list', + name: 'keyword list', + type: 'keyword', +}; +const mockResult = { ...getFoundListsBySizeSchemaMock() }; +mockResult.smallLists = [...mockResult.smallLists, mockKeywordList]; +mockResult.largeLists = []; +jest.mock('@kbn/securitysolution-list-hooks', () => { + const originalModule = jest.requireActual('@kbn/securitysolution-list-hooks'); + + return { + ...originalModule, + useFindListsBySize: () => ({ + error: undefined, + loading: false, + result: mockResult, + start: mockStart.mockReturnValue(mockResult), + }), + }; +}); + +describe('AutocompleteFieldListsComponent', () => { + test('it renders disabled if "isDisabled" is true', async () => { + const wrapper = mount( + + ); + + expect( + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) + .prop('disabled') + ).toBeTruthy(); + }); + + test('it renders loading if "isLoading" is true', async () => { + const wrapper = mount( + + ); + + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] button`) + .at(0) + .simulate('click'); + expect( + wrapper + .find( + `EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteComboBox listsComboxBox-optionsList"]` + ) + .prop('isLoading') + ).toBeTruthy(); + }); + + test('it allows user to clear values if "isClearable" is true', async () => { + const wrapper = mount( + + ); + expect( + wrapper + .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') + .prop('options') + ).toEqual([{ label: 'some name', disabled: false }]); + }); + + test('it correctly displays lists that match the selected "keyword" field esType', () => { + const wrapper = mount( + + ); + + wrapper.find('[data-test-subj="comboBoxToggleListButton"] button').simulate('click'); + + expect( + wrapper + .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') + .prop('options') + ).toEqual([{ label: 'keyword list', disabled: false }]); + }); + + test('it correctly displays lists that match the selected "ip" field esType', () => { + const wrapper = mount( + + ); + + wrapper.find('[data-test-subj="comboBoxToggleListButton"] button').simulate('click'); + + expect( + wrapper + .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') + .prop('options') + ).toEqual([{ label: 'some name', disabled: false }]); + }); + + test('it correctly displays selected list', async () => { + const wrapper = mount( + + ); + + expect( + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) + .at(0) + .props().value + ).toEqual('some name'); + }); + + test('it invokes "onChange" when option selected', async () => { + const mockOnChange = jest.fn(); + const wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'some name', disabled: false }]); + + await waitFor(() => { + expect(mockOnChange).toHaveBeenCalledWith({ + '@timestamp': DATE_NOW, + _version: undefined, + created_at: DATE_NOW, + created_by: 'some user', + description: 'some description', + deserializer: undefined, + id: 'some-list-id', + immutable: IMMUTABLE, + meta: {}, + name: 'some name', + serializer: undefined, + tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', + type: 'ip', + updated_at: DATE_NOW, + updated_by: 'some user', + version: VERSION, + }); + }); + }); + + test('it render the value list modal', async () => { + mockShowValueListModal.mockReset(); + mount( + + ); + + expect(mockShowValueListModal).toHaveBeenCalledWith( + expect.objectContaining({ + children: 'Show value list', + listId: 'some-list-id', + shouldShowContentIfModalNotAvailable: false, + }) + ); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx new file mode 100644 index 000000000000..480791b001c5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx @@ -0,0 +1,182 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ElementType, useCallback, useEffect, useMemo, useState } from 'react'; +import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow, EuiLink, EuiText } from '@elastic/eui'; +import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { useFindListsBySize } from '@kbn/securitysolution-list-hooks'; +import { DataViewFieldBase } from '@kbn/es-query'; +import { getDocLinks } from '@kbn/doc-links'; + +import { filterFieldToList } from '../filter_field_to_list'; +import { getGenericComboBoxProps } from '../get_generic_combo_box_props'; + +// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 +// import { HttpStart } from '@kbn/core/public'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type HttpStart = any; + +import * as i18n from '../translations'; + +const SINGLE_SELECTION = { asPlainText: true }; + +interface AutocompleteFieldListsProps { + httpService: HttpStart; + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + onChange: (arg: ListSchema) => void; + placeholder: string; + rowLabel?: string; + selectedField: DataViewFieldBase | undefined; + selectedValue: string | undefined; + allowLargeValueLists?: boolean; + 'aria-label'?: string; + showValueListModal: ElementType; +} + +export interface AutocompleteListsData { + smallLists: ListSchema[]; + largeLists: ListSchema[]; +} + +export const AutocompleteFieldListsComponent: React.FC = ({ + httpService, + isClearable = false, + isDisabled = false, + isLoading = false, + onChange, + placeholder, + rowLabel, + selectedField, + selectedValue, + allowLargeValueLists = false, + 'aria-label': ariaLabel, + showValueListModal, +}): JSX.Element => { + const [error, setError] = useState(undefined); + const [listData, setListData] = useState({ + smallLists: [], + largeLists: [], + }); + const { loading, result, start } = useFindListsBySize(); + const getLabel = useCallback(({ name }: ListSchema) => name, []); + + const optionsMemo = useMemo( + () => filterFieldToList(listData, selectedField), + [listData, selectedField] + ); + const selectedOptionsMemo = useMemo(() => { + if (selectedValue != null) { + const combinedLists = [...listData.smallLists, ...listData.largeLists]; + const list = combinedLists.filter(({ id }) => id === selectedValue); + return list ?? []; + } else { + return []; + } + }, [selectedValue, listData]); + const { comboOptions, labels, selectedComboOptions } = useMemo( + () => + getGenericComboBoxProps({ + getLabel, + options: [...optionsMemo.smallLists, ...optionsMemo.largeLists], + selectedOptions: selectedOptionsMemo, + disabledOptions: allowLargeValueLists ? undefined : optionsMemo.largeLists, // Disable large lists if the rule type doesn't allow it + }), + [optionsMemo, selectedOptionsMemo, getLabel, allowLargeValueLists] + ); + + const handleValuesChange = useCallback( + (newOptions: EuiComboBoxOptionOption[]) => { + const combinedLists = [...optionsMemo.smallLists, ...optionsMemo.largeLists]; + const [newValue] = newOptions.map(({ label }) => combinedLists[labels.indexOf(label)]); + onChange(newValue ?? ''); + }, + [labels, optionsMemo, onChange] + ); + + const setIsTouchedValue = useCallback((): void => { + setError(selectedValue == null ? i18n.FIELD_REQUIRED_ERR : undefined); + }, [selectedValue]); + + useEffect(() => { + if (result != null) { + setListData(result); + } + }, [result]); + + useEffect(() => { + if (selectedField != null && httpService != null) { + start({ + http: httpService, + pageIndex: 1, + pageSize: 500, + }); + } + }, [selectedField, start, httpService]); + + const isLoadingState = useMemo((): boolean => isLoading || loading, [isLoading, loading]); + const ShowValueListModal = showValueListModal; + + const helpText = useMemo(() => { + return ( + <> + {selectedValue && ( + + {i18n.SHOW_VALUE_LIST_MODAL} + + )} + {!allowLargeValueLists && ( + + {i18n.LISTS_TOOLTIP_INFO}{' '} + + {i18n.SEE_DOCUMENTATION} + + + )} + + ); + }, [allowLargeValueLists, selectedValue, ShowValueListModal]); + return ( + + + + ); +}; + +AutocompleteFieldListsComponent.displayName = 'AutocompleteFieldList'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx new file mode 100644 index 000000000000..8ca17a78764c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx @@ -0,0 +1,629 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { ReactWrapper, mount } from 'enzyme'; +import { + EuiComboBox, + EuiComboBoxOptionOption, + EuiFormHelpText, + EuiSuperSelect, +} from '@elastic/eui'; +import { act, waitFor } from '@testing-library/react'; +import { AutocompleteFieldMatchComponent } from '.'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { fields, getField } from '../fields/index.mock'; +import { autocompleteStartMock } from '../autocomplete/index.mock'; + +jest.mock('../hooks/use_field_value_autocomplete'); +jest.mock('../translations', () => ({ + FIELD_SPACE_WARNING: 'Warning: there is a space', +})); +describe('AutocompleteFieldMatchComponent', () => { + let wrapper: ReactWrapper; + + const getValueSuggestionsMock = jest + .fn() + .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); + + const findEuiComboBox = () => + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + onSearchChange: (a: string) => void; + onCreateOption: (a: string) => void; + }; + + beforeEach(() => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + ['value 1', 'value 2'], + getValueSuggestionsMock, + ]); + }); + + afterEach(() => { + jest.clearAllMocks(); + wrapper.unmount(); + }); + + test('it renders row label if one passed in', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteMatchLabel"] label').at(0).text() + ).toEqual('Row Label'); + }); + + test('it renders disabled if "isDisabled" is true', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteMatch"] input').prop('disabled') + ).toBeTruthy(); + }); + + test('it renders loading if "isLoading" is true', () => { + wrapper = mount( + + ); + wrapper.find('[data-test-subj="valuesAutocompleteMatch"] button').at(0).simulate('click'); + expect( + wrapper + .find('EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteMatch-optionsList"]') + .prop('isLoading') + ).toBeTruthy(); + }); + + test('it allows user to clear values if "isClearable" is true', () => { + wrapper = mount( + + ); + + expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); + }); + + test('it correctly displays selected value', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteMatch"] input').at(0).props().value + ).toEqual('127.0.0.1'); + }); + + test('it invokes "onChange" when new value created', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + findEuiComboBox().onCreateOption('127.0.0.1'); + + expect(mockOnChange).toHaveBeenCalledWith('127.0.0.1'); + }); + + test('it invokes "onChange" when new value selected', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + findEuiComboBox().onChange([{ label: 'value 1' }]); + + expect(mockOnChange).toHaveBeenCalledWith('value 1'); + }); + + test('it invokes "onChange" with empty value (i.e. clears selection) when new value searched', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + act(() => { + findEuiComboBox().onSearchChange('value 12'); + }); + + expect(mockOnChange).toHaveBeenCalledWith(''); + }); + + test('should show the warning helper text if the new value contains spaces when change', async () => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + [' value 1 ', 'value 2'], + getValueSuggestionsMock, + ]); + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + await waitFor(() => findEuiComboBox().onChange([{ label: ' value 1 ' }])); + wrapper.update(); + expect(mockOnChange).toHaveBeenCalledWith(' value 1 '); + + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + }); + + test('it refreshes autocomplete with search query when new value searched', () => { + wrapper = mount( + + ); + act(() => { + findEuiComboBox().onSearchChange('value 1'); + }); + + expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ + autocompleteService: autocompleteStartMock, + fieldValue: '', + indexPattern: { + fields, + id: '1234', + title: 'logstash-*', + }, + operatorType: 'match', + query: 'value 1', + selectedField: getField('machine.os.raw'), + }); + }); + + test('it refreshes autocomplete with search query when input field is cleared', () => { + wrapper = mount( + + ); + + act(() => { + findEuiComboBox().onSearchChange('value 1'); + }); + act(() => { + findEuiComboBox().onSearchChange(''); + }); + + // 1st call is initial render, 2nd call sets the search query: + expect(useFieldValueAutocomplete).toHaveBeenNthCalledWith(2, { + autocompleteService: autocompleteStartMock, + fieldValue: 'windows', + indexPattern: { fields, id: '1234', title: 'logstash-*' }, + operatorType: 'match', + query: 'value 1', + selectedField: getField('machine.os.raw'), + }); + // last call is the refresh when input field is cleared + expect(useFieldValueAutocomplete).toHaveBeenLastCalledWith({ + autocompleteService: autocompleteStartMock, + fieldValue: 'windows', + indexPattern: { fields, id: '1234', title: 'logstash-*' }, + operatorType: 'match', + query: '', + selectedField: getField('machine.os.raw'), + }); + }); + + test('should show the warning helper text if the new value contains spaces when searching a new query', () => { + wrapper = mount( + + ); + act(() => { + findEuiComboBox().onSearchChange(' value 1'); + }); + + wrapper.update(); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + + test('should show the warning helper text if selectedValue contains spaces when editing', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + + test('should not show the warning helper text if selectedValue is falsy', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeFalsy(); + }); + + describe('boolean type', () => { + const valueSuggestionsMock = jest.fn().mockResolvedValue([false, false, [], jest.fn()]); + + beforeEach(() => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + false, + [], + valueSuggestionsMock, + ]); + }); + + test('it displays only two options - "true" or "false"', () => { + wrapper = mount( + + ); + expect( + wrapper.find('[data-test-subj="valuesAutocompleteMatchBoolean"]').exists() + ).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="valuesAutocompleteMatchBoolean"]').at(0).prop('options') + ).toEqual([ + { + inputDisplay: 'true', + value: 'true', + }, + { + inputDisplay: 'false', + value: 'false', + }, + ]); + }); + + test('it invokes "onChange" with "true" when selected', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiSuperSelect).props() as unknown as { + onChange: (a: string) => void; + } + ).onChange('true'); + + expect(mockOnChange).toHaveBeenCalledWith('true'); + }); + + test('it invokes "onChange" with "false" when selected', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiSuperSelect).props() as unknown as { + onChange: (a: string) => void; + } + ).onChange('false'); + + expect(mockOnChange).toHaveBeenCalledWith('false'); + }); + }); + + describe('number type', () => { + const valueSuggestionsMock = jest.fn().mockResolvedValue([false, false, [], jest.fn()]); + + beforeEach(() => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + false, + [], + valueSuggestionsMock, + ]); + }); + + test('it number input when field type is number', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valueAutocompleteFieldMatchNumber"]').exists() + ).toBeTruthy(); + }); + + test('it invokes "onChange" with numeric value when inputted', () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + wrapper + .find('[data-test-subj="valueAutocompleteFieldMatchNumber"] input') + .at(0) + .simulate('change', { target: { value: '8' } }); + + expect(mockOnChange).toHaveBeenCalledWith('8'); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx new file mode 100644 index 000000000000..a938ad2f7a99 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx @@ -0,0 +1,376 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback, useMemo, useState, useEffect } from 'react'; +import { + EuiSuperSelect, + EuiFormRow, + EuiFieldNumber, + EuiComboBoxOptionOption, + EuiComboBox, +} from '@elastic/eui'; +import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; + +import { uniq } from 'lodash'; + +import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 +// import { AutocompleteStart } from '../../../../../../../../../../src/plugins/unified_search/public'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AutocompleteStart = any; + +import * as i18n from '../translations'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { + getGenericComboBoxProps, + GetGenericComboBoxPropsReturn, +} from '../get_generic_combo_box_props'; +import { paramIsValid } from '../param_is_valid'; +import { paramContainsSpace } from '../param_contains_space'; + +const BOOLEAN_OPTIONS = [ + { inputDisplay: 'true', value: 'true' }, + { inputDisplay: 'false', value: 'false' }, +]; + +const SINGLE_SELECTION = { asPlainText: true }; + +type Warning = string | React.ReactNode; + +interface AutocompleteFieldMatchProps { + placeholder: string; + selectedField: DataViewFieldBase | undefined; + selectedValue: string | undefined; + indexPattern: DataViewBase | undefined; + isLoading?: boolean; + isDisabled?: boolean; + isClearable?: boolean; + isRequired?: boolean; + fieldInputWidth?: number; + rowLabel?: string; + autocompleteService: AutocompleteStart; + onChange: (arg: string) => void; + onError?: (arg: boolean) => void; + onWarning?: (arg: boolean) => void; + warning?: Warning; + 'aria-label'?: string; +} + +export const AutocompleteFieldMatchComponent: React.FC = ({ + placeholder, + rowLabel, + selectedField, + selectedValue, + indexPattern, + isLoading = false, + isDisabled = false, + isClearable = false, + isRequired = false, + fieldInputWidth, + autocompleteService, + onChange, + onError, + onWarning, + warning, + 'aria-label': ariaLabel, +}): JSX.Element => { + const [searchQuery, setSearchQuery] = useState(''); + const [touched, setIsTouched] = useState(false); + const [error, setError] = useState(undefined); + const [showSpacesWarning, setShowSpacesWarning] = useState(false); + const [isLoadingSuggestions, isSuggestingValues, suggestions] = useFieldValueAutocomplete({ + autocompleteService, + fieldValue: selectedValue, + indexPattern, + operatorType: OperatorTypeEnum.MATCH, + query: searchQuery, + selectedField, + }); + const getLabel = useCallback((option: string): string => option, []); + + const optionsMemo = useMemo((): string[] => { + const valueAsStr = String(selectedValue); + return selectedValue != null && selectedValue.trim() !== '' + ? uniq([valueAsStr, ...suggestions]) + : suggestions; + }, [suggestions, selectedValue]); + + const selectedOptionsMemo = useMemo((): string[] => { + const valueAsStr = String(selectedValue); + return selectedValue ? [valueAsStr] : []; + }, [selectedValue]); + + const handleSpacesWarning = useCallback( + (param: string | undefined) => { + if (!param) return setShowSpacesWarning(false); + setShowSpacesWarning(!!paramContainsSpace(param)); + }, + [setShowSpacesWarning] + ); + + const handleError = useCallback( + (err: string | undefined): void => { + setError((existingErr): string | undefined => { + const oldErr = existingErr != null; + const newErr = err != null; + if (oldErr !== newErr && onError != null) { + onError(newErr); + } + + return err; + }); + }, + [setError, onError] + ); + + const handleWarning = useCallback( + (warn: Warning | undefined): void => { + if (onWarning) { + onWarning(warn !== undefined); + } + }, + [onWarning] + ); + + const { comboOptions, labels, selectedComboOptions } = useMemo( + (): GetGenericComboBoxPropsReturn => + getGenericComboBoxProps({ + getLabel, + options: optionsMemo, + selectedOptions: selectedOptionsMemo, + }), + [optionsMemo, selectedOptionsMemo, getLabel] + ); + + const handleValuesChange = useCallback( + (newOptions: EuiComboBoxOptionOption[]): void => { + const [newValue] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); + + handleSpacesWarning(newValue); + handleError(undefined); + handleWarning(undefined); + onChange(newValue ?? ''); + }, + [handleError, handleWarning, handleSpacesWarning, labels, onChange, optionsMemo] + ); + + const handleSearchChange = useCallback( + (searchVal: string): void => { + if (searchVal !== '' && selectedField != null) { + const err = paramIsValid(searchVal, selectedField, isRequired, touched); + handleError(err); + handleWarning(warning); + + if (!err) handleSpacesWarning(searchVal); + } + + if (searchVal) { + // Clear selected option when user types to allow user to modify value without {backspace} + onChange(''); + } + + // Update search query unconditionally to show correct suggestions even when input is cleared + setSearchQuery(searchVal); + }, + [ + selectedField, + onChange, + isRequired, + touched, + handleError, + handleWarning, + warning, + handleSpacesWarning, + ] + ); + + const handleCreateOption = useCallback( + (option: string): boolean | undefined => { + const err = paramIsValid(option, selectedField, isRequired, touched); + handleError(err); + handleWarning(warning); + + if (err != null) { + // Explicitly reject the user's input + setShowSpacesWarning(false); + return false; + } + + handleSpacesWarning(option); + onChange(option); + return undefined; + }, + [ + isRequired, + onChange, + selectedField, + touched, + handleError, + handleSpacesWarning, + handleWarning, + warning, + ] + ); + + const handleNonComboBoxInputChange = useCallback( + (event: React.ChangeEvent): void => { + const newValue = event.target.value; + onChange(newValue); + }, + [onChange] + ); + + const handleBooleanInputChange = useCallback( + (newOption: string): void => { + onChange(newOption); + }, + [onChange] + ); + + const setIsTouchedValue = useCallback((): void => { + setIsTouched(true); + + const err = paramIsValid(selectedValue, selectedField, isRequired, true); + handleError(err); + handleWarning(warning); + }, [setIsTouched, handleError, selectedValue, selectedField, isRequired, warning, handleWarning]); + + const inputPlaceholder = useMemo((): string => { + if (isLoading || isLoadingSuggestions) { + return i18n.LOADING; + } else if (selectedField == null) { + return i18n.SELECT_FIELD_FIRST; + } else { + return placeholder; + } + }, [isLoading, selectedField, isLoadingSuggestions, placeholder]); + + const isLoadingState = useMemo( + (): boolean => isLoading || isLoadingSuggestions, + [isLoading, isLoadingSuggestions] + ); + + useEffect((): void => { + setError(undefined); + if (onError != null) onError(false); + + handleSpacesWarning(selectedValue); + // Looks like selectedField return new object every time when we for example add "and" entry + // that's why we need to check for name and type here + // Probably we should use some kind of memoization on parent components for entries + }, [selectedField?.name, selectedField?.type, selectedValue, handleSpacesWarning, onError]); + + const defaultInput = useMemo((): JSX.Element => { + return ( + + + + ); + }, [ + rowLabel, + error, + selectedField, + showSpacesWarning, + inputPlaceholder, + isDisabled, + isLoadingState, + isClearable, + comboOptions, + selectedComboOptions, + handleValuesChange, + handleSearchChange, + handleCreateOption, + setIsTouchedValue, + warning, + fieldInputWidth, + ariaLabel, + ]); + + if (!isSuggestingValues && selectedField != null) { + switch (selectedField.type) { + case 'number': + return ( + + 0 + ? parseFloat(selectedValue) + : selectedValue ?? '' + } + onChange={handleNonComboBoxInputChange} + data-test-subj="valueAutocompleteFieldMatchNumber" + style={fieldInputWidth ? { width: `${fieldInputWidth}px` } : {}} + aria-label={ariaLabel} + fullWidth + /> + + ); + case 'boolean': + return ( + + + + ); + default: + return defaultInput; + } + } else { + return defaultInput; + } +}; + +AutocompleteFieldMatchComponent.displayName = 'AutocompleteFieldMatch'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx new file mode 100644 index 000000000000..33355e2cb382 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx @@ -0,0 +1,398 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { ReactWrapper, mount } from 'enzyme'; +import { EuiComboBox, EuiComboBoxOptionOption, EuiFormHelpText } from '@elastic/eui'; +import { act, waitFor } from '@testing-library/react'; + +import { AutocompleteFieldMatchAnyComponent } from '.'; +import { getField, fields } from '../fields/index.mock'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { autocompleteStartMock } from '../autocomplete/index.mock'; + +jest.mock('../hooks/use_field_value_autocomplete', () => { + const actual = jest.requireActual('../hooks/use_field_value_autocomplete'); + return { + ...actual, + useFieldValueAutocomplete: jest.fn(), + }; +}); +jest.mock('../translations', () => ({ + FIELD_SPACE_WARNING: 'Warning: there is a space', +})); + +describe('AutocompleteFieldMatchAnyComponent', () => { + let wrapper: ReactWrapper; + const getValueSuggestionsMock = jest + .fn() + .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); + + beforeEach(() => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + ['value 1', 'value 2'], + getValueSuggestionsMock, + ]); + }); + + afterEach(() => { + jest.clearAllMocks(); + wrapper.unmount(); + }); + + test('it renders disabled if "isDisabled" is true', () => { + wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] input`).prop('disabled') + ).toBeTruthy(); + }); + + test('it renders loading if "isLoading" is true', () => { + wrapper = mount( + + ); + wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] button`).at(0).simulate('click'); + expect( + wrapper + .find(`EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteMatchAny-optionsList"]`) + .prop('isLoading') + ).toBeTruthy(); + }); + + test('it allows user to clear values if "isClearable" is true', () => { + wrapper = mount( + + ); + + expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); + }); + + test('it correctly displays selected value', () => { + wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="valuesAutocompleteMatchAny"] EuiComboBoxPill`).at(0).text() + ).toEqual('127.0.0.1'); + }); + + test('it invokes "onChange" when new value created', async () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onCreateOption: (a: string) => void; + } + ).onCreateOption('127.0.0.1'); + + expect(mockOnChange).toHaveBeenCalledWith(['127.0.0.1']); + }); + + test('it invokes "onChange" when new value selected', async () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'value 1' }]); + + expect(mockOnChange).toHaveBeenCalledWith(['value 1']); + }); + + test('it refreshes autocomplete with search query when new value searched', () => { + wrapper = mount( + + ); + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange('value 1'); + }); + expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ + autocompleteService: autocompleteStartMock, + fieldValue: [], + indexPattern: { + fields, + id: '1234', + title: 'logstash-*', + }, + operatorType: 'match_any', + query: 'value 1', + selectedField: getField('machine.os.raw'), + }); + }); + test('should show the warning helper text if the new value contains spaces when change', async () => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + [' value 1 ', 'value 2'], + getValueSuggestionsMock, + ]); + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + await waitFor(() => + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: ' value 1 ' }]) + ); + wrapper.update(); + expect(mockOnChange).toHaveBeenCalledWith([' value 1 ']); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + }); + test('should show the warning helper text if the new value contains spaces when searching a new query', () => { + wrapper = mount( + + ); + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange(' value 1'); + }); + + wrapper.update(); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + test('should show the warning helper text if selectedValue contains spaces when editing', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + test('should not show the warning helper text if selectedValue is falsy', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeFalsy(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx new file mode 100644 index 000000000000..be7fac088ec1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx @@ -0,0 +1,252 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow } from '@elastic/eui'; +import { uniq } from 'lodash'; +import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; + +// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 +// import { AutocompleteStart } from '../../../../../../../../../../src/plugins/unified_search/public'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AutocompleteStart = any; + +import * as i18n from '../translations'; +import { + getGenericComboBoxProps, + GetGenericComboBoxPropsReturn, +} from '../get_generic_combo_box_props'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { paramIsValid } from '../param_is_valid'; +import { paramContainsSpace } from '../param_contains_space'; + +interface AutocompleteFieldMatchAnyProps { + placeholder: string; + selectedField: DataViewFieldBase | undefined; + selectedValue: string[]; + indexPattern: DataViewBase | undefined; + isLoading: boolean; + isDisabled: boolean; + isClearable: boolean; + isRequired?: boolean; + rowLabel?: string; + autocompleteService: AutocompleteStart; + onChange: (arg: string[]) => void; + onError?: (arg: boolean) => void; + 'aria-label'?: string; +} + +export const AutocompleteFieldMatchAnyComponent: React.FC = ({ + placeholder, + rowLabel, + selectedField, + selectedValue, + indexPattern, + isLoading, + isDisabled = false, + isClearable = false, + isRequired = false, + onChange, + onError, + autocompleteService, + 'aria-label': ariaLabel, +}): JSX.Element => { + const [searchQuery, setSearchQuery] = useState(''); + const [touched, setIsTouched] = useState(false); + const [error, setError] = useState(undefined); + const [showSpacesWarning, setShowSpacesWarning] = useState(false); + const [isLoadingSuggestions, isSuggestingValues, suggestions] = useFieldValueAutocomplete({ + autocompleteService, + fieldValue: selectedValue, + indexPattern, + operatorType: OperatorTypeEnum.MATCH_ANY, + query: searchQuery, + selectedField, + }); + const getLabel = useCallback((option: string): string => option, []); + const optionsMemo = useMemo( + (): string[] => (selectedValue ? uniq([...selectedValue, ...suggestions]) : suggestions), + [suggestions, selectedValue] + ); + const { comboOptions, labels, selectedComboOptions } = useMemo( + (): GetGenericComboBoxPropsReturn => + getGenericComboBoxProps({ + getLabel, + options: optionsMemo, + selectedOptions: selectedValue, + }), + [optionsMemo, selectedValue, getLabel] + ); + const handleSpacesWarning = useCallback( + (params: string[]) => + setShowSpacesWarning(!!params.find((param: string) => paramContainsSpace(param))), + [setShowSpacesWarning] + ); + const handleError = useCallback( + (err: string | undefined): void => { + setError((existingErr): string | undefined => { + const oldErr = existingErr != null; + const newErr = err != null; + if (oldErr !== newErr && onError != null) { + onError(newErr); + } + + return err; + }); + }, + [setError, onError] + ); + + const handleValuesChange = useCallback( + (newOptions: EuiComboBoxOptionOption[]): void => { + const newValues: string[] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); + handleError(undefined); + handleSpacesWarning(newValues); + onChange(newValues); + }, + [handleError, handleSpacesWarning, labels, onChange, optionsMemo] + ); + + const handleSearchChange = useCallback( + (searchVal: string) => { + if (searchVal === '') { + handleError(undefined); + } + + if (searchVal !== '' && selectedField != null) { + const err = paramIsValid(searchVal, selectedField, isRequired, touched); + handleError(err); + + if (!err) handleSpacesWarning([searchVal]); + + setSearchQuery(searchVal); + } + }, + [handleError, handleSpacesWarning, isRequired, selectedField, touched] + ); + + const handleCreateOption = useCallback( + (option: string): boolean => { + const err = paramIsValid(option, selectedField, isRequired, touched); + handleError(err); + + if (err != null) { + // Explicitly reject the user's input + setShowSpacesWarning(false); + return false; + } + + onChange([...(selectedValue || []), option]); + handleSpacesWarning([option]); + return true; + }, + [handleError, handleSpacesWarning, isRequired, onChange, selectedField, selectedValue, touched] + ); + + const setIsTouchedValue = useCallback((): void => { + handleError(selectedComboOptions.length === 0 ? i18n.FIELD_REQUIRED_ERR : undefined); + setIsTouched(true); + }, [setIsTouched, handleError, selectedComboOptions]); + + const inputPlaceholder = useMemo( + (): string => (isLoading || isLoadingSuggestions ? i18n.LOADING : placeholder), + [isLoading, isLoadingSuggestions, placeholder] + ); + + const isLoadingState = useMemo( + (): boolean => isLoading || isLoadingSuggestions, + [isLoading, isLoadingSuggestions] + ); + useEffect((): void => { + handleSpacesWarning(selectedValue); + }, [selectedField, selectedValue, handleSpacesWarning]); + + const defaultInput = useMemo((): JSX.Element => { + return ( + + + + ); + }, [ + rowLabel, + error, + selectedField, + showSpacesWarning, + inputPlaceholder, + isLoadingState, + isClearable, + isDisabled, + comboOptions, + selectedComboOptions, + handleValuesChange, + handleSearchChange, + handleCreateOption, + setIsTouchedValue, + ariaLabel, + ]); + + if (!isSuggestingValues && selectedField != null) { + switch (selectedField.type) { + case 'number': + return ( + + + + ); + default: + return defaultInput; + } + } + + return defaultInput; +}; + +AutocompleteFieldMatchAnyComponent.displayName = 'AutocompleteFieldMatchAny'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx new file mode 100644 index 000000000000..2c2411f0a0c1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.test.tsx @@ -0,0 +1,514 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { ReactWrapper, mount } from 'enzyme'; +import { EuiComboBox, EuiComboBoxOptionOption, EuiFormHelpText } from '@elastic/eui'; +import { act, waitFor } from '@testing-library/react'; +import { AutocompleteFieldWildcardComponent } from '.'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { fields, getField } from '../fields/index.mock'; +import { autocompleteStartMock } from '../autocomplete/index.mock'; +import { WILDCARD_WARNING, FILEPATH_WARNING } from '@kbn/securitysolution-utils'; + +jest.mock('../hooks/use_field_value_autocomplete'); +jest.mock('../translations', () => ({ + FIELD_SPACE_WARNING: 'Warning: there is a space', +})); +describe('AutocompleteFieldWildcardComponent', () => { + let wrapper: ReactWrapper; + + const getValueSuggestionsMock = jest + .fn() + .mockResolvedValue([false, true, ['value 3', 'value 4'], jest.fn()]); + + beforeEach(() => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + ['value 1', 'value 2'], + getValueSuggestionsMock, + ]); + }); + + afterEach(() => { + jest.clearAllMocks(); + wrapper.unmount(); + }); + + test('it renders row label if one passed in', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteWildcardLabel"] label').at(0).text() + ).toEqual('Row Label'); + }); + + test('it renders disabled if "isDisabled" is true', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] input').prop('disabled') + ).toBeTruthy(); + }); + + test('it renders loading if "isLoading" is true', () => { + wrapper = mount( + + ); + wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] button').at(0).simulate('click'); + expect( + wrapper + .find('EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteWildcard-optionsList"]') + .prop('isLoading') + ).toBeTruthy(); + }); + + test('it allows user to clear values if "isClearable" is true', () => { + wrapper = mount( + + ); + + expect(wrapper.find(`[data-test-subj="comboBoxClearButton"]`)).toBeTruthy(); + }); + + test('it correctly displays selected value', () => { + wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="valuesAutocompleteWildcard"] input').at(0).props().value + ).toEqual('/opt/*/app.dmg'); + }); + + test('it invokes "onChange" when new value created', async () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onCreateOption: (a: string) => void; + } + ).onCreateOption('/opt/*/app.dmg'); + + expect(mockOnChange).toHaveBeenCalledWith('/opt/*/app.dmg'); + }); + + test('it invokes "onChange" when new value selected', async () => { + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'value 1' }]); + + expect(mockOnChange).toHaveBeenCalledWith('value 1'); + }); + + test('it refreshes autocomplete with search query when new value searched', () => { + wrapper = mount( + + ); + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange('A:\\Some Folder\\inc*.exe'); + }); + + expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ + autocompleteService: autocompleteStartMock, + fieldValue: '', + indexPattern: { + fields, + id: '1234', + title: 'logs-endpoint.events.*', + }, + operatorType: 'wildcard', + query: 'A:\\Some Folder\\inc*.exe', + selectedField: getField('file.path.text'), + }); + }); + + test('it does not invoke "onWarning" when no warning exists', () => { + const mockOnWarning = jest.fn(); + wrapper = mount( + + ); + + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onBlur: () => void; + } + ).onBlur(); + }); + + expect(mockOnWarning).not.toHaveBeenCalledWith(true); + }); + + test('it invokes "onWarning" when warning exists', () => { + const mockOnWarning = jest.fn(); + wrapper = mount( + + ); + + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onBlur: () => void; + } + ).onBlur(); + }); + + expect(mockOnWarning).toHaveBeenCalledWith(true); + expect( + wrapper + .find('[data-test-subj="valuesAutocompleteWildcardLabel"] div.euiFormHelpText') + .at(0) + .text() + ).toEqual(FILEPATH_WARNING); + }); + + test('it invokes "onWarning" when warning exists and is wildcard warning', () => { + const mockOnWarning = jest.fn(); + wrapper = mount( + + ); + + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onBlur: () => void; + } + ).onBlur(); + }); + + expect(mockOnWarning).toHaveBeenCalledWith(true); + const helpText = wrapper + .find('[data-test-subj="valuesAutocompleteWildcardLabel"] div.euiFormHelpText') + .at(0); + expect(helpText.text()).toEqual(WILDCARD_WARNING); + expect(helpText.find('.euiToolTipAnchor')).toBeTruthy(); + }); + test('should show the warning helper text if the new value contains spaces when change', async () => { + (useFieldValueAutocomplete as jest.Mock).mockReturnValue([ + false, + true, + [' value 1 ', 'value 2'], + getValueSuggestionsMock, + ]); + const mockOnChange = jest.fn(); + wrapper = mount( + + ); + + await waitFor(() => + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: ' value 1 ' }]) + ); + wrapper.update(); + expect(mockOnChange).toHaveBeenCalledWith(' value 1 '); + + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + }); + test('should show the warning helper text if the new value contains spaces when searching a new query', () => { + wrapper = mount( + + ); + act(() => { + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange(' value 1'); + }); + + wrapper.update(); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + test('should show the warning helper text if selectedValue contains spaces when editing', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeTruthy(); + expect(euiFormHelptext.text()).toEqual('Warning: there is a space'); + }); + test('should not show the warning helper text if selectedValue is falsy', () => { + wrapper = mount( + + ); + const euiFormHelptext = wrapper.find(EuiFormHelpText); + expect(euiFormHelptext.length).toBeFalsy(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx new file mode 100644 index 000000000000..c095578bf0ff --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/field_value_wildcard/index.tsx @@ -0,0 +1,285 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback, useMemo, useState, useEffect, memo } from 'react'; +import { EuiFormRow, EuiComboBoxOptionOption, EuiComboBox } from '@elastic/eui'; +import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; + +import { uniq } from 'lodash'; + +import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 +// import { AutocompleteStart } from '../../../../../../../../../../src/plugins/unified_search/public'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AutocompleteStart = any; + +import * as i18n from '../translations'; +import { useFieldValueAutocomplete } from '../hooks/use_field_value_autocomplete'; +import { + getGenericComboBoxProps, + GetGenericComboBoxPropsReturn, +} from '../get_generic_combo_box_props'; +import { paramIsValid } from '../param_is_valid'; +import { paramContainsSpace } from '../param_contains_space'; + +const SINGLE_SELECTION = { asPlainText: true }; + +type Warning = string | React.ReactNode; +interface AutocompleteFieldWildcardProps { + placeholder: string; + selectedField: DataViewFieldBase | undefined; + selectedValue: string | undefined; + indexPattern: DataViewBase | undefined; + isLoading: boolean; + isDisabled?: boolean; + isClearable?: boolean; + isRequired?: boolean; + fieldInputWidth?: number; + rowLabel?: string; + autocompleteService: AutocompleteStart; + onChange: (arg: string) => void; + onError: (arg: boolean) => void; + onWarning: (arg: boolean) => void; + warning?: Warning; + 'aria-label'?: string; +} + +export const AutocompleteFieldWildcardComponent: React.FC = memo( + ({ + autocompleteService, + placeholder, + rowLabel, + selectedField, + selectedValue, + indexPattern, + isLoading, + isDisabled = false, + isClearable = false, + isRequired = false, + fieldInputWidth, + onChange, + onError, + onWarning, + warning, + 'aria-label': ariaLabel, + }): JSX.Element => { + const [searchQuery, setSearchQuery] = useState(''); + const [touched, setIsTouched] = useState(false); + const [error, setError] = useState(undefined); + const [showSpacesWarning, setShowSpacesWarning] = useState(false); + const [isLoadingSuggestions, , suggestions] = useFieldValueAutocomplete({ + autocompleteService, + fieldValue: selectedValue, + indexPattern, + operatorType: OperatorTypeEnum.WILDCARD, + query: searchQuery, + selectedField, + }); + const getLabel = useCallback((option: string): string => option, []); + const optionsMemo = useMemo((): string[] => { + const valueAsStr = String(selectedValue); + return selectedValue != null && selectedValue.trim() !== '' + ? uniq([valueAsStr, ...suggestions]) + : suggestions; + }, [suggestions, selectedValue]); + const selectedOptionsMemo = useMemo((): string[] => { + const valueAsStr = String(selectedValue); + return selectedValue ? [valueAsStr] : []; + }, [selectedValue]); + + const handleSpacesWarning = useCallback( + (param: string | undefined) => { + if (!param) return setShowSpacesWarning(false); + setShowSpacesWarning(!!paramContainsSpace(param)); + }, + [setShowSpacesWarning] + ); + const handleError = useCallback( + (err: string | undefined): void => { + setError((existingErr): string | undefined => { + const oldErr = existingErr != null; + const newErr = err != null; + if (oldErr !== newErr && onError != null) { + onError(newErr); + } + + return err; + }); + }, + [setError, onError] + ); + + const handleWarning = useCallback( + (warn: Warning | undefined): void => { + onWarning(warn !== undefined); + }, + [onWarning] + ); + + const { comboOptions, labels, selectedComboOptions } = useMemo( + (): GetGenericComboBoxPropsReturn => + getGenericComboBoxProps({ + getLabel, + options: optionsMemo, + selectedOptions: selectedOptionsMemo, + }), + [optionsMemo, selectedOptionsMemo, getLabel] + ); + + const handleValuesChange = useCallback( + (newOptions: EuiComboBoxOptionOption[]): void => { + const [newValue] = newOptions.map(({ label }) => optionsMemo[labels.indexOf(label)]); + handleError(undefined); + handleSpacesWarning(newValue); + setShowSpacesWarning(false); + + onChange(newValue ?? ''); + }, + [handleError, handleSpacesWarning, labels, onChange, optionsMemo] + ); + + const handleSearchChange = useCallback( + (searchVal: string): void => { + if (searchVal.trim() !== '' && selectedField != null) { + const err = paramIsValid(searchVal, selectedField, isRequired, touched); + handleError(err); + handleWarning(warning); + if (!err) handleSpacesWarning(searchVal); + + setSearchQuery(searchVal); + } + }, + [handleError, handleSpacesWarning, isRequired, selectedField, touched, warning, handleWarning] + ); + + const handleCreateOption = useCallback( + (option: string): boolean | undefined => { + const err = paramIsValid(option, selectedField, isRequired, touched); + handleError(err); + handleWarning(warning); + + if (err != null) { + // Explicitly reject the user's input + setShowSpacesWarning(false); + return false; + } + + handleSpacesWarning(option); + onChange(option); + return undefined; + }, + [ + isRequired, + handleSpacesWarning, + onChange, + selectedField, + touched, + handleError, + handleWarning, + warning, + ] + ); + + const setIsTouchedValue = useCallback((): void => { + setIsTouched(true); + + const err = paramIsValid(selectedValue, selectedField, isRequired, true); + handleError(err); + handleWarning(warning); + }, [ + setIsTouched, + handleError, + selectedValue, + selectedField, + isRequired, + handleWarning, + warning, + ]); + + const inputPlaceholder = useMemo((): string => { + if (isLoading || isLoadingSuggestions) { + return i18n.LOADING; + } else if (selectedField == null) { + return i18n.SELECT_FIELD_FIRST; + } else { + return placeholder; + } + }, [isLoading, selectedField, isLoadingSuggestions, placeholder]); + + const isLoadingState = useMemo( + (): boolean => isLoading || isLoadingSuggestions, + [isLoading, isLoadingSuggestions] + ); + + useEffect((): void => { + setError(undefined); + if (onError != null) { + onError(false); + } + handleSpacesWarning(selectedValue); + + onWarning(false); + }, [selectedField, selectedValue, onError, onWarning, handleSpacesWarning]); + + const defaultInput = useMemo((): JSX.Element => { + return ( + + + + ); + }, [ + rowLabel, + error, + warning, + showSpacesWarning, + selectedField, + inputPlaceholder, + isDisabled, + isLoadingState, + isClearable, + comboOptions, + selectedComboOptions, + handleValuesChange, + handleSearchChange, + handleCreateOption, + setIsTouchedValue, + fieldInputWidth, + ariaLabel, + ]); + + return defaultInput; + } +); + +AutocompleteFieldWildcardComponent.displayName = 'AutocompleteFieldWildcard'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts new file mode 100644 index 000000000000..32e9d6019786 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts @@ -0,0 +1,321 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewFieldBase } from '@kbn/es-query'; + +// Copied from "src/plugins/data/common/index_patterns/fields/fields.mocks.ts" but with the types changed to "DataViewFieldBase" since that type is compatible. +// TODO: This should move out once those mocks are directly useable or in their own package, https://github.com/elastic/kibana/issues/100715 + +export const fields: DataViewFieldBase[] = [ + { + name: 'bytes', + type: 'number', + esTypes: ['long'], + count: 10, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'ssl', + type: 'boolean', + esTypes: ['boolean'], + count: 20, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '@timestamp', + type: 'date', + esTypes: ['date'], + count: 30, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'time', + type: 'date', + esTypes: ['date'], + count: 30, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '@tags', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'utc_time', + type: 'date', + esTypes: ['date'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'phpmemory', + type: 'number', + esTypes: ['integer'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'ip', + type: 'ip', + esTypes: ['ip'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'request_body', + type: 'attachment', + esTypes: ['attachment'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'point', + type: 'geo_point', + esTypes: ['geo_point'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'area', + type: 'geo_shape', + esTypes: ['geo_shape'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'hashed', + type: 'murmur3', + esTypes: ['murmur3'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + }, + { + name: 'geo.coordinates', + type: 'geo_point', + esTypes: ['geo_point'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'extension', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'machine.os', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'machine.os.raw', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + subType: { multi: { parent: 'machine.os' } }, + }, + { + name: 'geo.src', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '_id', + type: 'string', + esTypes: ['_id'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: '_type', + type: 'string', + esTypes: ['_type'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: '_source', + type: '_source', + esTypes: ['_source'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'non-filterable', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: false, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'non-sortable', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: false, + aggregatable: false, + readFromDocValues: false, + }, + { + name: 'custom_user_field', + type: 'conflict', + esTypes: ['long', 'text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'script string', + type: 'string', + count: 0, + scripted: true, + script: "'i am a string'", + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script number', + type: 'number', + count: 0, + scripted: true, + script: '1234', + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script date', + type: 'date', + count: 0, + scripted: true, + script: '1234', + lang: 'painless', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script murmur3', + type: 'murmur3', + count: 0, + scripted: true, + script: '1234', + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'nestedField.child', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + subType: { nested: { path: 'nestedField' } }, + }, + { + name: 'nestedField.nestedChild.doublyNestedChild', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + subType: { nested: { path: 'nestedField.nestedChild' } }, + }, + { + name: 'file.path.text', + type: 'string', + esTypes: ['text'], + searchable: true, + aggregatable: false, + subType: { multi: { parent: 'file.path' } }, + }, +] as unknown as DataViewFieldBase[]; + +export const getField = (name: string) => fields.find((field) => field.name === name); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts new file mode 100644 index 000000000000..3328af4e2fa2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.test.ts @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { filterFieldToList } from '.'; + +import { getListResponseMock } from '../list_schema/index.mock'; +import { DataViewFieldBase } from '@kbn/es-query'; +import { AutocompleteListsData } from '../field_value_lists'; + +const emptyListData: AutocompleteListsData = { smallLists: [], largeLists: [] }; + +describe('#filterFieldToList', () => { + test('it returns empty list data object if given a undefined for field', () => { + const filter = filterFieldToList(emptyListData, undefined); + expect(filter).toEqual(emptyListData); + }); + + test('it returns empty list data object if filed does not contain esTypes', () => { + const field: DataViewFieldBase = { + name: 'some-name', + type: 'some-type', + }; + const filter = filterFieldToList(emptyListData, field); + expect(filter).toEqual(emptyListData); + }); + + test('it returns filtered lists of ip_range -> ip', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['ip'], + name: 'some-name', + type: 'ip', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], + largeLists: [], + }; + const filter = filterFieldToList(listData, field); + const expected = listData; + expect(filter).toEqual(expected); + }); + + test('it returns filtered lists of ip -> ip', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['ip'], + name: 'some-name', + type: 'ip', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'ip' }], + largeLists: [], + }; + const filter = filterFieldToList(listData, field); + const expected = listData; + expect(filter).toEqual(expected); + }); + + test('it returns filtered lists of keyword -> keyword', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['keyword'], + name: 'some-name', + type: 'keyword', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'keyword' }], + largeLists: [], + }; + const filter = filterFieldToList(listData, field); + const expected = listData; + expect(filter).toEqual(expected); + }); + + test('it returns filtered lists of text -> text', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['text'], + name: 'some-name', + type: 'text', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'text' }], + largeLists: [], + }; + const filter = filterFieldToList(listData, field); + const expected = listData; + expect(filter).toEqual(expected); + }); + + test('it returns small and large filtered lists of ip_range -> ip', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['ip'], + name: 'some-name', + type: 'ip', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], + largeLists: [{ ...getListResponseMock(), type: 'ip_range' }], + }; + const filter = filterFieldToList(listData, field); + const expected = listData; + expect(filter).toEqual(expected); + }); + + test('it returns 1 filtered lists of ip_range -> ip if the 2nd is not compatible type', () => { + const field: DataViewFieldBase & { esTypes: string[] } = { + esTypes: ['ip'], + name: 'some-name', + type: 'ip', + }; + const listData: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], + largeLists: [{ ...getListResponseMock(), type: 'text' }], + }; + const filter = filterFieldToList(listData, field); + const expected: AutocompleteListsData = { + smallLists: [{ ...getListResponseMock(), type: 'ip_range' }], + largeLists: [], + }; + expect(filter).toEqual(expected); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts new file mode 100644 index 000000000000..a4df119766a9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/filter_field_to_list/index.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewFieldBase } from '@kbn/es-query'; +import { typeMatch } from '../type_match'; +import { AutocompleteListsData } from '../field_value_lists'; + +/** + * Given an array of lists and optionally a field this will return all + * the lists that match against the field based on the types from the field + * + * NOTE: That we support one additional property from "FieldSpec" located here: + * src/plugins/data/common/index_patterns/fields/types.ts + * This type property is esTypes. If it exists and is on there we will read off the esTypes. + * @param lists The lists to match against the field + * @param field The field to check against the list to see if they are compatible + */ +export const filterFieldToList = ( + lists: AutocompleteListsData, + field?: DataViewFieldBase & { esTypes?: string[] } +): AutocompleteListsData => { + if (field != null) { + const { esTypes = [] } = field; + return { + smallLists: lists.smallLists.filter(({ type }) => + esTypes.some((esType: string) => typeMatch(type, esType)) + ), + largeLists: lists.largeLists.filter(({ type }) => + esTypes.some((esType: string) => typeMatch(type, esType)) + ), + }; + } else { + return { smallLists: [], largeLists: [] }; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx new file mode 100644 index 000000000000..f333e7c6ebdd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.test.tsx @@ -0,0 +1,124 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getGenericComboBoxProps } from '.'; + +describe('get_generic_combo_box_props', () => { + test('it returns empty arrays if "options" is empty array', () => { + const result = getGenericComboBoxProps({ + options: [], + selectedOptions: ['option1'], + getLabel: (t: string) => t, + }); + + expect(result).toEqual({ comboOptions: [], labels: [], selectedComboOptions: [] }); + }); + + test('it returns formatted props if "options" array is not empty', () => { + const result = getGenericComboBoxProps({ + options: ['option1', 'option2', 'option3'], + selectedOptions: [], + getLabel: (t: string) => t, + }); + + expect(result).toEqual({ + comboOptions: [ + { + label: 'option1', + }, + { + label: 'option2', + }, + { + label: 'option3', + }, + ], + labels: ['option1', 'option2', 'option3'], + selectedComboOptions: [], + }); + }); + + test('it does not return "selectedOptions" items that do not appear in "options"', () => { + const result = getGenericComboBoxProps({ + options: ['option1', 'option2', 'option3'], + selectedOptions: ['option4'], + getLabel: (t: string) => t, + }); + + expect(result).toEqual({ + comboOptions: [ + { + label: 'option1', + }, + { + label: 'option2', + }, + { + label: 'option3', + }, + ], + labels: ['option1', 'option2', 'option3'], + selectedComboOptions: [], + }); + }); + + test('it returns "selectedOptions" items that do appear in "options"', () => { + const result = getGenericComboBoxProps({ + options: ['option1', 'option2', 'option3'], + selectedOptions: ['option2'], + getLabel: (t: string) => t, + }); + + expect(result).toEqual({ + comboOptions: [ + { + label: 'option1', + }, + { + label: 'option2', + }, + { + label: 'option3', + }, + ], + labels: ['option1', 'option2', 'option3'], + selectedComboOptions: [ + { + label: 'option2', + }, + ], + }); + }); + + test('it returns "disabledOptions" items that do appear in "options" as disabled', () => { + const result = getGenericComboBoxProps({ + options: ['option1', 'option2', 'option3'], + selectedOptions: [], + disabledOptions: ['option2'], + getLabel: (t: string) => t, + }); + + expect(result).toEqual({ + comboOptions: [ + { + label: 'option1', + disabled: false, + }, + { + label: 'option2', + disabled: true, + }, + { + label: 'option3', + disabled: false, + }, + ], + labels: ['option1', 'option2', 'option3'], + selectedComboOptions: [], + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.ts new file mode 100644 index 000000000000..f043fc978836 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_generic_combo_box_props/index.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiComboBoxOptionOption } from '@elastic/eui'; + +export interface GetGenericComboBoxPropsReturn { + comboOptions: EuiComboBoxOptionOption[]; + labels: string[]; + selectedComboOptions: EuiComboBoxOptionOption[]; +} + +/** + * Determines the options, selected values and option labels for EUI combo box + * @param options options user can select from + * @param selectedOptions user selection if any + * @param getLabel helper function to know which property to use for labels + */ +export const getGenericComboBoxProps = ({ + getLabel, + options, + selectedOptions, + disabledOptions, +}: { + getLabel: (value: T) => string; + options: T[]; + selectedOptions: T[]; + disabledOptions?: T[]; +}): GetGenericComboBoxPropsReturn => { + const newLabels = options.map(getLabel); + const disabledLabels = disabledOptions?.map(getLabel); + const newComboOptions: EuiComboBoxOptionOption[] = newLabels.map((label) => ({ + label, + disabled: disabledLabels && disabledLabels.length !== 0 && disabledLabels.includes(label), + })); + const newSelectedComboOptions = selectedOptions + .map(getLabel) + .filter((option) => { + return newLabels.indexOf(option) !== -1; + }) + .map((option) => { + return newComboOptions[newLabels.indexOf(option)]; + }); + + return { + comboOptions: newComboOptions, + labels: newLabels, + selectedComboOptions: newSelectedComboOptions, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts new file mode 100644 index 000000000000..db031a65e0bb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.test.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + doesNotExistOperator, + EVENT_FILTERS_OPERATORS, + ALL_OPERATORS, + existsOperator, + isNotOperator, + isOperator, +} from '@kbn/securitysolution-list-utils'; +import { getOperators } from '.'; +import { getField } from '../fields/index.mock'; + +describe('#getOperators', () => { + test('it returns "isOperator" if passed in field is "undefined"', () => { + const operator = getOperators(undefined); + + expect(operator).toEqual([isOperator]); + }); + + test('it returns expected operators when field type is "boolean"', () => { + const operator = getOperators(getField('ssl')); + + expect(operator).toEqual([isOperator, isNotOperator, existsOperator, doesNotExistOperator]); + }); + + test('it returns "isOperator" when field type is "nested"', () => { + const operator = getOperators({ + name: 'nestedField', + scripted: false, + subType: { nested: { path: 'nestedField' } }, + type: 'nested', + }); + + expect(operator).toEqual([isOperator]); + }); + + test('it includes a "matches" operator when field is "file.path.text"', () => { + const operator = getOperators({ + name: 'file.path.text', + type: 'simple', + }); + + expect(operator).toEqual(EVENT_FILTERS_OPERATORS); + }); + + test('it returns all operator types when field type is not null, boolean, or nested', () => { + const operator = getOperators(getField('machine.os.raw')); + + expect(operator).toEqual(ALL_OPERATORS); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.ts new file mode 100644 index 000000000000..451d4f5c21a7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/get_operators/index.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewFieldBase } from '@kbn/es-query'; + +import { + ALL_OPERATORS, + EVENT_FILTERS_OPERATORS, + OperatorOption, + doesNotExistOperator, + existsOperator, + isNotOperator, + isOperator, +} from '@kbn/securitysolution-list-utils'; + +/** + * Returns the appropriate operators given a field type + * + * @param field DataViewFieldBase selected field + * + */ +export const getOperators = (field: DataViewFieldBase | undefined): OperatorOption[] => { + if (field == null) { + return [isOperator]; + } else if (field.type === 'boolean') { + return [isOperator, isNotOperator, existsOperator, doesNotExistOperator]; + } else if (field.type === 'nested') { + return [isOperator]; + } else if (field.name === 'file.path.text') { + return EVENT_FILTERS_OPERATORS; + } else { + return ALL_OPERATORS; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/index.ts new file mode 100644 index 000000000000..e9d4507b1400 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './use_field_value_autocomplete'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts new file mode 100644 index 000000000000..7d776db12413 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.test.ts @@ -0,0 +1,298 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { waitFor, renderHook } from '@testing-library/react'; +import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; + +import { UseFieldValueAutocompleteReturn, useFieldValueAutocomplete } from '.'; +import { getField } from '../../fields/index.mock'; +import { autocompleteStartMock } from '../../autocomplete/index.mock'; +import { DataViewFieldBase } from '@kbn/es-query'; + +// Copied from "src/plugins/data/common/index_patterns/index_pattern.stub.ts" +// TODO: Remove this in favor of the above if/when it is ported, https://github.com/elastic/kibana/issues/100715 +export const stubIndexPatternWithFields = { + id: '1234', + title: 'logstash-*', + fields: [ + { + name: 'response', + type: 'number', + esTypes: ['integer'], + aggregatable: true, + filterable: true, + searchable: true, + }, + ], +}; + +describe('use_field_value_autocomplete', () => { + const onErrorMock = jest.fn(); + const getValueSuggestionsMock = jest.fn().mockResolvedValue(['value 1', 'value 2']); + + afterEach(() => { + onErrorMock.mockClear(); + getValueSuggestionsMock.mockClear(); + }); + + test('initializes hook', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: undefined, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: undefined, + }) + ); + await waitFor(() => expect(result.current).toEqual([false, true, [], result.current[3]])); + }); + + test('does not call autocomplete service if "operatorType" is "exists"', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.EXISTS, + query: '', + selectedField: getField('machine.os'), + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; + + expect(result.current).toEqual(expectedResult); + expect(getValueSuggestionsMock).not.toHaveBeenCalled(); + }); + }); + + test('does not call autocomplete service if "selectedField" is undefined', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.EXISTS, + query: '', + selectedField: undefined, + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; + + expect(result.current).toEqual(expectedResult); + expect(getValueSuggestionsMock).not.toHaveBeenCalled(); + }); + }); + + test('does not call autocomplete service if "indexPattern" is undefined', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: undefined, + operatorType: OperatorTypeEnum.EXISTS, + query: '', + selectedField: getField('machine.os'), + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [false, true, [], result.current[3]]; + + expect(result.current).toEqual(expectedResult); + expect(getValueSuggestionsMock).not.toHaveBeenCalled(); + }); + }); + + test('it uses full path name for nested fields to fetch suggestions', async () => { + const suggestionsMock = jest.fn().mockResolvedValue([]); + + const selectedField: DataViewFieldBase | undefined = getField('nestedField.child'); + if (selectedField == null) { + throw new TypeError('selectedField for this test should always be defined'); + } + + const { signal } = new AbortController(); + renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: suggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: { ...selectedField, name: 'child' }, + }) + ); + + await waitFor(() => + expect(suggestionsMock).toHaveBeenCalledWith({ + field: { ...getField('nestedField.child'), name: 'nestedField.child' }, + indexPattern: { + fields: [ + { + aggregatable: true, + esTypes: ['integer'], + filterable: true, + name: 'response', + searchable: true, + type: 'number', + }, + ], + id: '1234', + title: 'logstash-*', + }, + query: '', + signal, + useTimeRange: false, + }) + ); + }); + + test('returns "isSuggestingValues" of false if field type is boolean', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: getField('ssl'), + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [false, false, [], result.current[3]]; + + expect(result.current).toEqual(expectedResult); + expect(getValueSuggestionsMock).not.toHaveBeenCalled(); + }); + }); + + test('returns "isSuggestingValues" of false to note that autocomplete service is not in use if no autocomplete suggestions available', async () => { + const suggestionsMock = jest.fn().mockResolvedValue([]); + + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: suggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: getField('bytes'), + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [false, false, [], result.current[3]]; + + expect(suggestionsMock).toHaveBeenCalled(); + expect(result.current).toEqual(expectedResult); + }); + }); + + test('returns suggestions', async () => { + const { signal } = new AbortController(); + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: getField('@tags'), + }) + ); + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [ + false, + true, + ['value 1', 'value 2'], + result.current[3], + ]; + + expect(getValueSuggestionsMock).toHaveBeenCalledWith({ + field: getField('@tags'), + indexPattern: stubIndexPatternWithFields, + query: '', + signal, + useTimeRange: false, + }); + expect(result.current).toEqual(expectedResult); + }); + }); + + test('returns new suggestions on subsequent calls', async () => { + const { result } = renderHook(() => + useFieldValueAutocomplete({ + autocompleteService: { + ...autocompleteStartMock, + getValueSuggestions: getValueSuggestionsMock, + }, + fieldValue: '', + indexPattern: stubIndexPatternWithFields, + operatorType: OperatorTypeEnum.MATCH, + query: '', + selectedField: getField('@tags'), + }) + ); + + await waitFor(() => expect(result.current[3]).not.toBeNull()); + + // Added check for typescripts sake, if null, + // would not reach below logic as test would stop above + if (result.current[3] != null) { + result.current[3]({ + fieldSelected: getField('@tags'), + patterns: stubIndexPatternWithFields, + searchQuery: '', + value: 'hello', + }); + } + + await waitFor(() => { + const expectedResult: UseFieldValueAutocompleteReturn = [ + false, + true, + ['value 1', 'value 2'], + result.current[3], + ]; + + expect(getValueSuggestionsMock).toHaveBeenCalledTimes(2); + expect(result.current).toEqual(expectedResult); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts new file mode 100644 index 000000000000..dbbe321014e2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/hooks/use_field_value_autocomplete/index.ts @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useEffect, useRef, useState } from 'react'; +import { debounce } from 'lodash'; +import { ListOperatorTypeEnum as OperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { DataViewBase, DataViewFieldBase, getDataViewFieldSubtypeNested } from '@kbn/es-query'; + +// TODO: I have to use any here for now, but once this is available below, we should use the correct types, https://github.com/elastic/kibana/issues/100715 +// import { AutocompleteStart } from '../../../../../../../../../../../src/plugins/unified_search/public'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AutocompleteStart = any; + +interface FuncArgs { + fieldSelected: DataViewFieldBase | undefined; + patterns: DataViewBase | undefined; + searchQuery: string; + value: string | string[] | undefined; +} + +type Func = (args: FuncArgs) => void; + +export type UseFieldValueAutocompleteReturn = [boolean, boolean, string[], Func | null]; + +export interface UseFieldValueAutocompleteProps { + autocompleteService: AutocompleteStart; + fieldValue: string | string[] | undefined; + indexPattern: DataViewBase | undefined; + operatorType: OperatorTypeEnum; + query: string; + selectedField: DataViewFieldBase | undefined; +} +/** + * Hook for using the field value autocomplete service + */ +export const useFieldValueAutocomplete = ({ + selectedField, + operatorType, + fieldValue, + query, + indexPattern, + autocompleteService, +}: UseFieldValueAutocompleteProps): UseFieldValueAutocompleteReturn => { + const [isLoading, setIsLoading] = useState(false); + const [isSuggestingValues, setIsSuggestingValues] = useState(true); + const [suggestions, setSuggestions] = useState([]); + const updateSuggestions = useRef(null); + + useEffect(() => { + let isSubscribed = true; + const abortCtrl = new AbortController(); + + const fetchSuggestions = debounce( + async ({ fieldSelected, patterns, searchQuery }: FuncArgs) => { + try { + if (isSubscribed) { + if (fieldSelected == null || patterns == null) { + return; + } + + if (fieldSelected.type === 'boolean') { + setIsSuggestingValues(false); + return; + } + + setIsLoading(true); + const subTypeNested = getDataViewFieldSubtypeNested(fieldSelected); + const field = subTypeNested + ? { + ...fieldSelected, + name: `${subTypeNested.nested.path}.${fieldSelected.name}`, + } + : fieldSelected; + + const newSuggestions = await autocompleteService.getValueSuggestions({ + field, + indexPattern: patterns, + query: searchQuery, + signal: abortCtrl.signal, + useTimeRange: false, + }); + + if (newSuggestions.length === 0) { + setIsSuggestingValues(false); + } + + setIsLoading(false); + setSuggestions([...newSuggestions]); + } + } catch (error) { + if (isSubscribed) { + setSuggestions([]); + setIsLoading(false); + } + } + }, + 500 + ); + + if (operatorType !== OperatorTypeEnum.EXISTS) { + fetchSuggestions({ + fieldSelected: selectedField, + patterns: indexPattern, + searchQuery: query, + value: fieldValue, + }); + } + + updateSuggestions.current = fetchSuggestions; + + return (): void => { + isSubscribed = false; + abortCtrl.abort(); + }; + }, [selectedField, operatorType, fieldValue, indexPattern, query, autocompleteService]); + + return [isLoading, isSuggestingValues, suggestions, updateSuggestions.current]; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts new file mode 100644 index 000000000000..aade602f1950 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/list_schema/index.mock.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + FoundListSchema, + ListSchema, + FoundListsBySizeSchema, +} from '@kbn/securitysolution-io-ts-list-types'; + +// TODO: Once this mock is available within packages, use it instead, https://github.com/elastic/kibana/issues/100715 +// import { getFoundListSchemaMock } from '../../../../../../../../lists/common/schemas/response/found_list_schema.mock'; +export const getFoundListSchemaMock = (): FoundListSchema => ({ + cursor: '123', + data: [getListResponseMock()], + page: 1, + per_page: 1, + total: 1, +}); + +export const getFoundListsBySizeSchemaMock = (): FoundListsBySizeSchema => ({ + smallLists: [getListResponseMock()], + largeLists: [getListResponseMock()], +}); + +// TODO: Once these mocks are available from packages use it instead, https://github.com/elastic/kibana/issues/100715 +export const DATE_NOW = '2020-04-20T15:25:31.830Z'; +export const USER = 'some user'; +export const IMMUTABLE = false; +export const VERSION = 1; +export const DESCRIPTION = 'some description'; +export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; +export const LIST_ID = 'some-list-id'; +export const META = {}; +export const TYPE = 'ip'; +export const NAME = 'some name'; + +// TODO: Once this mock is available within packages, use it instead, https://github.com/elastic/kibana/issues/100715 +// import { getListResponseMock } from '../../../../../../../../lists/common/schemas/response/list_schema.mock'; +export const getListResponseMock = (): ListSchema => ({ + '@timestamp': DATE_NOW, + _version: undefined, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + deserializer: undefined, + id: LIST_ID, + immutable: IMMUTABLE, + meta: META, + name: NAME, + serializer: undefined, + tie_breaker_id: TIE_BREAKER, + type: TYPE, + updated_at: DATE_NOW, + updated_by: USER, + version: VERSION, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx new file mode 100644 index 000000000000..eef8738b67c5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx @@ -0,0 +1,253 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { mount } from 'enzyme'; +import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; +import { isNotOperator, isOperator } from '@kbn/securitysolution-list-utils'; + +import { OperatorComponent } from '.'; +import { getField } from '../fields/index.mock'; + +describe('operator', () => { + test('it renders disabled if "isDisabled" is true', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"] input`).prop('disabled') + ).toBeTruthy(); + }); + + test('it renders loading if "isLoading" is true', () => { + const wrapper = mount( + + ); + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"] button`).at(0).simulate('click'); + expect( + wrapper + .find(`EuiComboBoxOptionsList[data-test-subj="operatorAutocompleteComboBox-optionsList"]`) + .prop('isLoading') + ).toBeTruthy(); + }); + + test('it allows user to clear values if "isClearable" is true', () => { + const wrapper = mount( + + ); + + expect(wrapper.find(`button[data-test-subj="comboBoxClearButton"]`).exists()).toBeTruthy(); + }); + + test('it displays "operatorOptions" if param is passed in with items', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([{ label: 'is not' }]); + }); + + test('it does not display "operatorOptions" if param is passed in with no items', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([ + { + label: 'is', + }, + { + label: 'is not', + }, + { + label: 'is one of', + }, + { + label: 'is not one of', + }, + { + label: 'exists', + }, + { + label: 'does not exist', + }, + { + label: 'is in list', + }, + { + label: 'is not in list', + }, + { + label: 'matches', + }, + { + label: 'does not match', + }, + ]); + }); + + test('it correctly displays selected operator', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find('[data-test-subj="operatorAutocompleteComboBox"] input').at(0).props().value + ).toEqual('is'); + }); + + test('it only displays subset of operators if field type is nested', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([{ label: 'is' }]); + }); + + test('it only displays subset of operators if field type is boolean', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([ + { label: 'is' }, + { label: 'is not' }, + { label: 'exists' }, + { label: 'does not exist' }, + ]); + }); + + test('it only displays subset of operators if field name is "file.path.text"', () => { + const wrapper = mount( + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([ + { label: 'is' }, + { label: 'is not' }, + { label: 'is one of' }, + { label: 'is not one of' }, + { label: 'matches' }, + { label: 'does not match' }, + ]); + }); + + test('it invokes "onChange" when option selected', () => { + const mockOnChange = jest.fn(); + const wrapper = mount( + + ); + + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'is not' }]); + + expect(mockOnChange).toHaveBeenCalledWith([ + { message: 'is not', operator: 'excluded', type: 'match', value: 'is_not' }, + ]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx new file mode 100644 index 000000000000..6c91f7e70b94 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback, useMemo } from 'react'; +import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; +import { OperatorOption } from '@kbn/securitysolution-list-utils'; +import { DataViewFieldBase } from '@kbn/es-query'; + +import { getOperators } from '../get_operators'; +import { + getGenericComboBoxProps, + GetGenericComboBoxPropsReturn, +} from '../get_generic_combo_box_props'; + +const AS_PLAIN_TEXT = { asPlainText: true }; + +interface OperatorState { + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + onChange: (arg: OperatorOption[]) => void; + operator: OperatorOption; + operatorInputWidth?: number; + operatorOptions?: OperatorOption[]; + placeholder: string; + selectedField: DataViewFieldBase | undefined; + 'aria-label'?: string; +} + +export const OperatorComponent: React.FC = ({ + isClearable = false, + isDisabled = false, + isLoading = false, + onChange, + operator, + operatorOptions, + operatorInputWidth = 150, + placeholder, + selectedField, + 'aria-label': ariaLabel, +}): JSX.Element => { + const getLabel = useCallback(({ message }: OperatorOption): string => message, []); + const optionsMemo = useMemo( + (): OperatorOption[] => + operatorOptions != null && operatorOptions.length > 0 + ? operatorOptions + : getOperators(selectedField), + [operatorOptions, selectedField] + ); + const selectedOptionsMemo = useMemo( + (): OperatorOption[] => (operator ? [operator] : []), + [operator] + ); + const { comboOptions, labels, selectedComboOptions } = useMemo( + (): GetGenericComboBoxPropsReturn => + getGenericComboBoxProps({ + getLabel, + options: optionsMemo, + selectedOptions: selectedOptionsMemo, + }), + [optionsMemo, selectedOptionsMemo, getLabel] + ); + + const handleValuesChange = useCallback( + (newOptions: EuiComboBoxOptionOption[]): void => { + const newValues: OperatorOption[] = newOptions.map( + ({ label }) => optionsMemo[labels.indexOf(label)] + ); + onChange(newValues); + }, + [labels, onChange, optionsMemo] + ); + + const inputWidth = useMemo(() => { + return { width: `${operatorInputWidth}px` }; + }, [operatorInputWidth]); + + return ( + + ); +}; + +OperatorComponent.displayName = 'Operator'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts new file mode 100644 index 000000000000..d0571d157ec2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.test.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { paramContainsSpace } from '.'; + +describe('param_contains_space', () => { + test('should return true if leading spaces were found', () => { + expect(paramContainsSpace(' test')).toBeTruthy(); + }); + test('should return true if trailing spaces were found', () => { + expect(paramContainsSpace('test ')).toBeTruthy(); + }); + test('should return true if both trailing and leading spaces were found', () => { + expect(paramContainsSpace(' test ')).toBeTruthy(); + }); + test('should return true if tabs was found', () => { + expect(paramContainsSpace('\ttest')).toBeTruthy(); + }); + test('should return false if no spaces were found', () => { + expect(paramContainsSpace('test test')).toBeFalsy(); + }); + test('should return false if param is falsy', () => { + expect(paramContainsSpace('')).toBeFalsy(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.ts new file mode 100644 index 000000000000..3d7bb99ae3d0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_contains_space/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const paramContainsSpace = (param: string) => param && param.trim().length !== param.length; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts new file mode 100644 index 000000000000..f93ad28eb4ad --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts @@ -0,0 +1,105 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { paramIsValid } from '.'; +import { getField } from '../fields/index.mock'; +import * as i18n from '../translations'; +import moment from 'moment'; + +describe('params_is_valid', () => { + beforeEach(() => { + // Disable momentJS deprecation warning and it looks like it is not typed either so + // we have to disable the type as well and cannot extend it easily. + ( + moment as unknown as { + suppressDeprecationWarnings: boolean; + } + ).suppressDeprecationWarnings = true; + }); + + afterEach(() => { + // Re-enable momentJS deprecation warning and it looks like it is not typed either so + // we have to disable the type as well and cannot extend it easily. + ( + moment as unknown as { + suppressDeprecationWarnings: boolean; + } + ).suppressDeprecationWarnings = false; + }); + + test('returns no errors if no field has been selected', () => { + const isValid = paramIsValid('', undefined, true, false); + + expect(isValid).toBeUndefined(); + }); + + test('returns error string if user has touched a required input and left empty', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), true, true); + + expect(isValid).toEqual(i18n.FIELD_REQUIRED_ERR); + }); + + test('returns no errors if required input is empty but user has not yet touched it', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), true, false); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if user has touched an input that is not required and left empty', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), false, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if user has touched an input that is not required and left empty string', () => { + const isValid = paramIsValid('', getField('@timestamp'), false, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if field is of type date and value is valid', () => { + const isValid = paramIsValid('1994-11-05T08:15:30-05:00', getField('@timestamp'), false, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns errors if filed is of type date and value is not valid', () => { + const isValid = paramIsValid('1593478826', getField('@timestamp'), false, true); + + expect(isValid).toEqual(i18n.DATE_ERR); + }); + + test('returns no errors if field is of type number and value is an integer', () => { + const isValid = paramIsValid('4', getField('bytes'), true, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if field is of type number and value is a float', () => { + const isValid = paramIsValid('4.3', getField('bytes'), true, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns no errors if field is of type number and value is a long', () => { + const isValid = paramIsValid('-9223372036854775808', getField('bytes'), true, true); + + expect(isValid).toBeUndefined(); + }); + + test('returns errors if field is of type number and value is "hello"', () => { + const isValid = paramIsValid('hello', getField('bytes'), true, true); + + expect(isValid).toEqual(i18n.NUMBER_ERR); + }); + + test('returns errors if field is of type number and value is "123abc"', () => { + const isValid = paramIsValid('123abc', getField('bytes'), true, true); + + expect(isValid).toEqual(i18n.NUMBER_ERR); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.ts new file mode 100644 index 000000000000..3d091b7a9b21 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import dateMath from '@kbn/datemath'; +import { DataViewFieldBase } from '@kbn/es-query'; +import { checkEmptyValue } from '../check_empty_value'; + +import * as i18n from '../translations'; + +/** + * Very basic validation for values + * @param param the value being checked + * @param field the selected field + * @param isRequired whether or not an empty value is allowed + * @param touched has field been touched by user + * @returns undefined if valid, string with error message if invalid + */ +export const paramIsValid = ( + param: string | undefined, + field: DataViewFieldBase | undefined, + isRequired: boolean, + touched: boolean +): string | undefined => { + if (field == null) { + return undefined; + } + + const emptyValueError = checkEmptyValue(param, field, isRequired, touched); + if (emptyValueError !== null) { + return emptyValueError; + } + + switch (field.type) { + case 'date': + const moment = dateMath.parse(param ?? ''); + const isDate = Boolean(moment && moment.isValid()); + return isDate ? undefined : i18n.DATE_ERR; + case 'number': + const isNum = param != null && param.trim() !== '' && !isNaN(+param); + return isNum ? undefined : i18n.NUMBER_ERR; + default: + return undefined; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/translations/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/translations/index.ts new file mode 100644 index 000000000000..51790e96ba68 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/translations/index.ts @@ -0,0 +1,79 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const LOADING = i18n.translate('autocomplete.loadingDescription', { + defaultMessage: 'Loading...', +}); + +export const SELECT_FIELD_FIRST = i18n.translate('autocomplete.selectField', { + defaultMessage: 'Please select a field first...', +}); + +export const FIELD_REQUIRED_ERR = i18n.translate('autocomplete.fieldRequiredError', { + defaultMessage: 'Value cannot be empty', +}); + +export const NUMBER_ERR = i18n.translate('autocomplete.invalidNumberError', { + defaultMessage: 'Not a valid number', +}); + +export const DATE_ERR = i18n.translate('autocomplete.invalidDateError', { + defaultMessage: 'Not a valid date', +}); + +export const BINARY_TYPE_NOT_SUPPORTED = i18n.translate('autocomplete.invalidBinaryType', { + defaultMessage: 'Binary fields are currently unsupported', +}); +export const FIELD_SPACE_WARNING = i18n.translate('autocomplete.fieldSpaceWarning', { + defaultMessage: "Warning: Spaces at the start or end of this value aren't being displayed.", +}); + +export const LISTS_TOOLTIP_INFO = i18n.translate('autocomplete.listsTooltipWarning', { + defaultMessage: "Lists that aren't able to be processed by this rule type will be disabled.", +}); + +export const SEE_DOCUMENTATION = i18n.translate('autocomplete.seeDocumentation', { + defaultMessage: 'See Documentation', +}); + +export const FIELD_CONFLICT_INDICES_WARNING_TITLE = i18n.translate( + 'autocomplete.conflictIndicesWarning.title', + { + defaultMessage: 'Mapping Conflict', + } +); + +export const FIELD_CONFLICT_INDICES_WARNING_DESCRIPTION = i18n.translate( + 'autocomplete.conflictIndicesWarning.description', + { + defaultMessage: + 'This field is defined as different types across the following indices or is unmapped. This can cause unexpected query results.', + } +); + +export const CONFLICT_MULTIPLE_INDEX_DESCRIPTION = (name: string, count: number): string => + i18n.translate('autocomplete.conflictIndicesWarning.index.description', { + defaultMessage: '{name} ({count} indices)', + values: { count, name }, + }); + +export const SHOW_VALUE_LIST_MODAL = i18n.translate('autocomplete.showValueListModal', { + defaultMessage: 'Show value list', +}); + +// eslint-disable-next-line import/no-default-export +export default { + LOADING, + SELECT_FIELD_FIRST, + FIELD_REQUIRED_ERR, + NUMBER_ERR, + DATE_ERR, + FIELD_SPACE_WARNING, + BINARY_TYPE_NOT_SUPPORTED, +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.test.ts new file mode 100644 index 000000000000..74c713f63d36 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.test.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { typeMatch } from '.'; + +describe('type_match', () => { + test('ip -> ip is true', () => { + expect(typeMatch('ip', 'ip')).toEqual(true); + }); + + test('keyword -> keyword is true', () => { + expect(typeMatch('keyword', 'keyword')).toEqual(true); + }); + + test('text -> text is true', () => { + expect(typeMatch('text', 'text')).toEqual(true); + }); + + test('ip_range -> ip is true', () => { + expect(typeMatch('ip_range', 'ip')).toEqual(true); + }); + + test('date_range -> date is true', () => { + expect(typeMatch('date_range', 'date')).toEqual(true); + }); + + test('double_range -> double is true', () => { + expect(typeMatch('double_range', 'double')).toEqual(true); + }); + + test('float_range -> float is true', () => { + expect(typeMatch('float_range', 'float')).toEqual(true); + }); + + test('integer_range -> integer is true', () => { + expect(typeMatch('integer_range', 'integer')).toEqual(true); + }); + + test('long_range -> long is true', () => { + expect(typeMatch('long_range', 'long')).toEqual(true); + }); + + test('ip -> date is false', () => { + expect(typeMatch('ip', 'date')).toEqual(false); + }); + + test('long -> float is false', () => { + expect(typeMatch('long', 'float')).toEqual(false); + }); + + test('integer -> long is false', () => { + expect(typeMatch('integer', 'long')).toEqual(false); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.ts new file mode 100644 index 000000000000..0e368127b596 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/src/type_match/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { Type } from '@kbn/securitysolution-io-ts-list-types'; + +/** + * Given an input list type and a string based ES type this will match + * if they're exact or if they are compatible with a range + * @param type The type to match against the esType + * @param esType The ES type to match with + */ +export const typeMatch = (type: Type, esType: string): boolean => { + return ( + type === esType || + (type === 'ip_range' && esType === 'ip') || + (type === 'date_range' && esType === 'date') || + (type === 'double_range' && esType === 'double') || + (type === 'float_range' && esType === 'float') || + (type === 'integer_range' && esType === 'integer') || + (type === 'long_range' && esType === 'long') + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/tsconfig.json new file mode 100644 index 000000000000..e4f0b64736b0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-autocomplete/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "include": [ + "**/*.ts", + "**/*.tsx", + ], + "kbn_references": [ + "@kbn/datemath", + "@kbn/es-query", + "@kbn/i18n", + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-list-hooks", + "@kbn/securitysolution-list-utils", + "@kbn/doc-links", + "@kbn/securitysolution-utils", + ], + "exclude": [ + "target/**/*", + ], +} diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/README.md similarity index 100% rename from packages/kbn-securitysolution-endpoint-exceptions-common/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.ts new file mode 100644 index 000000000000..c8e4f90c347a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.gen.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Create endpoint list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { EndpointList } from '../model/endpoint_list_common.gen'; + +export type CreateEndpointListResponse = z.infer; +export const CreateEndpointListResponse = EndpointList; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml new file mode 100644 index 000000000000..cdc9004ce7e6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list/create_endpoint_list.schema.yaml @@ -0,0 +1,45 @@ +openapi: 3.0.0 +info: + title: Create endpoint list API endpoint + version: '2023-10-31' +paths: + /api/endpoint_list: + post: + x-labels: [serverless, ess] + x-codegen-enabled: true + operationId: CreateEndpointList + summary: Create an endpoint exception list + description: Create an endpoint exception list, which groups endpoint exception list items. If an endpoint exception list already exists, an empty response is returned. + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointList' + 400: + description: Invalid input data + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Insufficient privileges + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 500: + description: Internal server error + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts similarity index 81% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts index ed3a60dc08f3..c4ce0697b237 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml similarity index 77% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml index b90bee75fc07..6948df21afbb 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/create_endpoint_list_item/create_endpoint_list_item.schema.yaml @@ -57,29 +57,29 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Insufficient privileges content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 409: description: Endpoint list item already exists content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts similarity index 75% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts index 5cb5f518494e..4f268641f93c 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml new file mode 100644 index 000000000000..ae1010573e5e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/delete_endpoint_list_item/delete_endpoint_list_item.schema.yaml @@ -0,0 +1,64 @@ +openapi: 3.0.0 +info: + title: Delete endpoint list item API endpoint + version: '2023-10-31' +paths: + /api/endpoint_list/items: + delete: + x-labels: [serverless, ess] + x-codegen-enabled: true + operationId: DeleteEndpointListItem + summary: Delete an endpoint exception list item + description: Delete an endpoint exception list item using the `id` or `item_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' + - name: item_id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' + 400: + description: Invalid input data + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Insufficient privileges + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Endpoint list item not found + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts similarity index 83% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts index a830572c7b50..5b1e10d9bb04 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml new file mode 100644 index 000000000000..400851ac5254 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/find_endpoint_list_item/find_endpoint_list_item.schema.yaml @@ -0,0 +1,113 @@ +openapi: 3.0.0 +info: + title: Find endpoint list items API endpoint + version: '2023-10-31' +paths: + /api/endpoint_list/items/_find: + get: + x-labels: [serverless, ess] + x-codegen-enabled: true + operationId: FindEndpointListItems + summary: Get endpoint exception list items + description: Get a list of all endpoint exception list items. + parameters: + - name: filter + in: query + required: false + description: | + Filters the returned results according to the value of the specified field, + using the `:` syntax. + schema: + $ref: '#/components/schemas/FindEndpointListItemsFilter' + - name: page + in: query + required: false + description: The page number to return + schema: + type: integer + minimum: 0 + - name: per_page + in: query + required: false + description: The number of exception list items to return per page + schema: + type: integer + minimum: 0 + - name: sort_field + in: query + required: false + description: Determines which field is used to sort the results + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + - name: sort_order + in: query + required: false + description: Determines the sort order, which can be `desc` or `asc` + schema: + type: string + enum: [desc, asc] + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' + page: + type: integer + minimum: 0 + per_page: + type: integer + minimum: 0 + total: + type: integer + minimum: 0 + pit: + type: string + required: + - data + - page + - per_page + - total + 400: + description: Invalid input data + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Insufficient privileges + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Endpoint list not found + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + +components: + schemas: + FindEndpointListItemsFilter: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts new file mode 100644 index 000000000000..912af19448e4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './create_endpoint_list/create_endpoint_list.gen'; +export * from './create_endpoint_list_item/create_endpoint_list_item.gen'; +export * from './read_endpoint_list_item/read_endpoint_list_item.gen'; +export * from './update_endpoint_list_item/update_endpoint_list_item.gen'; +export * from './delete_endpoint_list_item/delete_endpoint_list_item.gen'; +export * from './find_endpoint_list_item/find_endpoint_list_item.gen'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.ts new file mode 100644 index 000000000000..a68abd53c11c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.gen.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Common Exception List Attributes + * version: not applicable + */ + +import { z } from '@kbn/zod'; + +import { + ExceptionList, + ExceptionListItem, +} from '@kbn/securitysolution-exceptions-common/api/model/exception_list_common.gen'; + +export type EndpointList = z.infer; +export const EndpointList = z.union([ExceptionList, z.object({}).strict()]); + +export type EndpointListItem = z.infer; +export const EndpointListItem = ExceptionListItem; diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/model/endpoint_list_common.schema.yaml diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts similarity index 75% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts index 4a9c335b395b..e2dc38450bbb 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml new file mode 100644 index 000000000000..0b64bac231df --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/read_endpoint_list_item/read_endpoint_list_item.schema.yaml @@ -0,0 +1,66 @@ +openapi: 3.0.0 +info: + title: Read endpoint list item API endpoint + version: '2023-10-31' +paths: + /api/endpoint_list/items: + get: + x-labels: [serverless, ess] + x-codegen-enabled: true + operationId: ReadEndpointListItem + summary: Get an endpoint exception list item + description: Get the details of an endpoint exception list item using the `id` or `item_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' + - name: item_id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../../../kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: array + items: + $ref: '../model/endpoint_list_common.schema.yaml#/components/schemas/EndpointListItem' + 400: + description: Invalid input data + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Insufficient privileges + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Endpoint list item not found + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts similarity index 83% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts index 0a235ca2ff89..ec86992d58b7 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml similarity index 78% rename from packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml index 679000674c7b..1fbe40d2b94e 100644 --- a/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/api/update_endpoint_list_item/update_endpoint_list_item.schema.yaml @@ -62,29 +62,29 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Insufficient privileges content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 404: description: Endpoint list item not found content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/ess/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/serverless/security_solution_endpoint_exceptions_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-endpoint-exceptions-common/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-endpoint-exceptions-common/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/package.json new file mode 100644 index 000000000000..39e6232e4e0f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/package.json @@ -0,0 +1,11 @@ +{ + "description": "OpenAPI Endpoint Exceptions Common", + "license": "Elastic License 2.0", + "name": "@kbn/securitysolution-endpoint-exceptions-common", + "private": true, + "version": "1.0.0", + "scripts": { + "openapi:generate": "node scripts/openapi_generate", + "openapi:bundle": "node scripts/openapi_bundle" + } +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js new file mode 100644 index 000000000000..c54e162b6462 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { bundle } = require('@kbn/openapi-bundler'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/serverless/security_solution_endpoint_exceptions_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['serverless'], + prototypeDocument: { + info: { + title: 'Security Endpoint Exceptions API (Elastic Cloud Serverless)', + description: 'Endpoint Exceptions API allow you to manage Endpoint lists.', + }, + tags: [ + { + name: 'Security Endpoint Exceptions API', + 'x-displayName': 'Security endpoint exceptions', + description: + "Endpoint Exceptions API allows you to manage detection rule endpoint exceptions to prevent a rule from generating an alert from incoming events even when the rule's other criteria are met.", + }, + ], + }, + }, + }); + + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/ess/security_solution_endpoint_exceptions_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['ess'], + prototypeDocument: { + info: { + title: 'Security Endpoint Exceptions API (Elastic Cloud and self-hosted)', + description: 'Endpoint Exceptions API allow you to manage Endpoint lists.', + }, + tags: [ + { + name: 'Security Endpoint Exceptions API', + 'x-displayName': 'Security endpoint exceptions', + description: + "Endpoint Exceptions API allows you to manage detection rule endpoint exceptions to prevent a rule from generating an alert from incoming events even when the rule's other criteria are met.", + }, + ], + }, + }, + }); +})(); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js new file mode 100644 index 000000000000..9a303c4f74be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_generate.js @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { generate } = require('@kbn/openapi-generator'); +const { REPO_ROOT } = require('@kbn/repo-info'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await generate({ + title: 'OpenAPI Endpoint Exceptions API Schemas', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'zod_operation_schema', + }); + + await generate({ + title: 'Endpoint Exceptions API client for tests', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'api_client_supertest', + skipLinting: true, + bundle: { + outFile: join( + REPO_ROOT, + 'x-pack/test/api_integration/services/security_solution_endpoint_exceptions_api.gen.ts' + ), + }, + }); +})(); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json new file mode 100644 index 000000000000..38f2843b03ad --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "exclude": ["target/**/*"], + "extends": "../../../../../tsconfig.base.json", + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/securitysolution-exceptions-common", + "@kbn/openapi-common", + "@kbn/zod", + ] +} diff --git a/packages/kbn-securitysolution-exception-list-components/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/README.md similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/index.ts new file mode 100644 index 000000000000..40277892f1f7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/search_bar'; +export * from './src/empty_viewer_state'; +export * from './src/pagination/pagination'; +// export * from './src/exceptions_utility/exceptions_utility'; +export * from './src/exception_items'; +export * from './src/exception_item_card'; +export * from './src/value_with_space_warning'; +export * from './src/types'; +export * from './src/list_header'; +export * from './src/header_menu'; +export * from './src/generate_linked_rules_menu_item'; +export * from './src/wildcard_with_wrong_operator_callout'; +export * from './src/partial_code_signature_callout'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/jest.config.js new file mode 100644 index 000000000000..d9a562b21e87 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/jest.config.js @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: [ + '/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components', + ], + coverageReporters: ['text', 'html'], + collectCoverageFrom: [ + '/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/*.{ts,tsx}', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/*.test', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/types/*', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/*.type', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/*.styles', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/mocks/*', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/*.config', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/translations', + '!/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/**/types/*', + ], + setupFilesAfterEnv: [ + '/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/setup_test.ts', + ], +}; diff --git a/packages/kbn-securitysolution-exception-list-components/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/package.json new file mode 100644 index 000000000000..f9246cb9353d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/package.json @@ -0,0 +1,7 @@ +{ + "name": "@kbn/securitysolution-exception-list-components", + "private": true, + "version": "1.0.0", + "license": "Elastic License 2.0", + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/setup_test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/setup_test.ts new file mode 100644 index 000000000000..72e0edd0d07f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/setup_test.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +// eslint-disable-next-line import/no-extraneous-dependencies +import '@testing-library/jest-dom'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/assets/images/illustration_product_no_results_magnifying_glass.svg diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts new file mode 100644 index 000000000000..18dda6a91003 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/custom.d.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +declare module '*.svg' { + const content: string; + // eslint-disable-next-line import/no-default-export + export default content; +} diff --git a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx similarity index 93% rename from packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx index 1b711185c526..7df3f732711a 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/empty_viewer_state.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx new file mode 100644 index 000000000000..2e489cb5dca9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/empty_viewer_state/index.tsx @@ -0,0 +1,133 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useMemo } from 'react'; +import type { FC } from 'react'; +import { css } from '@emotion/react'; +import { + EuiSkeletonText, + EuiImage, + EuiEmptyPrompt, + EuiButton, + useEuiTheme, + EuiPanel, +} from '@elastic/eui'; +import type { ExpressionColor } from '@elastic/eui/src/components/expression/expression'; +import type { EuiFacetGroupLayout } from '@elastic/eui/src/components/facet/facet_group'; +import { euiThemeVars } from '@kbn/ui-theme'; +import { ListTypeText, ViewerStatus } from '../types'; +import * as i18n from '../translations'; +import illustration from '../assets/images/illustration_product_no_results_magnifying_glass.svg'; + +interface EmptyViewerStateProps { + title?: string; + body?: string; + buttonText?: string; + listType?: ListTypeText; + isReadOnly: boolean; + viewerStatus: ViewerStatus; + onEmptyButtonStateClick?: () => void | null; +} + +const panelCss = css` + margin: ${euiThemeVars.euiSizeL} 0; + padding: ${euiThemeVars.euiSizeL} 0; +`; +const EmptyViewerStateComponent: FC = ({ + title, + body, + buttonText, + listType, + isReadOnly, + viewerStatus, + onEmptyButtonStateClick, +}) => { + const { euiTheme } = useEuiTheme(); + + const euiEmptyPromptProps = useMemo(() => { + switch (viewerStatus) { + case ViewerStatus.ERROR: { + return { + color: 'danger' as ExpressionColor, + iconType: 'error', + title: ( +

{title || i18n.EMPTY_VIEWER_STATE_ERROR_TITLE}

+ ), + body:

{body || i18n.EMPTY_VIEWER_STATE_ERROR_BODY}

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

{title || i18n.EMPTY_VIEWER_STATE_EMPTY_TITLE}

+ ), + body:

{body || i18n.EMPTY_VIEWER_STATE_EMPTY_BODY}

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

+ {title || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE} +

+ ), + body: ( +

+ {body || i18n.EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY} +

+ ), + 'data-test-subj': 'emptySearchViewerState', + }; + } + }, [ + viewerStatus, + euiTheme.colors.darkestShade, + title, + body, + onEmptyButtonStateClick, + isReadOnly, + buttonText, + listType, + ]); + + return ( + + + + + + ); +}; + +export const EmptyViewerState = React.memo(EmptyViewerStateComponent); + +EmptyViewerState.displayName = 'EmptyViewerState'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/__snapshots__/comments.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/__snapshots__/comments.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/__snapshots__/comments.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/__snapshots__/comments.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx similarity index 83% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx index c8c8e92cd6c7..caf989efcc9e 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/comments.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx new file mode 100644 index 000000000000..76ef48fba0a9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/comments/index.tsx @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import type { EuiCommentProps } from '@elastic/eui'; +import { EuiAccordion, EuiCommentList, EuiFlexItem, EuiPanel, EuiText } from '@elastic/eui'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import * as i18n from '../translations'; + +const accordionCss = css` + color: ${euiThemeVars.euiColorPrimary}; +`; + +export interface ExceptionItemCardCommentsProps { + comments: EuiCommentProps[]; + dataTestSubj?: string; +} + +export const ExceptionItemCardComments = memo( + ({ comments, dataTestSubj }) => { + if (!comments.length) return null; + return ( + + + {i18n.exceptionItemCardCommentsAccordion(comments.length)} + + } + arrowDisplay="none" + data-test-subj="exceptionItemCardComments" + > + + + + + + ); + } +); + +ExceptionItemCardComments.displayName = 'ExceptionItemCardComments'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts similarity index 77% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts index fdb545dc2c03..0c826f40f022 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.config.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx new file mode 100644 index 000000000000..043e2e2e4485 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.styles.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { cx } from '@emotion/css'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; + +// TODO check font Roboto Mono +export const nestedGroupSpaceCss = css` + margin-left: ${euiThemeVars.euiSizeXL}; + margin-bottom: ${euiThemeVars.euiSizeXS}; + padding-top: ${euiThemeVars.euiSizeXS}; +`; + +export const borderCss = cx( + 'eui-xScroll', + ` + border: 1px; + border-color: #d3dae6; + border-style: solid; +` +); + +export const valueContainerCss = css` + display: flex; + align-items: center; + margin-left: ${euiThemeVars.euiSizeS}; +`; +export const expressionContainerCss = css` + display: flex; + align-items: center; +`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx similarity index 96% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx index e19327226de2..6cd3ee06d203 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/conditions.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { render } from '@testing-library/react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/__snapshots__/entry_content.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/__snapshots__/entry_content.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/__snapshots__/entry_content.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/__snapshots__/entry_content.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx similarity index 93% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx index e49d18ec78c4..07de278ace7b 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx similarity index 85% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx index 2fa113e5a612..aeca92d4d003 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.helper.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React, { ElementType } from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx similarity index 83% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx index 7eb141493ef4..bed784f46b87 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/entry_content.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx new file mode 100644 index 000000000000..7f75694b16d3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/entry_content/index.tsx @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ElementType, FC, memo } from 'react'; +import { EuiExpression, EuiToken, EuiFlexGroup } from '@elastic/eui'; +import { ListOperatorTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { + nestedGroupSpaceCss, + valueContainerCss, + expressionContainerCss, +} from '../conditions.styles'; +import type { Entry } from '../types'; +import * as i18n from '../../translations'; +import { getValue, getValueExpression } from './entry_content.helper'; + +interface EntryContentProps { + entry: Entry; + index: number; + isNestedEntry?: boolean; + dataTestSubj?: string; + showValueListModal: ElementType; +} + +export const EntryContent: FC = memo( + ({ entry, index, isNestedEntry = false, dataTestSubj, showValueListModal }) => { + const { field, type } = entry; + const value = getValue(entry); + const operator = 'operator' in entry ? entry.operator : ''; + + const entryKey = `${field}${type}${value}${index}`; + return ( +
+
+ {isNestedEntry ? ( + + + +
+ + {getValueExpression( + type as ListOperatorTypeEnum, + operator, + value, + showValueListModal + )} +
+
+ ) : ( + <> + + + {getValueExpression( + type as ListOperatorTypeEnum, + operator, + value, + showValueListModal + )} + + )} +
+
+ ); + } +); +EntryContent.displayName = 'EntryContent'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx new file mode 100644 index 000000000000..804af918e4f1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/index.tsx @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import { EuiPanel } from '@elastic/eui'; + +import { borderCss } from './conditions.styles'; +import { EntryContent } from './entry_content'; +import { OsCondition } from './os_conditions'; +import type { CriteriaConditionsProps, Entry } from './types'; + +export const ExceptionItemCardConditions = memo( + ({ os, entries, dataTestSubj, showValueListModal }) => { + return ( + + {os?.length ? : null} + {entries.map((entry: Entry, index: number) => { + const nestedEntries = 'entries' in entry ? entry.entries : []; + return ( +
+ + {nestedEntries?.length + ? nestedEntries.map((nestedEntry: Entry, nestedIndex: number) => ( + + )) + : null} +
+ ); + })} +
+ ); + } +); +ExceptionItemCardConditions.displayName = 'ExceptionItemCardConditions'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/__snapshots__/os_conditions.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/__snapshots__/os_conditions.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/__snapshots__/os_conditions.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/__snapshots__/os_conditions.test.tsx.snap diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx new file mode 100644 index 000000000000..3a2dded6ce2b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/index.tsx @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo, useMemo } from 'react'; +import { EuiExpression } from '@elastic/eui'; + +import { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { OS_LABELS } from '../conditions.config'; +import * as i18n from '../../translations'; + +export interface OsConditionsProps { + dataTestSubj?: string; + os: ExceptionListItemSchema['os_types']; +} + +export const OsCondition = memo(({ os, dataTestSubj }) => { + const osLabel = useMemo(() => { + return os.map((osValue) => OS_LABELS[osValue] ?? osValue).join(', '); + }, [os]); + return osLabel ? ( +
+ + + + +
+ ) : null; +}); +OsCondition.displayName = 'OsCondition'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx similarity index 82% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx index 3aea8d5ed006..a3575c184522 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/os_conditions/os_conditions.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; @@ -35,6 +33,7 @@ describe('OsCondition', () => { expect(wrapper.container).toMatchSnapshot(); }); it('should return any os sent', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const wrapper = render(); expect(wrapper.getByTestId('osLabel')).toHaveTextContent(i18n.CONDITION_OS); expect(wrapper.getByTestId('osValue')).toHaveTextContent( diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts new file mode 100644 index 000000000000..a69a0f16c1d7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/conditions/types.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { + EntryExists, + EntryList, + EntryMatch, + EntryMatchAny, + EntryMatchWildcard, + EntryNested, + ExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { ElementType } from 'react'; + +export type Entry = + | EntryExists + | EntryList + | EntryMatch + | EntryMatchAny + | EntryMatchWildcard + | EntryNested; + +export type Entries = ExceptionListItemSchema['entries']; +export interface CriteriaConditionsProps { + entries: Entries; + dataTestSubj: string; + os?: ExceptionListItemSchema['os_types']; + showValueListModal: ElementType; +} diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx similarity index 94% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx index aeaf5755ea1d..b3f06eddec71 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx similarity index 91% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx index 44456a130687..52d2f730b33b 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/exception_item_card.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React, { FC, ElementType } from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx similarity index 81% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx index 5de4f5d729f0..9127589b5b56 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/header.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx new file mode 100644 index 000000000000..88eb6233a935 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/header/index.tsx @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { HeaderMenu } from '../../header_menu'; + +export interface ExceptionItemCardHeaderProps { + item: ExceptionListItemSchema; + actions: Array<{ key: string; icon: string; label: string | boolean; onClick: () => void }>; + disableActions?: boolean; + dataTestSubj: string; +} + +export const ExceptionItemCardHeader = memo( + ({ item, actions, disableActions = false, dataTestSubj }) => { + return ( + + + +

{item.name}

+
+
+ + + +
+ ); + } +); + +ExceptionItemCardHeader.displayName = 'ExceptionItemCardHeader'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts new file mode 100644 index 000000000000..2d2b38d288da --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './conditions'; +export * from './header'; +export * from './meta'; +export * from './comments'; +export * from './exception_item_card'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/__snapshots__/details_info.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/__snapshots__/details_info.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/__snapshots__/details_info.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/__snapshots__/details_info.test.tsx.snap diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx new file mode 100644 index 000000000000..3950d674a1ad --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/details_info.test.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { MetaInfoDetails } from '.'; + +describe('MetaInfoDetails', () => { + it('should render lastUpdate as string', () => { + const wrapper = render( + + ); + expect(wrapper.container).toMatchSnapshot(); + expect(wrapper.getByTestId('MetaInfoDetailslastUpdate')).toHaveTextContent('last update'); + }); + it('should render lastUpdate as JSX Element', () => { + const wrapper = render( + Last update value

} + lastUpdateValue="value" + /> + ); + expect(wrapper.container).toMatchSnapshot(); + expect(wrapper.getByTestId('MetaInfoDetailslastUpdate')).toHaveTextContent('Last update value'); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx new file mode 100644 index 000000000000..209ce3b59553 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/details_info/index.tsx @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import { EuiBadge, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import * as i18n from '../../translations'; + +interface MetaInfoDetailsProps { + label: string; + lastUpdate: JSX.Element | string; + lastUpdateValue?: string; + dataTestSubj?: string; +} + +const euiBadgeFontFamily = css` + font-family: ${euiThemeVars.euiFontFamily}; +`; +export const MetaInfoDetails = memo( + ({ label, lastUpdate, lastUpdateValue, dataTestSubj }) => { + return ( + + + + {label} + + + + + {lastUpdate} + + + {lastUpdateValue != null && ( + <> + + + {i18n.EXCEPTION_ITEM_CARD_META_BY} + + + + + + + {lastUpdateValue} + + + + + + )} + + ); + } +); + +MetaInfoDetails.displayName = 'MetaInfoDetails'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx new file mode 100644 index 000000000000..8c7734ab51c9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/index.tsx @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo, useMemo } from 'react'; +import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; +import * as i18n from '../translations'; +import type { Rule } from '../../types'; +import { MetaInfoDetails } from './details_info'; +import { HeaderMenu } from '../../header_menu'; +import { generateLinkedRulesMenuItems } from '../../generate_linked_rules_menu_item'; + +const itemCss = css` + border-right: 1px solid #d3dae6; + padding: ${euiThemeVars.euiSizeS} ${euiThemeVars.euiSizeM} ${euiThemeVars.euiSizeS} 0; +`; + +export interface ExceptionItemCardMetaInfoProps { + item: ExceptionListItemSchema; + rules: Rule[]; + dataTestSubj: string; + formattedDateComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common +} + +export const ExceptionItemCardMetaInfo = memo( + ({ item, rules, dataTestSubj, securityLinkAnchorComponent, formattedDateComponent }) => { + const FormattedDateComponent = formattedDateComponent; + + const referencedLinks = useMemo( + () => + generateLinkedRulesMenuItems({ + dataTestSubj, + linkedRules: rules, + securityLinkAnchorComponent, + }), + [dataTestSubj, rules, securityLinkAnchorComponent] + ); + + const isExpired = useMemo( + () => (item.expire_time ? new Date(item.expire_time) <= new Date() : false), + [item] + ); + + return ( + + {FormattedDateComponent !== null && ( + <> + + + } + lastUpdateValue={item.created_by} + dataTestSubj={`${dataTestSubj || ''}CreatedBy`} + /> + + + + + } + lastUpdateValue={item.updated_by} + dataTestSubj={`${dataTestSubj || ''}UpdatedBy`} + /> + + {item.expire_time != null && ( + <> + + + } + dataTestSubj={`${dataTestSubj || ''}ExpireTime`} + /> + + + )} + + )} + + + + + ); + } +); +ExceptionItemCardMetaInfo.displayName = 'ExceptionItemCardMetaInfo'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx similarity index 90% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx index 10570b263781..f7a94d9d76ff 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/meta/meta.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts new file mode 100644 index 000000000000..9b1a64bd6cf4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/translations.ts @@ -0,0 +1,179 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const exceptionItemCardEditButton = (listType: string) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.editItemButton', { + values: { listType }, + defaultMessage: 'Edit {listType} exception', + }); + +export const exceptionItemCardDeleteButton = (listType: string) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.deleteItemButton', { + values: { listType }, + defaultMessage: 'Delete {listType} exception', + }); + +export const EXCEPTION_ITEM_CARD_CREATED_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.createdLabel', + { + defaultMessage: 'Created', + } +); + +export const EXCEPTION_ITEM_CARD_UPDATED_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.updatedLabel', + { + defaultMessage: 'Updated', + } +); + +export const EXCEPTION_ITEM_CARD_EXPIRES_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.expiresLabel', + { + defaultMessage: 'Expires at', + } +); + +export const EXCEPTION_ITEM_CARD_EXPIRED_LABEL = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.expiredLabel', + { + defaultMessage: 'Expired at', + } +); + +export const EXCEPTION_ITEM_CARD_META_BY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.metaDetailsBy', + { + defaultMessage: 'by', + } +); + +export const exceptionItemCardCommentsAccordion = (comments: number) => + i18n.translate('exceptionList-components.exceptions.exceptionItem.card.showCommentsLabel', { + values: { comments }, + defaultMessage: 'Show {comments, plural, =1 {comment} other {comments}} ({comments})', + }); + +export const CONDITION_OPERATOR_TYPE_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator', + { + defaultMessage: 'IS', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchOperator.not', + { + defaultMessage: 'IS NOT', + } +); + +export const CONDITION_OPERATOR_TYPE_WILDCARD_MATCHES = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardMatchesOperator', + { + defaultMessage: 'MATCHES', + } +); + +export const CONDITION_OPERATOR_TYPE_WILDCARD_DOES_NOT_MATCH = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.wildcardDoesNotMatchOperator', + { + defaultMessage: 'DOES NOT MATCH', + } +); + +export const CONDITION_OPERATOR_TYPE_NESTED = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.nestedOperator', + { + defaultMessage: 'has', + } +); + +export const CONDITION_OPERATOR_TYPE_MATCH_ANY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator', + { + defaultMessage: 'is one of', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_MATCH_ANY = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.matchAnyOperator.not', + { + defaultMessage: 'is not one of', + } +); + +export const CONDITION_OPERATOR_TYPE_EXISTS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator', + { + defaultMessage: 'exists', + } +); + +export const CONDITION_OPERATOR_TYPE_DOES_NOT_EXIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.existsOperator.not', + { + defaultMessage: 'does not exist', + } +); + +export const CONDITION_OPERATOR_TYPE_LIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator', + { + defaultMessage: 'included in', + } +); + +export const CONDITION_OPERATOR_TYPE_NOT_IN_LIST = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.listOperator.not', + { + defaultMessage: 'is not included in', + } +); + +export const CONDITION_AND = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.and', + { + defaultMessage: 'AND', + } +); + +export const CONDITION_OS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.os', + { + defaultMessage: 'OS', + } +); + +export const OS_WINDOWS = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.windows', + { + defaultMessage: 'Windows', + } +); + +export const OS_LINUX = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.linux', + { + defaultMessage: 'Linux', + } +); + +export const OS_MAC = i18n.translate( + 'exceptionList-components.exceptions.exceptionItem.card.conditions.macos', + { + defaultMessage: 'Mac', + } +); + +export const AFFECTED_RULES = (numRules: number) => + i18n.translate('exceptionList-components.exceptions.card.exceptionItem.affectedRules', { + values: { numRules }, + defaultMessage: 'Affects {numRules} {numRules, plural, =1 {rule} other {rules}}', + }); diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts similarity index 90% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts index 5c04c8772714..1a144182eeed 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts similarity index 86% rename from packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts index 2978dfb12c72..f3da4ec92595 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_item_card/use_exception_item_card.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { useCallback, useMemo } from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx similarity index 96% rename from packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx index e60cff40626f..936a58b670f5 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/exception_items.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx new file mode 100644 index 000000000000..6fde321cfcb9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/exception_items/index.tsx @@ -0,0 +1,153 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ElementType } from 'react'; +import { css } from '@emotion/react'; +import type { FC } from 'react'; +import { EuiCommentProps, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; + +import type { + CommentsArray, + ExceptionListItemSchema, + ExceptionListTypeEnum, +} from '@kbn/securitysolution-io-ts-list-types'; + +import { euiThemeVars } from '@kbn/ui-theme'; +import { EmptyViewerState, ExceptionItemCard, Pagination, PaginationProps } from '../..'; + +import type { + RuleReferences, + ExceptionListItemIdentifiers, + ViewerStatus, + GetExceptionItemProps, +} from '../types'; + +const exceptionItemCss = css` + margin: ${euiThemeVars.euiSize} 0; + &div:first-child { + margin: ${euiThemeVars.euiSizeXS} 0 ${euiThemeVars.euiSize}; + } +`; + +interface ExceptionItemsProps { + lastUpdated: string | number | null; + viewerStatus: ViewerStatus; + isReadOnly: boolean; + emptyViewerTitle?: string; + emptyViewerBody?: string; + emptyViewerButtonText?: string; + exceptions: ExceptionListItemSchema[]; + listType: ExceptionListTypeEnum; + ruleReferences: RuleReferences; + pagination: PaginationProps['pagination']; + editActionLabel?: string; + deleteActionLabel?: string; + dataTestSubj?: string; + securityLinkAnchorComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + formattedDateComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + exceptionsUtilityComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + getFormattedComments: (comments: CommentsArray) => EuiCommentProps[]; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + onCreateExceptionListItem?: () => void; + onDeleteException: (arg: ExceptionListItemIdentifiers) => void; + onEditExceptionItem: (item: ExceptionListItemSchema) => void; + onPaginationChange: (arg: GetExceptionItemProps) => void; + showValueListModal: ElementType; +} + +const ExceptionItemsComponent: FC = ({ + lastUpdated, + viewerStatus, + isReadOnly, + exceptions, + listType, + ruleReferences, + emptyViewerTitle, + emptyViewerBody, + emptyViewerButtonText, + pagination, + dataTestSubj, + editActionLabel, + deleteActionLabel, + securityLinkAnchorComponent, + exceptionsUtilityComponent, + formattedDateComponent, + getFormattedComments, + onPaginationChange, + onDeleteException, + onEditExceptionItem, + onCreateExceptionListItem, + showValueListModal, +}) => { + const ExceptionsUtility = exceptionsUtilityComponent; + if (!exceptions.length || viewerStatus) + return ( + + ); + const ShowValueListModal = showValueListModal; + return ( + <> + + + + + {exceptions.map((exception) => ( + + + + ))} + + + + + + ); +}; + +ExceptionItemsComponent.displayName = 'ExceptionItemsComponent'; + +export const ExceptionItems = React.memo(ExceptionItemsComponent); + +ExceptionItems.displayName = 'ExceptionsItems'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/__snapshots__/generate_linked_rules_menu_item.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/__snapshots__/generate_linked_rules_menu_item.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/__snapshots__/generate_linked_rules_menu_item.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/__snapshots__/generate_linked_rules_menu_item.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx similarity index 80% rename from packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx index 01f708a0f6bd..2bf26f551fb0 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/generate_linked_rules_menu_item.test.tsx @@ -1,15 +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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { render } from '@testing-library/react'; -import { ReactElement } from 'react'; -import { ElementType } from 'react'; +import { ReactElement, ElementType } from 'react'; import { generateLinkedRulesMenuItems } from '.'; import { rules } from '../mocks/rule_references.mock'; import { @@ -45,7 +42,7 @@ describe('generateLinedRulesMenuItems', () => { leftIcon: 'check', }) as ReactElement[]; - result.map((link) => { + result.forEach((link) => { const wrapper = render(link); expect(wrapper.container).toMatchSnapshot(); expect(wrapper.getByTestId('generateLinedRulesMenuItemsTestActionItem1a2b3c')); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx new file mode 100644 index 000000000000..9187d0975e92 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/index.tsx @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ElementType, ReactElement } from 'react'; +import { EuiContextMenuItem, EuiFlexGroup, EuiFlexItem, EuiIcon, IconType } from '@elastic/eui'; +import { Rule } from '../types'; +import { itemContentCss, containerCss } from './menu_link.styles'; + +interface MenuItemLinkedRulesProps { + leftIcon?: IconType; + dataTestSubj?: string; + linkedRules: Rule[]; + securityLinkAnchorComponent: ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common +} + +export const generateLinkedRulesMenuItems = ({ + dataTestSubj, + linkedRules, + securityLinkAnchorComponent, + leftIcon = '', +}: MenuItemLinkedRulesProps): ReactElement[] | null => { + if (!linkedRules.length || securityLinkAnchorComponent === null) return null; + + const SecurityLinkAnchor = securityLinkAnchorComponent; + return linkedRules.map((rule) => { + return ( + 1 ? containerCss : ''} + data-test-subj={`${dataTestSubj || ''}ActionItem${rule.id}`} + key={rule.id} + > + + {leftIcon ? ( + + + + ) : null} + + + + + + ); + }); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.ts new file mode 100644 index 000000000000..886369b22e23 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/generate_linked_rules_menu_item/menu_link.styles.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; + +export const containerCss = css` + border-bottom: 1px solid ${euiThemeVars.euiColorLightShade}; +`; + +export const itemContentCss = css` + color: ${euiThemeVars.euiColorPrimary}; + flex-basis: content; +`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/header_menu/__snapshots__/header_menu.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/__snapshots__/header_menu.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/header_menu/__snapshots__/header_menu.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/__snapshots__/header_menu.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx similarity index 93% rename from packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx index 7e14b503721b..2869b16e3aaa 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/header_menu.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { createEvent, fireEvent, render } from '@testing-library/react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx new file mode 100644 index 000000000000..bd634b5f6c36 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/header_menu/index.tsx @@ -0,0 +1,137 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FC, ReactElement, useMemo, useState } from 'react'; +import { + EuiButtonEmpty, + EuiButtonEmptyProps, + EuiButtonIcon, + EuiContextMenuItem, + EuiContextMenuPanel, + EuiFlexGroup, + EuiPopover, + PanelPaddingSize, + PopoverAnchorPosition, +} from '@elastic/eui'; + +import { css } from '@emotion/react'; + +export interface Action { + key: string; + icon: string; + label: string | boolean; + disabled?: boolean; + onClick: (e: React.MouseEvent) => void; +} + +interface HeaderMenuComponentProps { + disableActions: boolean; + actions: Action[] | ReactElement[] | null; + text?: string; + iconType?: EuiButtonEmptyProps['iconType']; + iconSide?: EuiButtonEmptyProps['iconSide']; + dataTestSubj?: string; + emptyButton?: boolean; + useCustomActions?: boolean; + anchorPosition?: PopoverAnchorPosition; + panelPaddingSize?: PanelPaddingSize; +} + +const popoverHeightStyle = css` + max-height: 300px; + height: 100%; + overflow-x: hidden; + overflow-y: auto; +`; +const HeaderMenuComponent: FC = ({ + text, + dataTestSubj, + actions, + disableActions, + emptyButton, + useCustomActions, + iconType, + iconSide = 'left', + anchorPosition = 'downCenter', + panelPaddingSize = 's', +}) => { + const [isPopoverOpen, setIsPopoverOpen] = useState(false); + + const onAffectedRulesClick = () => setIsPopoverOpen((isOpen) => !isOpen); + const onClosePopover = () => setIsPopoverOpen(false); + + const itemActions = useMemo(() => { + if (useCustomActions || actions === null) return actions; + return (actions as Action[]).map((action) => ( + { + onClosePopover(); + if (typeof action.onClick === 'function') action.onClick(e); + }} + > + {action.label} + + )); + }, [actions, dataTestSubj, useCustomActions]); + + return ( + + + {text} + + ) : ( + + {text} + + ) + } + onClick={(e) => e.stopPropagation()} + panelPaddingSize={panelPaddingSize} + isOpen={isPopoverOpen} + closePopover={onClosePopover} + anchorPosition={anchorPosition} + data-test-subj={`${dataTestSubj || ''}Items`} + > + {!itemActions ? null : ( + + )} + + + ); +}; +HeaderMenuComponent.displayName = 'HeaderMenuComponent'; + +export const HeaderMenu = React.memo(HeaderMenuComponent); + +HeaderMenu.displayName = 'HeaderMenu'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/__snapshots__/list_header.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/__snapshots__/list_header.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/__snapshots__/list_header.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/__snapshots__/list_header.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/__snapshots__/edit_modal.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/__snapshots__/edit_modal.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/__snapshots__/edit_modal.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/__snapshots__/edit_modal.test.tsx.snap diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx similarity index 93% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx index 39692e35394e..9b23afaf2089 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/edit_modal.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx new file mode 100644 index 000000000000..fda87a768fd0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/index.tsx @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FC } from 'react'; +import { + EuiButton, + EuiButtonEmpty, + EuiFieldText, + EuiForm, + EuiFormRow, + EuiModal, + EuiModalBody, + EuiModalFooter, + EuiModalHeader, + EuiModalHeaderTitle, + EuiTextArea, + EuiProgress, +} from '@elastic/eui'; +import * as i18n from '../../translations'; +import { ListDetails } from '../../types'; +import { useEditModal } from './use_edit_modal'; + +interface EditModalProps { + listDetails: ListDetails; + onSave: (newListDetails: ListDetails) => void; + onCancel: () => void; +} + +const EditModalComponent: FC = ({ listDetails, onSave, onCancel }) => { + const { error, modalFormId, newListDetails, showProgress, onBlur, onSubmit, onChange } = + useEditModal({ + listDetails, + onSave, + }); + return ( + + {showProgress && ( + + )} + + + {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_TITLE(listDetails.name)} + + + + + + + + + + + + + + + + + + {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_CANCEL_BUTTON} + + + + {i18n.EXCEPTION_LIST_HEADER_EDIT_MODAL_SAVE_BUTTON} + + + + ); +}; +EditModalComponent.displayName = 'EditModalComponent'; + +export const EditModal = React.memo(EditModalComponent); + +EditModal.displayName = 'EditModal'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts similarity index 81% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts index 65b532a55c83..a540fdd7704d 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { ChangeEvent, SyntheticEvent } from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts similarity index 80% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts index 6977b8467b94..38c60328ef3d 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/edit_modal/use_edit_modal.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { useGeneratedHtmlId } from '@elastic/eui'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx new file mode 100644 index 000000000000..a6fce8869999 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/index.tsx @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable react/jsx-no-literals */ + +import React from 'react'; +import type { FC } from 'react'; +import { EuiIcon, EuiPageHeader, EuiText } from '@elastic/eui'; +import * as i18n from '../translations'; +import { textCss, descriptionContainerCss, backTextCss } from './list_header.styles'; +import { MenuItems } from './menu_items'; +import { TextWithEdit } from '../text_with_edit'; +import { EditModal } from './edit_modal'; +import { ListDetails, Rule } from '../types'; +import { useExceptionListHeader } from './use_list_header'; +import { textWithEditContainerCss } from '../text_with_edit/text_with_edit.styles'; + +interface ExceptionListHeaderComponentProps { + name: string; + description?: string; + listId: string; + isReadonly: boolean; + linkedRules: Rule[]; + dataTestSubj?: string; + backOptions: BackOptions; + canUserEditList?: boolean; + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + onEditListDetails: (listDetails: ListDetails) => void; + onDeleteList: () => void; + onManageRules: () => void; + onExportList: () => void; + onDuplicateList: () => void; +} + +export interface BackOptions { + pageId: string; + path: string; + dataTestSubj?: string; + onNavigate: (path: string) => void; +} +const ExceptionListHeaderComponent: FC = ({ + name, + description, + listId, + linkedRules, + isReadonly, + dataTestSubj, + securityLinkAnchorComponent, + backOptions, + canUserEditList = true, + onEditListDetails, + onDeleteList, + onManageRules, + onExportList, + onDuplicateList, +}) => { + const { isModalVisible, listDetails, onEdit, onSave, onCancel } = useExceptionListHeader({ + name, + description, + onEditListDetails, + }); + return ( +
+ + } + responsive + data-test-subj={`${dataTestSubj || ''}PageHeader`} + description={ +
+ +
+ {i18n.EXCEPTION_LIST_HEADER_LIST_ID}: + {listId} +
+
+ } + rightSideItems={[ + , + ]} + breadcrumbs={[ + { + text: ( +
+ + {i18n.EXCEPTION_LIST_HEADER_BREADCRUMB} +
+ ), + color: 'primary', + 'aria-current': false, + href: backOptions.path, + onClick: (e) => { + e.preventDefault(); + backOptions.onNavigate(backOptions.path); + }, + }, + ]} + /> + {isModalVisible && ( + + )} +
+ ); +}; + +ExceptionListHeaderComponent.displayName = 'ExceptionListHeaderComponent'; + +export const ExceptionListHeader = React.memo(ExceptionListHeaderComponent); + +ExceptionListHeader.displayName = 'ExceptionListHeader'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.ts new file mode 100644 index 000000000000..7a82cd9bc289 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.styles.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; + +export const headerMenuCss = css` + border-right: 1px solid #d3dae6; + padding: ${euiThemeVars.euiSizeXS} ${euiThemeVars.euiSizeL} ${euiThemeVars.euiSizeXS} 0; +`; + +export const noLinkedRulesCss = css` + width: max-content; +`; + +export const textCss = css` + font-size: ${euiThemeVars.euiFontSize}; + color: ${euiThemeVars.euiTextSubduedColor}; + margin-left: ${euiThemeVars.euiSizeXS}; +`; +export const descriptionContainerCss = css` + margin-top: -${euiThemeVars.euiSizeL}; + margin-bottom: -${euiThemeVars.euiSizeL}; +`; + +export const backTextCss = css` + font-size: ${euiThemeVars.euiFontSizeXS}; +`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx similarity index 94% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx index 9ceb648dfa7e..246e88071608 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/list_header.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/__snapshots__/menu_items.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/__snapshots__/menu_items.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/__snapshots__/menu_items.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/__snapshots__/menu_items.test.tsx.snap diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx new file mode 100644 index 000000000000..798f737be65d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/index.tsx @@ -0,0 +1,134 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiTextColor } from '@elastic/eui'; +import React, { FC, useMemo } from 'react'; +import { HeaderMenu } from '../../header_menu'; +import { headerMenuCss, noLinkedRulesCss } from '../list_header.styles'; +import * as i18n from '../../translations'; +import { Rule } from '../../types'; +import { generateLinkedRulesMenuItems } from '../../generate_linked_rules_menu_item'; +interface MenuItemsProps { + isReadonly: boolean; + dataTestSubj?: string; + linkedRules: Rule[]; + canUserEditList?: boolean; + securityLinkAnchorComponent: React.ElementType; // This property needs to be removed to avoid the Prop Drilling, once we move all the common components from x-pack/security-solution/common + onDeleteList: () => void; + onManageRules: () => void; + onExportList: () => void; + onDuplicateList: () => void; +} + +const MenuItemsComponent: FC = ({ + dataTestSubj, + linkedRules, + securityLinkAnchorComponent, + isReadonly, + canUserEditList = true, + onDeleteList, + onManageRules, + onExportList, + onDuplicateList, +}) => { + const referencedLinks = useMemo( + () => + generateLinkedRulesMenuItems({ + leftIcon: 'check', + dataTestSubj, + linkedRules, + securityLinkAnchorComponent, + }), + [dataTestSubj, linkedRules, securityLinkAnchorComponent] + ); + return ( + + + {linkedRules.length ? ( + + ) : ( + + {i18n.EXCEPTION_LIST_HEADER_LINKED_RULES(linkedRules.length)} + + )} + + + {canUserEditList && ( + + { + if (typeof onManageRules === 'function') onManageRules(); + }} + > + {i18n.EXCEPTION_LIST_HEADER_LINK_RULES_BUTTON} + + + )} + + { + if (typeof onExportList === 'function') onExportList(); + }, + }, + { + key: '2', + icon: 'copy', + label: i18n.EXCEPTION_LIST_HEADER_DUPLICATE_ACTION, + onClick: () => { + if (typeof onDuplicateList === 'function') onDuplicateList(); + }, + disabled: !canUserEditList, + }, + { + key: '3', + icon: 'trash', + label: i18n.EXCEPTION_LIST_HEADER_DELETE_ACTION, + onClick: () => { + if (typeof onDeleteList === 'function') onDeleteList(); + }, + disabled: !canUserEditList, + }, + ]} + disableActions={isReadonly} + anchorPosition="downCenter" + /> + + + ); +}; + +MenuItemsComponent.displayName = 'MenuItemsComponent'; + +export const MenuItems = React.memo(MenuItemsComponent); + +MenuItems.displayName = 'MenuItems'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx similarity index 94% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx index 16072bab295a..8fdf6519cf44 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/menu_items/menu_items.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { fireEvent, render } from '@testing-library/react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts similarity index 86% rename from packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts index e16681d2b184..a49ef8f6f560 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { waitFor, renderHook, act } from '@testing-library/react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts new file mode 100644 index 000000000000..cda4bf346a20 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/list_header/use_list_header.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useState } from 'react'; +import { ListDetails } from '../types'; + +interface UseExceptionListHeaderProps { + name: string; + description?: string; + onEditListDetails: (listDetails: ListDetails) => void; +} +export const useExceptionListHeader = ({ + name, + description, + onEditListDetails, +}: UseExceptionListHeaderProps) => { + const [isModalVisible, setIsModalVisible] = useState(false); + const [listDetails, setListDetails] = useState({ name, description }); + const onEdit = () => { + setIsModalVisible(true); + }; + const onSave = (newListDetails: ListDetails) => { + setListDetails(newListDetails); + if (typeof onEditListDetails === 'function') onEditListDetails(newListDetails); + setTimeout(() => { + setIsModalVisible(false); + }, 200); + }; + const onCancel = () => { + setIsModalVisible(false); + }; + + return { + isModalVisible, + listDetails, + onEdit, + onSave, + onCancel, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx new file mode 100644 index 000000000000..02767cfb979d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/comments.mock.tsx @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import type { Comment, CommentsArray } from '@kbn/securitysolution-io-ts-list-types'; + +export const getCommentsMock = (): Comment => ({ + comment: 'some old comment', + created_at: '2020-04-20T15:25:31.830Z', + created_by: 'some user', + id: 'uuid_here', +}); + +export const getCommentsArrayMock = (): CommentsArray => [getCommentsMock(), getCommentsMock()]; + +export const mockGetFormattedComments = () => + getCommentsArrayMock().map((comment) => ({ + username: comment.created_by, + children:

{comment.comment}

, + })); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.ts new file mode 100644 index 000000000000..34a4e98cf981 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/entry.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Entry } from '../exception_item_card/conditions/types'; + +export const includedListTypeEntry: Entry = { + field: '', + operator: 'included', + type: 'list', + list: { id: 'list_id', type: 'boolean' }, +}; + +export const includedMatchTypeEntry: Entry = { + field: '', + operator: 'included', + type: 'match', + value: 'matches value', +}; + +export const includedExistsTypeEntry: Entry = { + field: '', + operator: 'included', + type: 'exists', +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts new file mode 100644 index 000000000000..a34ddc4dd484 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/exception_list_item_schema.mock.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +export const getExceptionListItemSchemaMock = ( + overrides?: Partial +): ExceptionListItemSchema => ({ + _version: undefined, + comments: [], + created_at: '2020-04-20T15:25:31.830Z', + created_by: 'some user', + description: 'some description', + entries: [ + { + entries: [ + { field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }, + ], + field: 'some.parentField', + type: 'nested', + }, + { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, + ], + expire_time: undefined, + id: '1', + item_id: 'endpoint_list_item', + list_id: 'endpoint_list_id', + meta: {}, + name: 'some name', + namespace_type: 'single', + os_types: [], + tags: ['user added string for a tag', 'malware'], + tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', + type: 'simple', + updated_at: '2020-04-20T15:25:31.830Z', + updated_by: 'some user', + ...(overrides || {}), +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.ts new file mode 100644 index 000000000000..5ee301495e6f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/header.mock.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const handleEdit = jest.fn(); +export const handleDelete = jest.fn(); +export const actions = [ + { + key: 'edit', + icon: 'pencil', + label: 'Edit detection exception', + onClick: handleEdit, + }, + { + key: 'delete', + icon: 'trash', + label: 'Delete detection exception', + onClick: handleDelete, + }, +]; +export const actionsWithDisabledDelete = [ + { + key: 'edit', + icon: 'pencil', + label: 'Edit detection exception', + onClick: handleEdit, + }, + { + key: 'delete', + icon: 'trash', + disabled: true, + label: 'Delete detection exception', + onClick: handleDelete, + }, +]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.ts new file mode 100644 index 000000000000..c4eaff274a74 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/rule_references.mock.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Rule, RuleReference } from '../types'; + +export const rules: Rule[] = [ + { + exceptions_list: [ + { + id: '123', + list_id: 'i_exist', + namespace_type: 'single', + type: 'detection', + }, + { + id: '456', + list_id: 'i_exist_2', + namespace_type: 'single', + type: 'detection', + }, + ], + id: '1a2b3c', + name: 'Simple Rule Query', + rule_id: 'rule-2', + }, +]; + +export const ruleReference: RuleReference = { + name: 'endpoint list', + id: 'endpoint_list', + referenced_rules: rules, + listId: 'endpoint_list_id', +}; + +export const ruleReferences = { + endpoint_list_id: ruleReference, +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx new file mode 100644 index 000000000000..03c44d7e9166 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/security_link_component.mock.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ReactElement } from 'react'; +import { generateLinkedRulesMenuItems } from '../generate_linked_rules_menu_item'; +import { rules } from './rule_references.mock'; +export const securityLinkAnchorComponentMock = ({ + referenceName, + referenceId, +}: { + referenceName: string; + referenceId: string; +}) => ( + +); + +export const getSecurityLinkAction = (dataTestSubj: string) => + generateLinkedRulesMenuItems({ + dataTestSubj, + linkedRules: [ + ...rules, + { + exceptions_list: [], + id: '2a2b3c', + name: 'Simple Rule Query 2', + rule_id: 'rule-2', + }, + ], + securityLinkAnchorComponent: securityLinkAnchorComponentMock, + }) as ReactElement[]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx new file mode 100644 index 000000000000..e0f9f5d700be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/mocks/value_list_modal.mock.tsx @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; + +export const mockShowValueListModal = jest.fn(); +export const MockedShowValueListModal = (props: { children: React.ReactNode }) => { + mockShowValueListModal(props); + return <>{props.children}; +}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx similarity index 84% rename from packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx index 5eaab267abb5..1467653d432b 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { fireEvent, render } from '@testing-library/react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx new file mode 100644 index 000000000000..e7275c4be2c2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/pagination.tsx @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import type { FC } from 'react'; +import { EuiTablePagination } from '@elastic/eui'; + +import type { PaginationProps } from '../types'; +import { usePagination } from './use_pagination'; + +const PaginationComponent: FC = ({ + dataTestSubj, + ariaLabel, + pagination, + onPaginationChange, +}) => { + const { + pageIndex, + pageCount, + pageSize, + pageSizeOptions, + + handleItemsPerPageChange, + handlePageIndexChange, + } = usePagination({ pagination, onPaginationChange }); + + return ( + + ); +}; + +PaginationComponent.displayName = 'PaginationComponent'; + +export const Pagination = React.memo(PaginationComponent); + +Pagination.displayName = 'Pagination'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts similarity index 87% rename from packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts index e90408f1e161..2126ace9191b 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { renderHook, act } from '@testing-library/react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts similarity index 76% rename from packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts index da96624f8b43..289d5ebcaa26 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/pagination/use_pagination.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { useCallback, useMemo } from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx new file mode 100644 index 000000000000..4339d95b6c4c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/partial_code_signature_callout/index.tsx @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { i18n } from '@kbn/i18n'; + +import { EuiCallOut } from '@elastic/eui'; + +export const PartialCodeSignatureCallout = () => { + return ( + + + + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx new file mode 100644 index 000000000000..dd36c16b9bd8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/index.tsx @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useCallback } from 'react'; +import type { FC } from 'react'; + +import type { EuiSearchBarProps, IconType, SearchFilterConfig } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiButton, EuiSearchBar } from '@elastic/eui'; +import type { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import type { GetExceptionItemProps } from '../types'; + +const ITEMS_SCHEMA = { + strict: true, + fields: { + created_by: { + type: 'string', + }, + description: { + type: 'string', + }, + id: { + type: 'string', + }, + item_id: { + type: 'string', + }, + list_id: { + type: 'string', + }, + name: { + type: 'string', + }, + os_types: { + type: 'string', + }, + tags: { + type: 'string', + }, + }, +}; +interface SearchBarProps { + addExceptionButtonText?: string; + placeholdertext?: string; + canAddException?: boolean; // TODO what is the default value + + // TODO: REFACTOR: not to send the listType and handle it in the Parent + // Exception list type used to determine what type of item is + // being created when "onAddExceptionClick" is invoked + listType: ExceptionListTypeEnum; + isSearching?: boolean; + dataTestSubj?: string; + filters?: SearchFilterConfig[]; // TODO about filters + isButtonFilled?: boolean; + buttonIconType?: IconType; + onSearch: (arg: GetExceptionItemProps) => void; + onAddExceptionClick: (type: ExceptionListTypeEnum) => void; +} +const SearchBarComponent: FC = ({ + addExceptionButtonText, + placeholdertext, + canAddException, + listType, + isSearching, + dataTestSubj, + filters = [], + isButtonFilled = true, + buttonIconType, + onSearch, + onAddExceptionClick, +}) => { + const handleOnSearch = useCallback>( + ({ queryText }): void => { + onSearch({ search: queryText }); + }, + [onSearch] + ); + + const handleAddException = useCallback(() => { + // TODO: ASK YARA why we need to send the listType + onAddExceptionClick(listType); + }, [onAddExceptionClick, listType]); + + return ( + + + + + {!canAddException && ( + + + {addExceptionButtonText} + + + )} + + ); +}; + +SearchBarComponent.displayName = 'SearchBarComponent'; + +export const SearchBar = React.memo(SearchBarComponent); + +SearchBar.displayName = 'SearchBar'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx similarity index 88% rename from packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx index b1eadded0e3f..a7eaa7ba47ad 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/search_bar/search_bar.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/__snapshots__/text_with_edit.test.tsx.snap b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/__snapshots__/text_with_edit.test.tsx.snap similarity index 100% rename from packages/kbn-securitysolution-exception-list-components/src/text_with_edit/__snapshots__/text_with_edit.test.tsx.snap rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/__snapshots__/text_with_edit.test.tsx.snap diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx new file mode 100644 index 000000000000..1428dcfa238e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/index.tsx @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FC } from 'react'; +import { EuiButtonIcon, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { Interpolation, Theme } from '@emotion/react'; +import { textWithEditContainerCss, editIconCss } from './text_with_edit.styles'; +interface TextWithEditProps { + isReadonly: boolean; + dataTestSubj?: string; + text: string; + textCss?: Interpolation; + onEdit?: () => void; +} + +const TextWithEditComponent: FC = ({ + isReadonly, + dataTestSubj, + text, + onEdit, + textCss, +}) => { + return ( + + + + {text} + + + + {isReadonly ? null : ( + (typeof onEdit === 'function' ? onEdit() : null)} + /> + )} + + + ); +}; +TextWithEditComponent.displayName = 'TextWithEditComponent'; + +export const TextWithEdit = React.memo(TextWithEditComponent); + +TextWithEdit.displayName = 'TextWithEdit'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.ts new file mode 100644 index 000000000000..d61aaab0f9be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.styles.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { css } from '@emotion/react'; +import { euiThemeVars } from '@kbn/ui-theme'; + +export const textWithEditContainerCss = css` + display: flex; + width: fit-content; + align-items: baseline; + padding-bottom: ${euiThemeVars.euiSizeS}; + h1 { + margin-bottom: 0; + } +`; +export const editIconCss = css` + button { + margin-left: -${euiThemeVars.euiSizeM}; + } +`; diff --git a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx similarity index 84% rename from packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx index eab0eb7817d8..24b5eec6e335 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/text_with_edit/text_with_edit.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { fireEvent, render } from '@testing-library/react'; @@ -35,6 +33,7 @@ describe('TextWithEdit', () => { isReadonly={false} dataTestSubj="TextWithEditTest" text="Test" + // eslint-disable-next-line @typescript-eslint/no-explicit-any onEdit={onEdit as any} /> ); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/translations.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/translations.ts new file mode 100644 index 000000000000..5660ac3564c7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/translations.ts @@ -0,0 +1,154 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const EMPTY_VIEWER_STATE_EMPTY_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty.title', + { + defaultMessage: 'Add exceptions to this list', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty.body', + { + defaultMessage: 'There is no exception in your list. Create your first exception.', + } +); +export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty_search.search.title', + { + defaultMessage: 'No results match your search criteria', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_SEARCH_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.empty_search.body', + { + defaultMessage: 'Try modifying your search', + } +); + +export const EMPTY_VIEWER_STATE_EMPTY_VIEWER_BUTTON = (exceptionType: string) => + i18n.translate('exceptionList-components.empty.viewer.state.empty.viewer_button', { + values: { exceptionType }, + defaultMessage: 'Create {exceptionType} exception', + }); + +export const EMPTY_VIEWER_STATE_ERROR_TITLE = i18n.translate( + 'exceptionList-components.empty.viewer.state.error_title', + { + defaultMessage: 'Unable to load exception items', + } +); + +export const EMPTY_VIEWER_STATE_ERROR_BODY = i18n.translate( + 'exceptionList-components.empty.viewer.state.error_body', + { + defaultMessage: + 'There was an error loading the exception items. Contact your administrator for help.', + } +); +export const EXCEPTION_LIST_HEADER_EXPORT_ACTION = i18n.translate( + 'exceptionList-components.exception_list_header_export_action', + { + defaultMessage: 'Export exception list', + } +); +export const EXCEPTION_LIST_HEADER_DELETE_ACTION = i18n.translate( + 'exceptionList-components.exception_list_header_delete_action', + { + defaultMessage: 'Delete exception list', + } +); +export const EXCEPTION_LIST_HEADER_DUPLICATE_ACTION = i18n.translate( + 'exceptionList-components.exception_list_header_duplicate_action', + { + defaultMessage: 'Duplicate exception list', + } +); +export const EXCEPTION_LIST_HEADER_LINK_RULES_BUTTON = i18n.translate( + 'exceptionList-components.exception_list_header_link_rules_button', + { + defaultMessage: 'Link rules', + } +); + +export const EXCEPTION_LIST_HEADER_LINKED_RULES = (noOfRules: number) => + i18n.translate('exceptionList-components.exception_list_header_linked_rules', { + values: { noOfRules }, + defaultMessage: 'Linked to {noOfRules} rules', + }); + +export const EXCEPTION_LIST_HEADER_BREADCRUMB = i18n.translate( + 'exceptionList-components.exception_list_header_breadcrumb', + { + defaultMessage: 'Shared Exception Lists', + } +); + +export const EXCEPTION_LIST_HEADER_LIST_ID = i18n.translate( + 'exceptionList-components.exception_list_header_list_id', + { + defaultMessage: 'List ID', + } +); + +export const EXCEPTION_LIST_HEADER_NAME = i18n.translate( + 'exceptionList-components.exception_list_header_name', + { + defaultMessage: 'Add a name', + } +); + +export const EXCEPTION_LIST_HEADER_DESCRIPTION = i18n.translate( + 'exceptionList-components.exception_list_header_description', + { + defaultMessage: 'Add a description', + } +); + +export const EXCEPTION_LIST_HEADER_EDIT_MODAL_TITLE = (listName: string) => + i18n.translate('exceptionList-components.exception_list_header_edit_modal_name', { + defaultMessage: 'Edit {listName}', + values: { listName }, + }); + +export const EXCEPTION_LIST_HEADER_EDIT_MODAL_SAVE_BUTTON = i18n.translate( + 'exceptionList-components.exception_list_header_edit_modal_save_button', + { + defaultMessage: 'Save', + } +); + +export const EXCEPTION_LIST_HEADER_EDIT_MODAL_CANCEL_BUTTON = i18n.translate( + 'exceptionList-components.exception_list_header_edit_modal_cancel_button', + { + defaultMessage: 'Cancel', + } +); +export const EXCEPTION_LIST_HEADER_NAME_TEXTBOX = i18n.translate( + 'exceptionList-components.exception_list_header_Name_textbox', + { + defaultMessage: 'Name', + } +); + +export const EXCEPTION_LIST_HEADER_DESCRIPTION_TEXTBOX = i18n.translate( + 'exceptionList-components.exception_list_header_description_textbox', + { + defaultMessage: 'Description (optional)', + } +); + +export const LIST_NAME_REQUIRED_ERROR = i18n.translate( + 'exceptionList-components.exception_list_header_description_textboxexceptionList-components.exception_list_header_name_required_eror', + { + defaultMessage: 'List name cannot be empty', + } +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/types/index.ts new file mode 100644 index 000000000000..d628cd013797 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/types/index.ts @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ListArray } from '@kbn/securitysolution-io-ts-list-types'; + +import type { Pagination } from '@elastic/eui'; +import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; + +export interface GetExceptionItemProps { + pagination?: PaginationProps['pagination']; + search?: string; + filters?: string; +} + +export interface PaginationProps { + dataTestSubj?: string; + ariaLabel?: string; + pagination: Pagination & { pageSize: number }; + onPaginationChange: (arg: GetExceptionItemProps) => void; +} + +export enum ViewerStatus { + ERROR = 'error', + EMPTY = 'empty', + EMPTY_SEARCH = 'empty_search', + LOADING = 'loading', + SEARCHING = 'searching', + DELETING = 'deleting', +} + +export interface ExceptionListSummaryProps { + pagination: Pagination; + // Corresponds to last time exception items were fetched + lastUpdated: string | number | null; +} + +export type ViewerFlyoutName = 'addException' | 'editException' | null; + +export interface RuleReferences { + [key: string]: RuleReference; +} + +export interface ExceptionListItemIdentifiers { + id: string; + name: string; + namespaceType: NamespaceType; +} + +export enum ListTypeText { + ENDPOINT = 'endpoint', + DETECTION = 'empty', + RULE_DEFAULT = 'empty_search', +} +export interface Rule { + name: string; + id: string; + rule_id: string; + exceptions_list?: ListArray; +} + +export interface RuleReference { + name: string; + id: string; + referenced_rules: Rule[]; + listId?: string; +} + +export interface ListDetails { + name: string; + description?: string; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts new file mode 100644 index 000000000000..968bc9666b09 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { ValueWithSpaceWarning } from './value_with_space_warning'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts similarity index 84% rename from packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts index 51954c0140e6..570399a5ecb2 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { renderHook } from '@testing-library/react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts new file mode 100644 index 000000000000..252f05f4d102 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/use_value_with_space_warning.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { paramContainsSpace, autoCompletei18n } from '@kbn/securitysolution-autocomplete'; + +interface UseValueWithSpaceWarningResult { + showSpaceWarningIcon: boolean; + warningText: string; +} +interface UseValueWithSpaceWarningProps { + value: string | string[]; + tooltipIconText?: string; +} + +export const useValueWithSpaceWarning = ({ + value, + tooltipIconText, +}: UseValueWithSpaceWarningProps): UseValueWithSpaceWarningResult => { + const showSpaceWarningIcon = Array.isArray(value) + ? value.find(paramContainsSpace) + : paramContainsSpace(value); + + return { + showSpaceWarningIcon: !!showSpaceWarningIcon, + warningText: tooltipIconText || autoCompletei18n.FIELD_SPACE_WARNING, + }; +}; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx similarity index 81% rename from packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx index 8f780181e052..a500f13af6e1 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.test.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx similarity index 75% rename from packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx rename to x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx index c736982142b1..c73a39a516ed 100644 --- a/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/value_with_space_warning/value_with_space_warning.tsx @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import React from 'react'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx new file mode 100644 index 000000000000..b21259f4ed89 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/src/wildcard_with_wrong_operator_callout/index.tsx @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n-react'; +import { i18n } from '@kbn/i18n'; + +import { EuiCallOut } from '@elastic/eui'; + +export const WildCardWithWrongOperatorCallout = () => { + return ( + +

+ + {i18n.translate( + 'exceptionList-components.wildcardWithWrongOperatorCallout.changeTheOperator', + { defaultMessage: 'Change the operator' } + )} + + ), + matches: ( + + {i18n.translate( + 'exceptionList-components.wildcardWithWrongOperatorCallout.matches', + { defaultMessage: 'matches' } + )} + + ), + }} + /> +

+
+ ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/tsconfig.json new file mode 100644 index 000000000000..5378a8fbdfe1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node", + "react", + "@emotion/react/types/css-prop" + ] + }, + "include": [ + "**/*.ts", + "**/*.tsx", + "**/*.d.ts" + ], + "kbn_references": [ + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-autocomplete", + "@kbn/ui-theme", + "@kbn/i18n", + "@kbn/i18n-react", + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-exceptions-common/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/README.md similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/README.md diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts similarity index 78% rename from packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts index a9acaee37cef..2c7dc29dd182 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml similarity index 77% rename from packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml index 5925d0bd923c..e4aa39a5db30 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list/create_exception_list.schema.yaml @@ -59,29 +59,29 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 409: description: Exception list already exists response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts similarity index 85% rename from packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts index 9adf64b6b083..dba75c11fde8 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml similarity index 76% rename from packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml index 47fa2895d27c..a86c6a21e25e 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_exception_list_item/create_exception_list_item.schema.yaml @@ -69,32 +69,32 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 409: description: Exception list item already exists response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: x-codegen-enabled: true @@ -103,7 +103,7 @@ components: type: object properties: comment: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' required: - comment diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts similarity index 88% rename from packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts index 77437ff51618..e2fa379cdc52 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml similarity index 76% rename from packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml index 6162d00d78ae..246c8de363a6 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_rule_exceptions/create_rule_exceptions.schema.yaml @@ -9,7 +9,7 @@ paths: operationId: CreateRuleExceptionListItems x-codegen-enabled: true summary: Create rule exception list items - description: Create exception items that apply to a single detection rule. + description: Create exception items that apply to a single detection rule. parameters: - name: id in: path @@ -45,37 +45,37 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: RuleId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/UUID' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/UUID' CreateRuleExceptionListItemComment: type: object properties: comment: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' required: - comment diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts new file mode 100644 index 000000000000..07650ee2d0c0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.gen.ts @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Create shared exception list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { + ExceptionListName, + ExceptionListDescription, + ExceptionList, +} from '../model/exception_list_common.gen'; + +export type CreateSharedExceptionListRequestBody = z.infer< + typeof CreateSharedExceptionListRequestBody +>; +export const CreateSharedExceptionListRequestBody = z.object({ + name: ExceptionListName, + description: ExceptionListDescription, +}); +export type CreateSharedExceptionListRequestBodyInput = z.input< + typeof CreateSharedExceptionListRequestBody +>; + +export type CreateSharedExceptionListResponse = z.infer; +export const CreateSharedExceptionListResponse = ExceptionList; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml new file mode 100644 index 000000000000..5ac7e8e78ccb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/create_shared_exceptions_list/create_shared_exceptions_list.schema.yaml @@ -0,0 +1,68 @@ +openapi: 3.0.0 +info: + title: Create shared exception list API endpoint + version: '2023-10-31' +paths: + /api/exceptions/shared: + post: + x-labels: [serverless, ess] + operationId: CreateSharedExceptionList + x-codegen-enabled: true + summary: Create a shared exception list + description: | + An exception list groups exception items and can be associated with detection rules. A shared exception list can apply to multiple detection rules. + > info + > All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListName' + description: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListDescription' + required: + - name + - description + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 409: + description: Exception list already exists response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts index a12512aab137..0842dc7c7463 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml new file mode 100644 index 000000000000..709afe0fdff6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list/delete_exception_list.schema.yaml @@ -0,0 +1,70 @@ +openapi: 3.0.0 +info: + title: Delete exception list API endpoint + version: '2023-10-31' +paths: + /api/exception_lists: + delete: + x-labels: [serverless, ess] + operationId: DeleteExceptionList + x-codegen-enabled: true + summary: Delete an exception list + description: Delete an exception list using the `id` or `list_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `list_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' + - name: list_id + in: query + required: false + description: Either `id` or `list_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' + - name: namespace_type + in: query + required: false + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + default: single + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts similarity index 76% rename from packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts index a93af0cf3d4c..429568c33f1c 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml new file mode 100644 index 000000000000..22344db77f61 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/delete_exception_list_item/delete_exception_list_item.schema.yaml @@ -0,0 +1,70 @@ +openapi: 3.0.0 +info: + title: Delete exception list item API endpoint + version: '2023-10-31' +paths: + /api/exception_lists/items: + delete: + x-labels: [serverless, ess] + operationId: DeleteExceptionListItem + x-codegen-enabled: true + summary: Delete an exception list item + description: Delete an exception list item using the `id` or `item_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' + - name: item_id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' + - name: namespace_type + in: query + required: false + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + default: single + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts index 61de17abe06f..d259d37b2348 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml new file mode 100644 index 000000000000..a758d2856123 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/duplicate_exception_list/duplicate_exception_list.schema.yaml @@ -0,0 +1,71 @@ +openapi: 3.0.0 +info: + title: Duplicate exception list API endpoint + version: '2023-10-31' +paths: + /api/exception_lists/_duplicate: + post: + x-labels: [serverless, ess] + operationId: DuplicateExceptionList + x-codegen-enabled: true + summary: Duplicate an exception list + description: Duplicate an existing exception list. + parameters: + - name: list_id + in: query + required: true + description: Exception list's human identifier + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' + - name: namespace_type + in: query + required: true + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + - name: include_expired_exceptions + in: query + required: true + description: Determines whether to include expired exceptions in the exported list + schema: + type: string + enum: ['true', 'false'] + default: 'true' + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 405: + description: Exception list to duplicate not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.ts new file mode 100644 index 000000000000..280884c7d749 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.gen.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Export exception list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { + ExceptionListId, + ExceptionListHumanId, + ExceptionNamespaceType, +} from '../model/exception_list_common.gen'; + +export type ExportExceptionListRequestQuery = z.infer; +export const ExportExceptionListRequestQuery = z.object({ + /** + * Exception list's identifier + */ + id: ExceptionListId, + /** + * Exception list's human identifier + */ + list_id: ExceptionListHumanId, + namespace_type: ExceptionNamespaceType, + /** + * Determines whether to include expired exceptions in the exported list + */ + include_expired_exceptions: z.enum(['true', 'false']).default('true'), +}); +export type ExportExceptionListRequestQueryInput = z.input; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml new file mode 100644 index 000000000000..2d5242131adb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/export_exception_list/export_exception_list.schema.yaml @@ -0,0 +1,79 @@ +openapi: 3.0.0 +info: + title: Export exception list API endpoint + version: '2023-10-31' +paths: + /api/exception_lists/_export: + post: + x-labels: [serverless, ess] + operationId: ExportExceptionList + x-codegen-enabled: true + summary: Export an exception list + description: Export an exception list and its associated items to an NDJSON file. + parameters: + - name: id + in: query + required: true + description: Exception list's identifier + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' + - name: list_id + in: query + required: true + description: Exception list's human identifier + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' + - name: namespace_type + in: query + required: true + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + - name: include_expired_exceptions + in: query + required: true + description: Determines whether to include expired exceptions in the exported list + schema: + type: string + enum: ['true', 'false'] + default: 'true' + responses: + 200: + description: Successful response + content: + application/ndjson: + schema: + type: string + format: binary + description: A `.ndjson` file containing specified exception list and its items + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts similarity index 86% rename from packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts index 99ed1b3a31dd..d7606bbccff3 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml index e40f780af03e..fc7680249242 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_list_items/find_exception_list_items.schema.yaml @@ -65,7 +65,7 @@ paths: required: false description: Determines which field is used to sort the results schema: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - name: sort_order in: query required: false @@ -107,34 +107,34 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 404: description: Exception list not found response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: FindExceptionListItemsFilter: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' diff --git a/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts similarity index 85% rename from packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts index 83a68b4232e8..82f5de2f5a15 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml similarity index 80% rename from packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml index c46dacbab01d..e5ef4f83a134 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/find_exception_lists/find_exception_lists.schema.yaml @@ -93,26 +93,26 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: diff --git a/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts similarity index 86% rename from packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts index ea24803e7945..738ce79dd97d 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml similarity index 83% rename from packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml index 8ae3ac1aa2c0..75778f07c0c8 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/import_exceptions/import_exceptions.schema.yaml @@ -92,26 +92,26 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/index.ts new file mode 100644 index 000000000000..014fe58cfce0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './model/exception_list_common.gen'; +export * from './model/exception_list_item_entry.gen'; +export * from './create_exception_list_item/create_exception_list_item.gen'; +export * from './create_rule_exceptions/create_rule_exceptions.gen'; +export * from './create_shared_exceptions_list/create_shared_exceptions_list.gen'; +export * from './create_exception_list/create_exception_list.gen'; +export * from './delete_exception_list_item/delete_exception_list_item.gen'; +export * from './delete_exception_list/delete_exception_list.gen'; +export * from './duplicate_exception_list/duplicate_exception_list.gen'; +export * from './export_exception_list/export_exception_list.gen'; +export * from './find_exception_list_items/find_exception_list_items.gen'; +export * from './find_exception_lists/find_exception_lists.gen'; +export * from './import_exceptions/import_exceptions.gen'; +export * from './read_exception_list_item/read_exception_list_item.gen'; +export * from './read_exception_list/read_exception_list.gen'; +export * from './read_exception_list_summary/read_exception_list_summary.gen'; +export * from './update_exception_list_item/update_exception_list_item.gen'; +export * from './update_exception_list/update_exception_list.gen'; diff --git a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts similarity index 94% rename from packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts index 1f2d9e7387da..2ee44afa69b9 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml similarity index 81% rename from packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml index ebcecc9c916f..8d8cdf82b6d9 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_common.schema.yaml @@ -7,10 +7,10 @@ components: x-codegen-enabled: true schemas: ExceptionListId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' ExceptionListHumanId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' description: Human readable string identifier, e.g. `trusted-linux-processes` ExceptionListType: @@ -122,17 +122,17 @@ components: - updated_by ExceptionListItemId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' ExceptionListItemHumanId: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' ExceptionListItemType: type: string enum: [simple] ExceptionListItemName: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' ExceptionListItemDescription: type: string @@ -144,7 +144,7 @@ components: ExceptionListItemTags: type: array items: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' ExceptionListItemOsType: type: string @@ -162,19 +162,19 @@ components: type: object properties: id: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' comment: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' created_at: type: string format: date-time created_by: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' updated_at: type: string format: date-time updated_by: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' required: - id - comment @@ -278,7 +278,7 @@ components: comments: $ref: '#/components/schemas/ExceptionListItemCommentArray' version: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' tie_breaker_id: type: string created_at: diff --git a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts similarity index 90% rename from packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts index 0b7f0233ba42..272e5e7d6c35 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml new file mode 100644 index 000000000000..73fe9ea229bc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/model/exception_list_item_entry.schema.yaml @@ -0,0 +1,147 @@ +openapi: 3.0.0 +info: + title: Common Exception List Item Entry Attributes + version: 'not applicable' +paths: {} +components: + x-codegen-enabled: true + schemas: + ExceptionListItemEntryOperator: + type: string + enum: [excluded, included] + + ExceptionListItemEntryMatch: + type: object + properties: + type: + type: string + enum: [match] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + value: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + operator: + $ref: '#/components/schemas/ExceptionListItemEntryOperator' + required: + - type + - field + - value + - operator + + ExceptionListItemEntryMatchAny: + type: object + properties: + type: + type: string + enum: [match_any] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + value: + type: array + items: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + minItems: 1 + operator: + $ref: '#/components/schemas/ExceptionListItemEntryOperator' + required: + - type + - field + - value + - operator + + ExceptionListItemEntryList: + type: object + properties: + type: + type: string + enum: [list] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + list: + type: object + properties: + id: + $ref: '../../../kbn-securitysolution-lists-common/api/model/list_common.schema.yaml#/components/schemas/ListId' + type: + $ref: '../../../kbn-securitysolution-lists-common/api/model/list_common.schema.yaml#/components/schemas/ListType' + required: [id, type] + operator: + $ref: '#/components/schemas/ExceptionListItemEntryOperator' + required: + - type + - field + - list + - operator + + ExceptionListItemEntryExists: + type: object + properties: + type: + type: string + enum: [exists] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + operator: + $ref: '#/components/schemas/ExceptionListItemEntryOperator' + required: + - type + - field + - operator + + ExceptionListItemEntryNestedEntryItem: + oneOf: + - $ref: '#/components/schemas/ExceptionListItemEntryMatch' + - $ref: '#/components/schemas/ExceptionListItemEntryMatchAny' + - $ref: '#/components/schemas/ExceptionListItemEntryExists' + + ExceptionListItemEntryNested: + type: object + properties: + type: + type: string + enum: [nested] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + entries: + type: array + items: + $ref: '#/components/schemas/ExceptionListItemEntryNestedEntryItem' + minItems: 1 + required: + - type + - field + - entries + + ExceptionListItemEntryMatchWildcard: + type: object + properties: + type: + type: string + enum: [wildcard] + field: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + value: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + operator: + $ref: '#/components/schemas/ExceptionListItemEntryOperator' + required: + - type + - field + - value + - operator + + ExceptionListItemEntry: + discriminator: + propertyName: type + anyOf: + - $ref: '#/components/schemas/ExceptionListItemEntryMatch' + - $ref: '#/components/schemas/ExceptionListItemEntryMatchAny' + - $ref: '#/components/schemas/ExceptionListItemEntryList' + - $ref: '#/components/schemas/ExceptionListItemEntryExists' + - $ref: '#/components/schemas/ExceptionListItemEntryNested' + - $ref: '#/components/schemas/ExceptionListItemEntryMatchWildcard' + + ExceptionListItemEntryArray: + type: array + items: + $ref: '#/components/schemas/ExceptionListItemEntry' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts new file mode 100644 index 000000000000..bfa84f18fa7c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts @@ -0,0 +1,425 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Exceptions API client for quickstart + * version: Bundle (no version) + */ + +import type { KbnClient } from '@kbn/test'; +import { ToolingLog } from '@kbn/tooling-log'; +import { ELASTIC_HTTP_VERSION_HEADER } from '@kbn/core-http-common'; +import { replaceParams } from '@kbn/openapi-common/shared'; +import { catchAxiosErrorFormatAndThrow } from '@kbn/securitysolution-utils'; + +import type { + CreateExceptionListItemRequestBodyInput, + CreateExceptionListItemResponse, +} from './create_exception_list_item/create_exception_list_item.gen'; +import type { + CreateExceptionListRequestBodyInput, + CreateExceptionListResponse, +} from './create_exception_list/create_exception_list.gen'; +import type { + CreateRuleExceptionListItemsRequestParamsInput, + CreateRuleExceptionListItemsRequestBodyInput, + CreateRuleExceptionListItemsResponse, +} from './create_rule_exceptions/create_rule_exceptions.gen'; +import type { + CreateSharedExceptionListRequestBodyInput, + CreateSharedExceptionListResponse, +} from './create_shared_exceptions_list/create_shared_exceptions_list.gen'; +import type { + DeleteExceptionListItemRequestQueryInput, + DeleteExceptionListItemResponse, +} from './delete_exception_list_item/delete_exception_list_item.gen'; +import type { + DeleteExceptionListRequestQueryInput, + DeleteExceptionListResponse, +} from './delete_exception_list/delete_exception_list.gen'; +import type { + DuplicateExceptionListRequestQueryInput, + DuplicateExceptionListResponse, +} from './duplicate_exception_list/duplicate_exception_list.gen'; +import type { ExportExceptionListRequestQueryInput } from './export_exception_list/export_exception_list.gen'; +import type { + FindExceptionListItemsRequestQueryInput, + FindExceptionListItemsResponse, +} from './find_exception_list_items/find_exception_list_items.gen'; +import type { + FindExceptionListsRequestQueryInput, + FindExceptionListsResponse, +} from './find_exception_lists/find_exception_lists.gen'; +import type { + ImportExceptionListRequestQueryInput, + ImportExceptionListResponse, +} from './import_exceptions/import_exceptions.gen'; +import type { + ReadExceptionListItemRequestQueryInput, + ReadExceptionListItemResponse, +} from './read_exception_list_item/read_exception_list_item.gen'; +import type { + ReadExceptionListSummaryRequestQueryInput, + ReadExceptionListSummaryResponse, +} from './read_exception_list_summary/read_exception_list_summary.gen'; +import type { + ReadExceptionListRequestQueryInput, + ReadExceptionListResponse, +} from './read_exception_list/read_exception_list.gen'; +import type { + UpdateExceptionListItemRequestBodyInput, + UpdateExceptionListItemResponse, +} from './update_exception_list_item/update_exception_list_item.gen'; +import type { + UpdateExceptionListRequestBodyInput, + UpdateExceptionListResponse, +} from './update_exception_list/update_exception_list.gen'; + +export interface ClientOptions { + kbnClient: KbnClient; + log: ToolingLog; +} + +export class Client { + readonly kbnClient: KbnClient; + readonly log: ToolingLog; + + constructor(options: ClientOptions) { + this.kbnClient = options.kbnClient; + this.log = options.log; + } + /** + * An exception list groups exception items and can be associated with detection rules. You can assign detection rules with multiple exception lists. +> info +> All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. + + */ + async createExceptionList(props: CreateExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Create an exception item and associate it with the specified exception list. +> info +> Before creating exception items, you must create an exception list. + + */ + async createExceptionListItem(props: CreateExceptionListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateExceptionListItem`); + return this.kbnClient + .request({ + path: '/api/exception_lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Create exception items that apply to a single detection rule. + */ + async createRuleExceptionListItems(props: CreateRuleExceptionListItemsProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateRuleExceptionListItems`); + return this.kbnClient + .request({ + path: replaceParams('/api/detection_engine/rules/{id}/exceptions', props.params), + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * An exception list groups exception items and can be associated with detection rules. A shared exception list can apply to multiple detection rules. +> info +> All exception items added to the same list are evaluated using `OR` logic. That is, if any of the items in a list evaluate to `true`, the exception prevents the rule from generating an alert. Likewise, `OR` logic is used for evaluating exceptions when more than one exception list is assigned to a rule. To use the `AND` operator, you can define multiple clauses (`entries`) in a single exception item. + + */ + async createSharedExceptionList(props: CreateSharedExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateSharedExceptionList`); + return this.kbnClient + .request({ + path: '/api/exceptions/shared', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Delete an exception list using the `id` or `list_id` field. + */ + async deleteExceptionList(props: DeleteExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API DeleteExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'DELETE', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Delete an exception list item using the `id` or `item_id` field. + */ + async deleteExceptionListItem(props: DeleteExceptionListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API DeleteExceptionListItem`); + return this.kbnClient + .request({ + path: '/api/exception_lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'DELETE', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Duplicate an existing exception list. + */ + async duplicateExceptionList(props: DuplicateExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API DuplicateExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists/_duplicate', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Export an exception list and its associated items to an NDJSON file. + */ + async exportExceptionList(props: ExportExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API ExportExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists/_export', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get a list of all exception list items in the specified list. + */ + async findExceptionListItems(props: FindExceptionListItemsProps) { + this.log.info(`${new Date().toISOString()} Calling API FindExceptionListItems`); + return this.kbnClient + .request({ + path: '/api/exception_lists/items/_find', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get a list of all exception lists. + */ + async findExceptionLists(props: FindExceptionListsProps) { + this.log.info(`${new Date().toISOString()} Calling API FindExceptionLists`); + return this.kbnClient + .request({ + path: '/api/exception_lists/_find', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Import an exception list and its associated items from an NDJSON file. + */ + async importExceptionList(props: ImportExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API ImportExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists/_import', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.attachment, + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get the details of an exception list using the `id` or `list_id` field. + */ + async readExceptionList(props: ReadExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API ReadExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get the details of an exception list item using the `id` or `item_id` field. + */ + async readExceptionListItem(props: ReadExceptionListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API ReadExceptionListItem`); + return this.kbnClient + .request({ + path: '/api/exception_lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get a summary of the specified exception list. + */ + async readExceptionListSummary(props: ReadExceptionListSummaryProps) { + this.log.info(`${new Date().toISOString()} Calling API ReadExceptionListSummary`); + return this.kbnClient + .request({ + path: '/api/exception_lists/summary', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update an exception list using the `id` or `list_id` field. + */ + async updateExceptionList(props: UpdateExceptionListProps) { + this.log.info(`${new Date().toISOString()} Calling API UpdateExceptionList`); + return this.kbnClient + .request({ + path: '/api/exception_lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PUT', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update an exception list item using the `id` or `item_id` field. + */ + async updateExceptionListItem(props: UpdateExceptionListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API UpdateExceptionListItem`); + return this.kbnClient + .request({ + path: '/api/exception_lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PUT', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } +} + +export interface CreateExceptionListProps { + body: CreateExceptionListRequestBodyInput; +} +export interface CreateExceptionListItemProps { + body: CreateExceptionListItemRequestBodyInput; +} +export interface CreateRuleExceptionListItemsProps { + params: CreateRuleExceptionListItemsRequestParamsInput; + body: CreateRuleExceptionListItemsRequestBodyInput; +} +export interface CreateSharedExceptionListProps { + body: CreateSharedExceptionListRequestBodyInput; +} +export interface DeleteExceptionListProps { + query: DeleteExceptionListRequestQueryInput; +} +export interface DeleteExceptionListItemProps { + query: DeleteExceptionListItemRequestQueryInput; +} +export interface DuplicateExceptionListProps { + query: DuplicateExceptionListRequestQueryInput; +} +export interface ExportExceptionListProps { + query: ExportExceptionListRequestQueryInput; +} +export interface FindExceptionListItemsProps { + query: FindExceptionListItemsRequestQueryInput; +} +export interface FindExceptionListsProps { + query: FindExceptionListsRequestQueryInput; +} +export interface ImportExceptionListProps { + query: ImportExceptionListRequestQueryInput; + attachment: FormData; +} +export interface ReadExceptionListProps { + query: ReadExceptionListRequestQueryInput; +} +export interface ReadExceptionListItemProps { + query: ReadExceptionListItemRequestQueryInput; +} +export interface ReadExceptionListSummaryProps { + query: ReadExceptionListSummaryRequestQueryInput; +} +export interface UpdateExceptionListProps { + body: UpdateExceptionListRequestBodyInput; +} +export interface UpdateExceptionListItemProps { + body: UpdateExceptionListItemRequestBodyInput; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.ts new file mode 100644 index 000000000000..87db0f9e7562 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.gen.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Read exception list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { + ExceptionListId, + ExceptionListHumanId, + ExceptionNamespaceType, + ExceptionList, +} from '../model/exception_list_common.gen'; + +export type ReadExceptionListRequestQuery = z.infer; +export const ReadExceptionListRequestQuery = z.object({ + /** + * Either `id` or `list_id` must be specified + */ + id: ExceptionListId.optional(), + /** + * Either `id` or `list_id` must be specified + */ + list_id: ExceptionListHumanId.optional(), + namespace_type: ExceptionNamespaceType.optional().default('single'), +}); +export type ReadExceptionListRequestQueryInput = z.input; + +export type ReadExceptionListResponse = z.infer; +export const ReadExceptionListResponse = ExceptionList; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml new file mode 100644 index 000000000000..001c56a3eafb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list/read_exception_list.schema.yaml @@ -0,0 +1,70 @@ +openapi: 3.0.0 +info: + title: Read exception list API endpoint + version: '2023-10-31' +paths: + /api/exception_lists: + get: + x-labels: [serverless, ess] + operationId: ReadExceptionList + x-codegen-enabled: true + summary: Get exception list details + description: Get the details of an exception list using the `id` or `list_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `list_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' + - name: list_id + in: query + required: false + description: Either `id` or `list_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' + - name: namespace_type + in: query + required: false + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + default: single + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionList' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts index 4de512301cd8..02f6d1055838 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml new file mode 100644 index 000000000000..82cac05e9781 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_item/read_exception_list_item.schema.yaml @@ -0,0 +1,70 @@ +openapi: 3.0.0 +info: + title: Read exception list item API endpoint + version: '2023-10-31' +paths: + /api/exception_lists/items: + get: + x-labels: [serverless, ess] + operationId: ReadExceptionListItem + x-codegen-enabled: true + summary: Get an exception list item + description: Get the details of an exception list item using the `id` or `item_id` field. + parameters: + - name: id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemId' + - name: item_id + in: query + required: false + description: Either `id` or `item_id` must be specified + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItemHumanId' + - name: namespace_type + in: query + required: false + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + default: single + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts similarity index 79% rename from packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts index 3e3230dddb0a..8807f4b7e781 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml new file mode 100644 index 000000000000..fe6bb93b9cdb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/read_exception_list_summary/read_exception_list_summary.schema.yaml @@ -0,0 +1,89 @@ +openapi: 3.0.0 +info: + title: Read exception list summary API endpoint + version: '2023-10-31' +paths: + /api/exception_lists/summary: + get: + x-labels: [serverless, ess] + operationId: ReadExceptionListSummary + x-codegen-enabled: true + summary: Get an exception list summary + description: Get a summary of the specified exception list. + parameters: + - name: id + in: query + required: false + description: Exception list's identifier generated upon creation + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListId' + - name: list_id + in: query + required: false + description: Exception list's human readable identifier + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionListHumanId' + - name: namespace_type + in: query + required: false + schema: + $ref: '../model/exception_list_common.schema.yaml#/components/schemas/ExceptionNamespaceType' + default: single + - name: filter + in: query + required: false + description: Search filter clause + schema: + type: string + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + windows: + type: integer + minimum: 0 + linux: + type: integer + minimum: 0 + macos: + type: integer + minimum: 0 + total: + type: integer + minimum: 0 + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: Exception list not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts similarity index 79% rename from packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts index 2f38661cc958..fb5fde05dcc8 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml index 5e8f3dfd8b50..5a07623f4c93 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list/update_exception_list.schema.yaml @@ -59,29 +59,29 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 404: description: Exception list not found response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts similarity index 86% rename from packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts index 651c1dc1f2d4..791af5f65e35 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml similarity index 75% rename from packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml index 2b8182aeb5c3..d6021768492c 100644 --- a/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/update_exception_list_item/update_exception_list_item.schema.yaml @@ -70,32 +70,32 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 404: description: Exception list item not found response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: x-codegen-enabled: true @@ -104,9 +104,9 @@ components: type: object properties: id: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' comment: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' required: - comment diff --git a/packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/ess/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/serverless/security_solution_exceptions_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-exceptions-common/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/package.json new file mode 100644 index 000000000000..e68c27982b29 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/package.json @@ -0,0 +1,11 @@ +{ + "description": "Security Solution Exceptions common package", + "license": "Elastic License 2.0", + "name": "@kbn/securitysolution-exceptions-common", + "private": true, + "version": "1.0.0", + "scripts": { + "openapi:generate": "node scripts/openapi_generate", + "openapi:bundle": "node scripts/openapi_bundle" + } +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js new file mode 100644 index 000000000000..996c55ce307d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { bundle } = require('@kbn/openapi-bundler'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/serverless/security_solution_exceptions_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['serverless'], + prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/exceptions_serverless.info.yaml'), + }, + }); + + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/ess/security_solution_exceptions_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['ess'], + prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/exceptions_ess.info.yaml'), + }, + }); +})(); diff --git a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_ess.info.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_ess.info.yaml similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_ess.info.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_ess.info.yaml diff --git a/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_serverless.info.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_serverless.info.yaml similarity index 100% rename from packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_serverless.info.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle_info/exceptions_serverless.info.yaml diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js new file mode 100644 index 000000000000..92488001b0b3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_generate.js @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { generate } = require('@kbn/openapi-generator'); +const { REPO_ROOT } = require('@kbn/repo-info'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await generate({ + title: 'OpenAPI Exceptions API Schemas', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'zod_operation_schema', + }); + + await generate({ + title: 'Exceptions API client for tests', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'api_client_supertest', + skipLinting: true, + bundle: { + outFile: join( + REPO_ROOT, + 'x-pack/test/api_integration/services/security_solution_exceptions_api.gen.ts' + ), + }, + }); + + await generate({ + title: 'Exceptions API client for quickstart', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'api_client_quickstart', + skipLinting: true, + bundle: { + outFile: join( + REPO_ROOT, + 'x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/api/quickstart_client.gen.ts' + ), + }, + }); +})(); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/tsconfig.json new file mode 100644 index 000000000000..ba5a2c115a33 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "exclude": ["target/**/*"], + "extends": "../../../../../tsconfig.base.json", + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/openapi-common", + "@kbn/zod-helpers", + "@kbn/securitysolution-lists-common", + "@kbn/test", + "@kbn/tooling-log", + "@kbn/core-http-common", + "@kbn/securitysolution-utils", + "@kbn/zod", + ] +} diff --git a/packages/kbn-securitysolution-hook-utils/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/README.md similarity index 100% rename from packages/kbn-securitysolution-hook-utils/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/index.ts new file mode 100644 index 000000000000..40ff03e88094 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/types'; +export * from './src/use_async'; +export * from './src/use_is_mounted'; +export * from './src/use_observable'; +export * from './src/with_optional_signal'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/jest.config.js new file mode 100644 index 000000000000..8238f9f7e97d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils'], +}; diff --git a/packages/kbn-securitysolution-hook-utils/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-hook-utils/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/package.json new file mode 100644 index 000000000000..efd415370f23 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-hook-utils", + "version": "1.0.0", + "description": "Security Solution utilities for React hooks", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/types.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/types.ts new file mode 100644 index 000000000000..1b31cae2a16d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/types.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/** + * Represents the state of an asynchronous task, along with an initiator + * function to kick off the work. + */ +export interface Task { + loading: boolean; + error: unknown | undefined; + result: Result | undefined; + start: (...args: Args) => void; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts new file mode 100644 index 000000000000..e5420124a0eb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts @@ -0,0 +1,164 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { waitFor, renderHook, act } from '@testing-library/react'; + +import { useAsync } from '.'; + +interface TestArgs { + n: number; + s: string; +} + +type TestReturn = Promise; + +describe('useAsync', () => { + /** + * Timeout for both jest tests and for the waitFor. + * jest tests default to 5 seconds and waitFor defaults to 1 second. + * 20_0000 = 20,000 milliseconds = 20 seconds + */ + const timeout = 20_000; + + let fn: jest.Mock; + let args: TestArgs; + + beforeEach(() => { + args = { n: 1, s: 's' }; + fn = jest.fn().mockResolvedValue(false); + }); + + it('does not invoke fn if start was not called', () => { + renderHook(() => useAsync(fn)); + expect(fn).not.toHaveBeenCalled(); + }); + + it( + 'invokes the function when start is called', + async () => { + const { result } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + await waitFor(() => expect(fn).toHaveBeenCalled(), { timeout }); + }, + timeout + ); + + it('invokes the function with start args', async () => { + const { result } = renderHook(() => useAsync(fn)); + const expectedArgs = { ...args }; + + act(() => { + result.current.start(args); + }); + await waitFor(() => expect(fn).toHaveBeenCalledWith(expectedArgs), { timeout }); + }); + + it( + 'populates result with the resolved value of the fn', + async () => { + const { result } = renderHook(() => useAsync(fn)); + fn.mockResolvedValue({ resolved: 'value' }); + + act(() => { + result.current.start(args); + }); + await waitFor( + () => { + expect(result.current.result).toEqual({ resolved: 'value' }); + expect(result.current.error).toBeUndefined(); + }, + { timeout } + ); + }, + timeout + ); + + it( + 'populates error if function rejects', + async () => { + fn.mockRejectedValue(new Error('whoops')); + const { result } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + + await waitFor( + () => { + expect(result.current.result).toBeUndefined(); + expect(result.current.error).toEqual(new Error('whoops')); + }, + { timeout } + ); + }, + timeout + ); + + it( + 'populates the loading state while the function is pending', + async () => { + let resolve: () => void; + fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); + + const { result } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => resolve()); + await waitFor(() => expect(result.current.loading).toBe(false), { timeout }); + }, + timeout + ); + + it( + 'multiple start calls reset state', + async () => { + let resolve: (result: string) => void; + fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); + + const { result } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => resolve('result')); + await waitFor( + () => { + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('result'); + }, + { timeout } + ); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + expect(result.current.result).toBe(undefined); + act(() => resolve('result')); + await waitFor( + () => { + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('result'); + }, + { timeout } + ); + }, + timeout + ); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts new file mode 100644 index 000000000000..027039ac7cca --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_async/index.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useState } from 'react'; + +import { Task } from '../types'; +import { useIsMounted } from '../use_is_mounted'; + +/** + * + * This hook wraps a promise-returning thunk (task) in order to conditionally + * initiate the work, and automatically provide state corresponding to the + * task's status. + * + * In order to function properly and not rerender unnecessarily, ensure that + * your task is a stable function reference. + * + * @param fn a function returning a promise. + * + * @returns An {@link Task} containing the task's current state along with a + * start callback + */ +export const useAsync = ( + fn: (...args: Args) => Promise +): Task => { + const isMounted = useIsMounted(); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(); + const [result, setResult] = useState(); + + const start = useCallback( + (...args: Args) => { + setLoading(true); + setResult(undefined); + setError(undefined); + fn(...args) + .then((r) => isMounted() && setResult(r)) + .catch((e) => isMounted() && setError(e)) + .finally(() => isMounted() && setLoading(false)); + }, + [fn, isMounted] + ); + + return { + error, + loading, + result, + start, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.ts new file mode 100644 index 000000000000..52f3a0739f4a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.test.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook } from '@testing-library/react'; + +import { useIsMounted } from '.'; + +describe('useIsMounted', () => { + it('evaluates to true when mounted', () => { + const { result } = renderHook(() => useIsMounted()); + + expect(result.current()).toEqual(true); + }); + + it('evaluates to false when unmounted', () => { + const { result, unmount } = renderHook(() => useIsMounted()); + + unmount(); + expect(result.current()).toEqual(false); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts new file mode 100644 index 000000000000..8d325aed1abd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_is_mounted/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useEffect, useRef } from 'react'; + +type GetIsMounted = () => boolean; + +/** + * + * @returns A {@link GetIsMounted} getter function returning whether the component is currently mounted + */ +export const useIsMounted = (): GetIsMounted => { + const isMounted = useRef(false); + const getIsMounted: GetIsMounted = useCallback(() => isMounted.current, []); + const handleCleanup = useCallback(() => { + isMounted.current = false; + }, []); + + useEffect(() => { + isMounted.current = true; + return handleCleanup; + }, [handleCleanup]); + + return getIsMounted; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts new file mode 100644 index 000000000000..3c6d96e3d3ac --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.test.ts @@ -0,0 +1,159 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook, act } from '@testing-library/react'; +import { Subject, throwError } from 'rxjs'; + +import { useObservable } from '.'; + +interface TestArgs { + n: number; + s: string; +} + +type TestReturn = Subject; + +describe('useObservable', () => { + let fn: jest.Mock; + let subject: TestReturn; + let args: TestArgs; + + beforeEach(() => { + args = { n: 1, s: 's' }; + subject = new Subject(); + fn = jest.fn().mockReturnValue(subject); + }); + + it('does not invoke fn if start was not called', () => { + renderHook(() => useObservable(fn)); + expect(fn).not.toHaveBeenCalled(); + }); + + it('invokes the function when start is called', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + + expect(fn).toHaveBeenCalled(); + }); + + it('invokes the function with start args', () => { + const { result } = renderHook(() => useObservable(fn)); + const expectedArgs = { ...args }; + + act(() => { + result.current.start(args); + }); + + expect(fn).toHaveBeenCalledWith(expectedArgs); + }); + + it('populates result with the next value of the fn', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + act(() => subject.next('value')); + + expect(result.current.result).toEqual('value'); + expect(result.current.error).toBeUndefined(); + }); + + it('populates error if observable throws an error', () => { + const error = new Error('whoops'); + const errorFn = () => throwError(error); + + const { result } = renderHook(() => useObservable(errorFn)); + + act(() => { + result.current.start(); + }); + + expect(result.current.result).toBeUndefined(); + expect(result.current.error).toEqual(error); + }); + + it('populates the loading state while no value has resolved', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => subject.next('a value')); + + expect(result.current.loading).toBe(false); + }); + + it('updates result with each resolved value', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + + act(() => subject.next('a value')); + expect(result.current.result).toEqual('a value'); + + act(() => subject.next('a subsequent value')); + expect(result.current.result).toEqual('a subsequent value'); + }); + + it('does not update result with values if start has not been called', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => subject.next('a value')); + expect(result.current.result).toBeUndefined(); + + act(() => subject.next('a subsequent value')); + expect(result.current.result).toBeUndefined(); + }); + + it('unsubscribes on unmount', () => { + const { result, unmount } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + expect(subject.observers).toHaveLength(1); + + unmount(); + expect(subject.observers).toHaveLength(0); + }); + + it('multiple start calls reset state', () => { + const { result } = renderHook(() => useObservable(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => subject.next('one value')); + + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('one value'); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + expect(result.current.result).toBe(undefined); + + act(() => subject.next('another value')); + + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('another value'); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts new file mode 100644 index 000000000000..b7cd1e2623b7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/use_observable/index.ts @@ -0,0 +1,91 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useEffect, useRef, useReducer, Reducer } from 'react'; +import { Observable, Subscription } from 'rxjs'; + +import { useIsMounted } from '../use_is_mounted'; +import { Task } from '../types'; + +interface State { + loading: boolean; + error?: unknown; + result?: T; +} + +export type Action = + | { type: 'setResult'; result: T } + | { type: 'setError'; error: unknown } + | { type: 'load' }; + +function reducer(state: State, action: Action) { + switch (action.type) { + case 'setResult': + return { ...state, result: action.result, loading: false }; + case 'setError': + return { ...state, error: action.error, loading: false }; + case 'load': + return { loading: true, result: undefined, error: undefined }; + } +} + +/** + * + * @param fn function returning an observable + * + * @returns An {@link Async} containing the underlying task's state along with a start callback + */ +export const useObservable = ( + fn: (...args: Args) => Observable +): Task => { + const isMounted = useIsMounted(); + const subRef = useRef(); + const [state, dispatch] = useReducer, Action>>(reducer, { + loading: false, + error: undefined, + result: undefined, + }); + + const start = useCallback( + (...args: Args) => { + if (subRef.current) { + subRef.current.unsubscribe(); + } + dispatch({ type: 'load' }); + + subRef.current = fn(...args).subscribe( + (r) => { + if (isMounted()) { + dispatch({ type: 'setResult', result: r }); + } + }, + (e) => { + if (isMounted()) { + dispatch({ type: 'setError', error: e }); + } + } + ); + }, + [fn, isMounted] + ); + + useEffect( + () => () => { + if (subRef.current) { + subRef.current.unsubscribe(); + } + }, + [] + ); + + return { + result: state.result, + error: state.error, + loading: state.loading, + start, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.ts new file mode 100644 index 000000000000..05a1b2fa167a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.test.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { withOptionalSignal } from '.'; + +type TestFn = ({ number, signal }: { number: number; signal: AbortSignal }) => boolean; + +describe('withOptionalSignal', () => { + it('does not require a signal on the returned function', () => { + const fn = jest.fn().mockReturnValue('hello') as TestFn; + + const wrappedFn = withOptionalSignal(fn); + + expect(wrappedFn({ number: 1 })).toEqual('hello'); + }); + + it('will pass a given signal to the wrapped function', () => { + const fn = jest.fn().mockReturnValue('hello') as TestFn; + const { signal } = new AbortController(); + + const wrappedFn = withOptionalSignal(fn); + + wrappedFn({ number: 1, signal }); + expect(fn).toHaveBeenCalledWith({ number: 1, signal }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts new file mode 100644 index 000000000000..eadad58804f8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +interface SignalArgs { + signal: AbortSignal; +} + +export type OptionalSignalArgs = Omit & Partial; + +/** + * + * @param fn an async function receiving an AbortSignal argument + * + * @returns An async function where the AbortSignal argument is optional + */ +export const withOptionalSignal = + (fn: (args: Args) => Result) => + (args: OptionalSignalArgs): Result => { + const signal = args.signal != null ? args.signal : new AbortController().signal; + return fn({ ...args, signal } as Args); + }; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/tsconfig.json new file mode 100644 index 000000000000..ccdf26c349f0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-hook-utils/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/README.md similarity index 100% rename from packages/kbn-securitysolution-io-ts-alerting-types/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/index.ts new file mode 100644 index 000000000000..f5e8f8419b25 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/index.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/actions'; +export * from './src/default_actions_array'; +export * from './src/default_export_file_name'; +export * from './src/default_from_string'; +export * from './src/default_interval_string'; +export * from './src/default_language_string'; +export * from './src/default_max_signals_number'; +export * from './src/default_page'; +export * from './src/default_per_page'; +export * from './src/default_risk_score_mapping_array'; +export * from './src/default_severity_mapping_array'; +export * from './src/default_threat_array'; +export * from './src/default_to_string'; +export * from './src/default_uuid'; +export * from './src/frequency'; +export * from './src/language'; +export * from './src/machine_learning_job_id'; +export * from './src/max_signals'; +export * from './src/normalized_ml_job_id'; +export * from './src/references_default_array'; +export * from './src/risk_score'; +export * from './src/risk_score_mapping'; +export * from './src/rule_schedule'; +export * from './src/saved_object_attributes'; +export * from './src/severity'; +export * from './src/severity_mapping'; +export * from './src/threat'; +export * from './src/threat_mapping'; +export * from './src/threat_subtechnique'; +export * from './src/threat_tactic'; +export * from './src/threat_technique'; +export * from './src/throttle'; +export * from './src/type'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js new file mode 100644 index 000000000000..16223422cbd8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types'], +}; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-io-ts-alerting-types/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/package.json new file mode 100644 index 000000000000..bbe6c163fb5e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-io-ts-alerting-types", + "version": "1.0.0", + "description": "io ts utilities and types to be shared with plugins from the security solution project", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts new file mode 100644 index 000000000000..64953a0dc0cd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/actions/index.ts @@ -0,0 +1,127 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +import * as t from 'io-ts'; +import { saved_object_attributes } from '../saved_object_attributes'; +import { RuleActionFrequency } from '../frequency'; + +export type RuleActionGroup = t.TypeOf; +export const RuleActionGroup = t.string; + +export type RuleActionId = t.TypeOf; +export const RuleActionId = t.string; + +export type RuleActionTypeId = t.TypeOf; +export const RuleActionTypeId = t.string; + +export type RuleActionUuid = t.TypeOf; +export const RuleActionUuid = NonEmptyString; + +/** + * Params is an "object", since it is a type of RuleActionParams which is action templates. + * @see x-pack/plugins/alerting/common/rule.ts + */ +export type RuleActionParams = t.TypeOf; +export const RuleActionParams = saved_object_attributes; + +export const RuleActionAlertsFilter = t.partial({ + query: t.union([ + t.undefined, + t.intersection([ + t.strict({ + kql: t.string, + filters: t.array( + t.intersection([ + t.type({ + meta: t.partial({ + alias: t.union([t.string, t.null]), + disabled: t.boolean, + negate: t.boolean, + controlledBy: t.string, + group: t.string, + index: t.string, + isMultiIndex: t.boolean, + type: t.string, + key: t.string, + params: t.any, + value: t.string, + }), + }), + t.partial({ + $state: t.type({ store: t.any }), + query: t.record(t.string, t.any), + }), + ]) + ), + }), + t.partial({ dsl: t.string }), + ]), + ]), + timeframe: t.union([ + t.undefined, + t.strict({ + timezone: t.string, + days: t.array( + t.union([ + t.literal(1), + t.literal(2), + t.literal(3), + t.literal(4), + t.literal(5), + t.literal(6), + t.literal(7), + ]) + ), + hours: t.strict({ + start: t.string, + end: t.string, + }), + }), + ]), +}); + +export type RuleAction = t.TypeOf; +export const RuleAction = t.exact( + t.intersection([ + t.type({ + group: RuleActionGroup, + id: RuleActionId, + action_type_id: RuleActionTypeId, + params: RuleActionParams, + }), + t.partial({ + uuid: RuleActionUuid, + alerts_filter: RuleActionAlertsFilter, + frequency: RuleActionFrequency, + }), + ]) +); + +export type RuleActionArray = t.TypeOf; +export const RuleActionArray = t.array(RuleAction); + +export type RuleActionCamel = t.TypeOf; +export const RuleActionCamel = t.exact( + t.intersection([ + t.type({ + group: RuleActionGroup, + id: RuleActionId, + actionTypeId: RuleActionTypeId, + params: RuleActionParams, + }), + t.partial({ + uuid: RuleActionUuid, + alertsFilter: RuleActionAlertsFilter, + frequency: RuleActionFrequency, + }), + ]) +); + +export type RuleActionArrayCamel = t.TypeOf; +export const RuleActionArrayCamel = t.array(RuleActionCamel); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.ts new file mode 100644 index 000000000000..2747846c74d8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.mock.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const ENTRY_VALUE = 'some host name'; +export const FIELD = 'host.name'; +export const MATCH = 'match'; +export const MATCH_ANY = 'match_any'; +export const OPERATOR = 'included'; +export const NESTED = 'nested'; +export const NESTED_FIELD = 'parent.field'; +export const LIST_ID = 'some-list-id'; +export const LIST = 'list'; +export const TYPE = 'ip'; +export const EXISTS = 'exists'; +export const WILDCARD = 'wildcard'; +export const USER = 'some user'; +export const DATE_NOW = '2020-04-20T15:25:31.830Z'; + +// Exception List specific +export const ID = 'uuid_here'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts new file mode 100644 index 000000000000..ad5a2ba26226 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/constants/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/** + * TODO: Create a kbn-alerting-constants and add this to it. + * @deprecated Use a DEFAULT_MAX_SIGNALS from a kbn-alerting-constants package. + */ +export const DEFAULT_MAX_SIGNALS = 100; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/index.ts new file mode 100644 index 000000000000..28ff3053564c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_actions_array/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; 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 { RuleActionArray } from '../actions'; + +export const DefaultActionsArray = new t.Type< + RuleActionArray, + RuleActionArray | undefined, + unknown +>( + 'DefaultActionsArray', + RuleActionArray.is, + (input, context): Either => + input == null ? t.success([]) : RuleActionArray.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts new file mode 100644 index 000000000000..009fdb23d3fb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultExportFileName } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts new file mode 100644 index 000000000000..53f0972baca2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_export_file_name/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts new file mode 100644 index 000000000000..f6c7f91e315a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultFromString } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.ts new file mode 100644 index 000000000000..d23bca135d03 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_from_string/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { From } from '../from'; + +/** + * Types the DefaultFromString as: + * - If null or undefined, then a default of the string "now-6m" will be used + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts new file mode 100644 index 000000000000..602d6c9ff79e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultIntervalString } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts new file mode 100644 index 000000000000..d743fa773f2e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_interval_string/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts new file mode 100644 index 000000000000..34e6e65518c7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.test.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { Language } from '../language'; +import { DefaultLanguageString } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/index.ts new file mode 100644 index 000000000000..ca557dafecef --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_language_string/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; 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 '../language'; + +/** + * Types the DefaultLanguageString as: + * - If null or undefined, then a default of the string "kuery" will be used + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts new file mode 100644 index 000000000000..cd4b0aa42953 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.test.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultMaxSignalsNumber } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.ts new file mode 100644 index 000000000000..535f9397c7af --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_max_signals_number/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { max_signals } from '../max_signals'; +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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts new file mode 100644 index 000000000000..d9e63e0f9ec1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.test.ts @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultPage } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.ts new file mode 100644 index 000000000000..6ae23dd8c676 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_page/index.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; + +/** + * 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts new file mode 100644 index 000000000000..07a6358ba2e8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.test.ts @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultPerPage } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.ts new file mode 100644 index 000000000000..320945311d3b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_per_page/index.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; + +/** + * 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.ts new file mode 100644 index 000000000000..a457c827e25f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_risk_score_mapping_array/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { RiskScoreMapping } from '../risk_score_mapping'; + +/** + * Types the DefaultStringArray as: + * - If null or undefined, then a default RiskScoreMapping array will be set + */ +export const DefaultRiskScoreMappingArray = new t.Type< + RiskScoreMapping, + RiskScoreMapping | undefined, + unknown +>( + 'DefaultRiskScoreMappingArray', + RiskScoreMapping.is, + (input, context): Either => + input == null ? t.success([]) : RiskScoreMapping.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.ts new file mode 100644 index 000000000000..8d7b581146ea --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_severity_mapping_array/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { SeverityMapping } from '../severity_mapping'; + +/** + * Types the DefaultStringArray as: + * - If null or undefined, then a default SeverityMapping array will be set + */ +export const DefaultSeverityMappingArray = new t.Type< + SeverityMapping, + SeverityMapping | undefined, + unknown +>( + 'DefaultSeverityMappingArray', + SeverityMapping.is, + (input, context): Either => + input == null ? t.success([]) : SeverityMapping.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts new file mode 100644 index 000000000000..ed42de41effc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.test.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { Threats } from '../threat'; +import { DefaultThreatArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/index.ts new file mode 100644 index 000000000000..8ed8abc58750 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_threat_array/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; 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 '../threat'; + +/** + * Types the DefaultThreatArray as: + * - If null or undefined, then an empty array will be set + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts new file mode 100644 index 000000000000..f87b1c4f24a9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultToString } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts new file mode 100644 index 000000000000..d2e58f423b59 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_to_string/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.test.ts new file mode 100644 index 000000000000..ee605a5c4383 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultUuid } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.ts new file mode 100644 index 000000000000..b3d6fda5b134 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/default_uuid/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { v4 as uuidv4 } from 'uuid'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +/** + * Types the DefaultUuid as: + * - If null or undefined, then a default string uuidv4() will be + * created otherwise it will be checked just against an empty string + */ +export const DefaultUuid = new t.Type( + 'DefaultUuid', + t.string.is, + (input, context): Either => + input == null ? t.success(uuidv4()) : NonEmptyString.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.ts new file mode 100644 index 000000000000..318408f14582 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/frequency/index.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RuleActionThrottle } from '../throttle'; + +/** + * Action summary indicates whether we will send a summary notification about all the generate alerts or notification per individual alert + */ +export type RuleActionSummary = t.TypeOf; +export const RuleActionSummary = t.boolean; + +/** + * The condition for throttling the notification: `onActionGroupChange`, `onActiveAlert`, or `onThrottleInterval` + */ +export type RuleActionNotifyWhen = t.TypeOf; +export const RuleActionNotifyWhen = t.union([ + t.literal('onActionGroupChange'), + t.literal('onActiveAlert'), + t.literal('onThrottleInterval'), +]); + +/** + * The action frequency defines when the action runs (for example, only on rule execution or at specific time intervals). + */ +export type RuleActionFrequency = t.TypeOf; +export const RuleActionFrequency = t.type({ + summary: RuleActionSummary, + notifyWhen: RuleActionNotifyWhen, + throttle: t.union([RuleActionThrottle, t.null]), +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts new file mode 100644 index 000000000000..d0330fae6140 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Either } from 'fp-ts/lib/Either'; +import * as t from 'io-ts'; +import { parseScheduleDates } from '@kbn/securitysolution-io-ts-utils'; + +const stringValidator = (input: unknown): input is string => typeof input === 'string'; + +export type From = t.TypeOf; +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 +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts new file mode 100644 index 000000000000..63ad102a4134 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const language = t.keyof({ eql: null, kuery: null, lucene: null, esql: null }); +export type Language = t.TypeOf; + +export const languageOrUndefined = t.union([language, t.undefined]); +export type LanguageOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts new file mode 100644 index 000000000000..8e6453ac7e7b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/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; 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 { 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/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts new file mode 100644 index 000000000000..64ded4827b5e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; +import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; + +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/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/normalized_ml_job_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/normalized_ml_job_id/index.ts new file mode 100644 index 000000000000..f81c3da1db5d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/normalized_ml_job_id/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 '@kbn/securitysolution-io-ts-types'; + +export const machine_learning_job_id_normalized = NonEmptyArray(t.string); +export type MachineLearningJobIdNormalized = t.TypeOf; + +export const machineLearningJobIdNormalizedOrUndefined = t.union([ + machine_learning_job_id_normalized, + t.undefined, +]); +export type MachineLearningJobIdNormalizedOrUndefined = t.TypeOf< + typeof machineLearningJobIdNormalizedOrUndefined +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.test.ts new file mode 100644 index 000000000000..7c5e9bb29877 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.test.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { ReferencesDefaultArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('default_string_array', () => { + test('it should validate an empty array', () => { + const payload: string[] = []; + const decoded = ReferencesDefaultArray.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 = ReferencesDefaultArray.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 = ReferencesDefaultArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to "referencesWithDefaultArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = ReferencesDefaultArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts new file mode 100644 index 000000000000..e5ccac365043 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/references_default_array/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts new file mode 100644 index 000000000000..b55ef415fbbb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.test.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { RiskScore } from '.'; + +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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts new file mode 100644 index 000000000000..143ea2e72754 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * 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. + */ +export type RiskScore = t.TypeOf; +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 +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts new file mode 100644 index 000000000000..0856806d4898 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { operator } from '@kbn/securitysolution-io-ts-types'; +import { RiskScore } from '../risk_score'; + +export type RiskScoreMappingItem = t.TypeOf; +export const RiskScoreMappingItem = t.exact( + t.type({ + field: t.string, + value: t.string, + operator, + risk_score: t.union([RiskScore, t.undefined]), + }) +); + +export type RiskScoreMapping = t.TypeOf; +export const RiskScoreMapping = t.array(RiskScoreMappingItem); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts new file mode 100644 index 000000000000..16bc6dc15310 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/rule_schedule/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { From } from '../from'; + +export type RuleInterval = t.TypeOf; +export const RuleInterval = t.string; // we need a more specific schema + +export type RuleIntervalFrom = t.TypeOf; +export const RuleIntervalFrom = From; + +/** + * TODO: Create a regular expression type or custom date math part type here + */ +export type RuleIntervalTo = t.TypeOf; +export const RuleIntervalTo = t.string; // we need a more specific schema diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.ts new file mode 100644 index 000000000000..33db222f098e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/saved_object_attributes/index.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +/** + * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove + * this copied type. + * + * Don't use this type, it's simply a helper type for {@link SavedObjectAttribute} + * + * @public + */ +export type SavedObjectAttributeSingle = + | string + | number + | boolean + | null + | undefined + | SavedObjectAttributes; + +/** + * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove + * this copied type. + * + * Type definition for a Saved Object attribute value + * + * @public + */ +export type SavedObjectAttribute = SavedObjectAttributeSingle | SavedObjectAttributeSingle[]; + +/** + * TODO: This type are originally from "src/core/types/saved_objects.ts", once that is package friendly remove + * this copied type. + * + * The data for a Saved Object is stored as an object in the `attributes` + * property. + * + * @public + */ +export interface SavedObjectAttributes { + [key: string]: SavedObjectAttribute; +} + +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]) +); +export const saved_object_attribute: t.Type = t.recursion( + 'saved_object_attribute', + () => t.union([saved_object_attribute_single, t.array(saved_object_attribute_single)]) +); +export const saved_object_attributes: t.Type = t.recursion( + 'saved_object_attributes', + () => t.record(t.string, saved_object_attribute) +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts new file mode 100644 index 000000000000..1b27423eb0db --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export type Severity = t.TypeOf; +export const Severity = t.keyof({ low: null, medium: null, high: null, critical: null }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.ts new file mode 100644 index 000000000000..4256314b32a2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/severity_mapping/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { operator } from '@kbn/securitysolution-io-ts-types'; +import { Severity } from '../severity'; + +export type SeverityMappingItem = t.TypeOf; +export const SeverityMappingItem = t.exact( + t.type({ + field: t.string, + operator, + value: t.string, + severity: Severity, + }) +); + +export type SeverityMapping = t.TypeOf; +export const SeverityMapping = t.array(SeverityMappingItem); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts new file mode 100644 index 000000000000..4b5b7aa16c2d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { threat_tactic } from '../threat_tactic'; +import { threat_techniques } from '../threat_technique'; + +export const threat_framework = t.string; + +export const threat = t.intersection([ + t.exact( + t.type({ + framework: threat_framework, + tactic: threat_tactic, + }) + ), + t.exact( + t.partial({ + technique: threat_techniques, + }) + ), +]); + +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/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts new file mode 100644 index 000000000000..781b5b89ebe6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts @@ -0,0 +1,235 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 { + concurrent_searches, + items_per_search, + ThreatMapping, + threatMappingEntries, + ThreatMappingEntries, + threat_mapping, +} from '.'; +import { foldLeftRight, getPaths, exactCheck } from '@kbn/securitysolution-io-ts-utils'; + +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: Array = [ + { + 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: Array = [ + { + 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: Array }> = [ + { + 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/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts new file mode 100644 index 000000000000..3bf4f84aeec8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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, + NonEmptyString, + PositiveIntegerGreaterThanZero, +} from '@kbn/securitysolution-io-ts-types'; +import { language } from '../language'; + +export const threat_query = t.string; +export type ThreatQuery = t.TypeOf; +export const threatQueryOrUndefined = t.union([threat_query, t.undefined]); +export type ThreatQueryOrUndefined = t.TypeOf; + +export const threat_indicator_path = t.string; +export type ThreatIndicatorPath = t.TypeOf; +export const threatIndicatorPathOrUndefined = t.union([threat_indicator_path, t.undefined]); +export type ThreatIndicatorPathOrUndefined = t.TypeOf; + +export const threat_filters = t.array(t.unknown); // Filters are not easily type-able yet +export type ThreatFilters = t.TypeOf; +export const threatFiltersOrUndefined = t.union([threat_filters, t.undefined]); +export type ThreatFiltersOrUndefined = t.TypeOf; + +export const threatMapEntry = t.exact( + t.type({ + field: NonEmptyString, + type: t.keyof({ mapping: null }), + value: NonEmptyString, + }) +); + +export type ThreatMapEntry = t.TypeOf; + +export const threatMappingEntries = t.array(threatMapEntry); +export type ThreatMappingEntries = t.TypeOf; + +export const threatMap = t.exact( + t.type({ + entries: threatMappingEntries, + }) +); +export type ThreatMap = t.TypeOf; + +export const threat_mapping = NonEmptyArray(threatMap, 'NonEmptyArray'); +export type ThreatMapping = t.TypeOf; + +export const threatMappingOrUndefined = t.union([threat_mapping, t.undefined]); +export type ThreatMappingOrUndefined = t.TypeOf; + +export const threat_index = t.array(t.string); +export type ThreatIndex = t.TypeOf; +export const threatIndexOrUndefined = t.union([threat_index, t.undefined]); +export type ThreatIndexOrUndefined = t.TypeOf; + +export const threat_language = t.union([language, t.undefined]); +export type ThreatLanguage = t.TypeOf; +export const threatLanguageOrUndefined = t.union([threat_language, t.undefined]); +export type ThreatLanguageOrUndefined = t.TypeOf; + +export const concurrent_searches = PositiveIntegerGreaterThanZero; +export type ConcurrentSearches = t.TypeOf; +export const concurrentSearchesOrUndefined = t.union([concurrent_searches, t.undefined]); +export type ConcurrentSearchesOrUndefined = t.TypeOf; + +export const items_per_search = PositiveIntegerGreaterThanZero; +export type ItemsPerSearch = t.TypeOf; +export const itemsPerSearchOrUndefined = t.union([items_per_search, t.undefined]); +export type ItemsPerSearchOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts new file mode 100644 index 000000000000..b5f2d95a139b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const threat_subtechnique_id = t.string; +export const threat_subtechnique_name = t.string; +export const threat_subtechnique_reference = t.string; + +export const threat_subtechnique = t.type({ + id: threat_subtechnique_id, + name: threat_subtechnique_name, + reference: threat_subtechnique_reference, +}); + +export const threat_subtechniques = t.array(threat_subtechnique); + +export type ThreatSubtechnique = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_tactic/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_tactic/index.ts new file mode 100644 index 000000000000..a4c63cb63289 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_tactic/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const threat_tactic_id = t.string; +export const threat_tactic_name = t.string; +export const threat_tactic_reference = t.string; + +export const threat_tactic = t.type({ + id: threat_tactic_id, + name: threat_tactic_name, + reference: threat_tactic_reference, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts new file mode 100644 index 000000000000..992c5b15ba65 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { threat_subtechniques } from '../threat_subtechnique'; + +export const threat_technique_id = t.string; +export const threat_technique_name = t.string; +export const threat_technique_reference = t.string; + +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, + }) + ), +]); +export const threat_techniques = t.array(threat_technique); + +export type ThreatTechnique = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts new file mode 100644 index 000000000000..b4be7a4a97ff --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/throttle/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { TimeDuration } from '@kbn/securitysolution-io-ts-types'; + +export type RuleActionThrottle = t.TypeOf; +export const RuleActionThrottle = t.union([ + t.literal('no_actions'), + t.literal('rule'), + TimeDuration({ allowedUnits: ['s', 'm', 'h', 'd'] }), +]); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts new file mode 100644 index 000000000000..92b71faf14fe --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +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, + new_terms: null, + esql: null, +}); +export type Type = t.TypeOf; + +export const typeOrUndefined = t.union([type, t.undefined]); +export type TypeOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/tsconfig.json new file mode 100644 index 000000000000..9b61aea31d97 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/securitysolution-io-ts-types", + "@kbn/securitysolution-io-ts-utils" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-io-ts-list-types/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/README.md similarity index 100% rename from packages/kbn-securitysolution-io-ts-list-types/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/index.ts new file mode 100644 index 000000000000..90db55188109 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/common'; +export * from './src/request'; +export * from './src/response'; +export * from './src/typescript_types'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/jest.config.js new file mode 100644 index 000000000000..1e8525371d27 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types'], +}; diff --git a/packages/kbn-securitysolution-io-ts-list-types/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-io-ts-list-types/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/package.json new file mode 100644 index 000000000000..da6c20901584 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-io-ts-list-types", + "version": "1.0.0", + "description": "io ts utilities and types to be shared with plugins from the security solution project", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.ts new file mode 100644 index 000000000000..69ad828a480e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Comment, CommentsArray } from '.'; +import { DATE_NOW, ID, USER } from '../../constants/index.mock'; + +export const getCommentsMock = (): Comment => ({ + comment: 'some old comment', + created_at: DATE_NOW, + created_by: USER, + id: ID, +}); + +export const getCommentsArrayMock = (): CommentsArray => [getCommentsMock(), getCommentsMock()]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts new file mode 100644 index 000000000000..32a230fcf586 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts @@ -0,0 +1,236 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 { getCommentsArrayMock, getCommentsMock } from './index.mock'; +import { + Comment, + comment, + CommentsArray, + commentsArray, + CommentsArrayOrUndefined, + commentsArrayOrUndefined, +} from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { DATE_NOW } from '../../constants/index.mock'; + +describe('Comment', () => { + describe('comment', () => { + test('it fails validation when "id" is undefined', () => { + const payload = { ...getCommentsMock(), id: undefined }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it passes validation with a typical comment', () => { + const payload = getCommentsMock(); + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation with "updated_at" and "updated_by" fields included', () => { + const payload = getCommentsMock(); + payload.updated_at = DATE_NOW; + payload.updated_by = 'someone'; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "comment" is an empty string', () => { + const payload: Omit & { comment: string } = { + ...getCommentsMock(), + comment: '', + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "comment" is not a string', () => { + const payload: Omit & { comment: string[] } = { + ...getCommentsMock(), + comment: ['some value'], + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "comment"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "created_at" is not a string', () => { + const payload: Omit & { created_at: number } = { + ...getCommentsMock(), + created_at: 1, + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "created_by" is not a string', () => { + const payload: Omit & { created_by: number } = { + ...getCommentsMock(), + created_by: 1, + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "created_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "updated_at" is not a string', () => { + const payload: Omit & { updated_at: number } = { + ...getCommentsMock(), + updated_at: 1, + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "updated_by" is not a string', () => { + const payload: Omit & { updated_by: number } = { + ...getCommentsMock(), + updated_by: 1, + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "updated_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: Comment & { + extraKey?: string; + } = getCommentsMock(); + payload.extraKey = 'some value'; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getCommentsMock()); + }); + }); + + describe('commentsArray', () => { + test('it passes validation an array of Comment', () => { + const payload = getCommentsArrayMock(); + const decoded = commentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation when a Comment includes "updated_at" and "updated_by"', () => { + const commentsPayload = getCommentsMock(); + commentsPayload.updated_at = DATE_NOW; + commentsPayload.updated_by = 'someone'; + const payload = [{ ...commentsPayload }, ...getCommentsArrayMock()]; + const decoded = commentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = commentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when array includes non Comment types', () => { + const payload = [1] as unknown as CommentsArray; + const decoded = commentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('commentsArrayOrUndefined', () => { + test('it passes validation an array of Comment', () => { + const payload = getCommentsArrayMock(); + const decoded = commentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation when undefined', () => { + const payload = undefined; + const decoded = commentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when array includes non Comment types', () => { + const payload = [1] as unknown as CommentsArrayOrUndefined; + const decoded = commentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.ts new file mode 100644 index 000000000000..48bce8fabafe --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { created_at } from '../created_at'; +import { created_by } from '../created_by'; +import { id } from '../id'; +import { updated_at } from '../updated_at'; +import { updated_by } from '../updated_by'; + +export const comment = t.intersection([ + t.exact( + t.type({ + comment: NonEmptyString, + created_at, + created_by, + id, + }) + ), + t.exact( + t.partial({ + updated_at, + updated_by, + }) + ), +]); + +export const commentsArray = t.array(comment); +export type CommentsArray = t.TypeOf; +export type Comment = t.TypeOf; +export const commentsArrayOrUndefined = t.union([commentsArray, t.undefined]); +export type CommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts new file mode 100644 index 000000000000..67be8d1f15da --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { CreateComment, CreateCommentsArray } from '.'; + +export const getCreateCommentsMock = (): CreateComment => ({ + comment: 'some comments', +}); + +export const getCreateCommentsArrayMock = (): CreateCommentsArray => [getCreateCommentsMock()]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts new file mode 100644 index 000000000000..15fab1c35a19 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts @@ -0,0 +1,133 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getCreateCommentsArrayMock, getCreateCommentsMock } from './index.mock'; +import { + CreateComment, + createComment, + CreateCommentsArray, + createCommentsArray, + CreateCommentsArrayOrUndefined, + createCommentsArrayOrUndefined, +} from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('CreateComment', () => { + describe('createComment', () => { + test('it passes validation with a default comment', () => { + const payload = getCreateCommentsMock(); + const decoded = createComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = createComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "{| comment: NonEmptyString |}"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "comment" is not a string', () => { + const payload: Omit & { comment: string[] } = { + ...getCreateCommentsMock(), + comment: ['some value'], + }; + const decoded = createComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "comment"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: CreateComment & { + extraKey?: string; + } = getCreateCommentsMock(); + payload.extraKey = 'some value'; + const decoded = createComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getCreateCommentsMock()); + }); + }); + + describe('createCommentsArray', () => { + test('it passes validation an array of comments', () => { + const payload = getCreateCommentsArrayMock(); + const decoded = createCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = createCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "Array<{| comment: NonEmptyString |}>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when array includes non comments types', () => { + const payload = [1] as unknown as CreateCommentsArray; + const decoded = createCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('createCommentsArrayOrUndefined', () => { + test('it passes validation an array of comments', () => { + const payload = getCreateCommentsArrayMock(); + const decoded = createCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation when undefined', () => { + const payload = undefined; + const decoded = createCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when array includes non comments types', () => { + const payload = [1] as unknown as CreateCommentsArrayOrUndefined; + const decoded = createCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.ts new file mode 100644 index 000000000000..e0942203bac6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const createComment = t.exact( + t.type({ + comment: NonEmptyString, + }) +); + +export type CreateComment = t.TypeOf; +export const createCommentsArray = t.array(createComment); +export type CreateCommentsArray = t.TypeOf; +export type CreateComments = t.TypeOf; +export const createCommentsArrayOrUndefined = t.union([createCommentsArray, t.undefined]); +export type CreateCommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts new file mode 100644 index 000000000000..e962946e447e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_at/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const created_at = t.string; // TODO: Make this into an ISO Date string check diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts new file mode 100644 index 000000000000..ccf8d816f8e8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/created_by/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const created_by = t.string; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts new file mode 100644 index 000000000000..626b510ec895 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/cursor/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const cursor = t.string; +export type Cursor = t.TypeOf; +export const cursorOrUndefined = t.union([cursor, t.undefined]); +export type CursorOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts new file mode 100644 index 000000000000..af9f342c15e5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.test.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { CommentsArray } from '../comment'; +import { DefaultCommentsArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getCommentsArrayMock } from '../comment/index.mock'; + +describe('default_comments_array', () => { + test('it should pass validation when supplied an empty array', () => { + const payload: CommentsArray = []; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of comments', () => { + const payload: CommentsArray = getCommentsArrayMock(); + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an array of numbers', () => { + const payload = [1]; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an array of strings', () => { + const payload = ['some string']; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/index.ts new file mode 100644 index 000000000000..af1576237b9c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_comments_array/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; 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 { comment, CommentsArray } from '../comment'; + +/** + * Types the DefaultCommentsArray as: + * - If null or undefined, then a default array of type entry will be set + */ +export const DefaultCommentsArray = new t.Type( + 'DefaultCommentsArray', + t.array(comment).is, + (input): Either => + input == null ? t.success([]) : t.array(comment).decode(input), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts new file mode 100644 index 000000000000..9f4aba07c9bf --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.test.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 '@kbn/securitysolution-io-ts-utils'; +import { CommentsArray } from '../comment'; +import { DefaultCommentsArray } from '../default_comments_array'; +import { getCommentsArrayMock } from '../comment/index.mock'; + +describe('default_comments_array', () => { + test('it should pass validation when supplied an empty array', () => { + const payload: CommentsArray = []; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of comments', () => { + const payload: CommentsArray = getCommentsArrayMock(); + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an array of numbers', () => { + const payload = [1]; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an array of strings', () => { + const payload = ['some string']; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.ts new file mode 100644 index 000000000000..5b825578191f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_create_comments_array/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { createComment, CreateCommentsArray } from '../create_comment'; + +/** + * Types the DefaultCreateComments as: + * - If null or undefined, then a default array of type entry will be set + */ +export const DefaultCreateCommentsArray = new t.Type< + CreateCommentsArray, + CreateCommentsArray, + unknown +>( + 'DefaultCreateComments', + t.array(createComment).is, + (input): Either => + input == null ? t.success([]) : t.array(createComment).decode(input), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.ts new file mode 100644 index 000000000000..ea59988dfe0c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.test.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; 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 '@kbn/securitysolution-io-ts-utils'; +import { ImportCommentsArray } from '../import_comment'; +import { DefaultImportCommentsArray } from '.'; +import { getCommentsArrayMock } from '../comment/index.mock'; +import { getCreateCommentsArrayMock } from '../create_comment/index.mock'; + +describe('default_import_comments_array', () => { + test('it should pass validation when supplied an empty array', () => { + const payload: ImportCommentsArray = []; + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of comments', () => { + const payload: ImportCommentsArray = getCommentsArrayMock(); + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of new comments', () => { + const payload: ImportCommentsArray = getCreateCommentsArrayMock(); + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of new and existing comments', () => { + const payload: ImportCommentsArray = [ + ...getCommentsArrayMock(), + ...getCreateCommentsArrayMock(), + ]; + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an array of numbers', () => { + const payload = [1]; + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "DefaultImportComments"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an array of strings', () => { + const payload = ['some string']; + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "DefaultImportComments"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultImportCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.ts new file mode 100644 index 000000000000..135288c2dd3f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_import_comments_array/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { importComment, ImportCommentsArray } from '../import_comment'; + +/** + * Types the DefaultImportCommentsArray as: + * - If null or undefined, then a default array of type ImportCommentsArray will be set + */ +export const DefaultImportCommentsArray = new t.Type< + ImportCommentsArray, + ImportCommentsArray, + unknown +>( + 'DefaultImportComments', + t.array(importComment).is, + (input, context): Either => + input == null ? t.success([]) : t.array(importComment).validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts new file mode 100644 index 000000000000..fc271855fc12 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.test.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultNamespace } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('default_namespace', () => { + test('it should validate "single"', () => { + const payload = 'single'; + const decoded = DefaultNamespace.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate "agnostic"', () => { + const payload = 'agnostic'; + const decoded = DefaultNamespace.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it defaults to "single" if "undefined"', () => { + const payload = undefined; + const decoded = DefaultNamespace.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('single'); + }); + + test('it defaults to "single" if "null"', () => { + const payload = null; + const decoded = DefaultNamespace.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('single'); + }); + + test('it should FAIL validation if not "single" or "agnostic"', () => { + const payload = 'something else'; + const decoded = DefaultNamespace.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + `Invalid value "something else" supplied to "DefaultNamespace"`, + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.ts new file mode 100644 index 000000000000..667ddbb82253 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const namespaceType = t.keyof({ agnostic: null, single: null }); +export type NamespaceType = t.TypeOf; + +/** + * Types the DefaultNamespace as: + * - If null or undefined, then a default string/enumeration of "single" will be used. + */ +export const DefaultNamespace = new t.Type( + 'DefaultNamespace', + namespaceType.is, + (input, context): Either => + input == null ? t.success('single') : namespaceType.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.test.ts new file mode 100644 index 000000000000..cb7012503d38 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.test.ts @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { DefaultNamespaceArray, DefaultNamespaceArrayType } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('default_namespace_array', () => { + test('it should validate "null" single item as an array with a "single" value', () => { + const payload: DefaultNamespaceArrayType = null; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single']); + }); + + test('it should FAIL validation of numeric value', () => { + const payload = 5; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to "DefaultNamespaceArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate "undefined" item as an array with a "single" value', () => { + const payload: DefaultNamespaceArrayType = undefined; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single']); + }); + + test('it should validate "single" as an array of a "single" value', () => { + const payload: DefaultNamespaceArrayType = 'single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([payload]); + }); + + test('it should validate "agnostic" as an array of a "agnostic" value', () => { + const payload: DefaultNamespaceArrayType = 'agnostic'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([payload]); + }); + + test('it should validate "single,agnostic" as an array of 2 values of ["single", "agnostic"] values', () => { + const payload: DefaultNamespaceArrayType = 'agnostic,single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['agnostic', 'single']); + }); + + test('it should validate 3 elements of "single,agnostic,single" as an array of 3 values of ["single", "agnostic", "single"] values', () => { + const payload: DefaultNamespaceArrayType = 'single,agnostic,single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single', 'agnostic', 'single']); + }); + + test('it should validate 3 elements of "single,agnostic, single" as an array of 3 values of ["single", "agnostic", "single"] values when there are spaces', () => { + const payload: DefaultNamespaceArrayType = ' single, agnostic, single '; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single', 'agnostic', 'single']); + }); + + test('it should FAIL validation when given 3 elements of "single,agnostic,junk" since the 3rd value is junk', () => { + const payload: DefaultNamespaceArrayType = 'single,agnostic,junk'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "junk" supplied to "DefaultNamespaceArray"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts new file mode 100644 index 000000000000..494c6025f198 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_namespace_array/index.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { namespaceType } from '../default_namespace'; + +export const namespaceTypeArray = t.array(namespaceType); +export type NamespaceTypeArray = t.TypeOf; + +/** + * Types the DefaultNamespaceArray as: + * - If null or undefined, then a default string array of "single" will be used. + * - If it contains a string, then it is split along the commas and puts them into an array and validates it + */ +export const DefaultNamespaceArray = new t.Type< + NamespaceTypeArray, + string | undefined | null, + unknown +>( + 'DefaultNamespaceArray', + namespaceTypeArray.is, + (input, context): Either => { + if (input == null) { + return t.success(['single']); + } else if (typeof input === 'string') { + const commaSeparatedValues = input + .trim() + .split(',') + .map((value) => value.trim()); + return namespaceTypeArray.validate(commaSeparatedValues, context); + } + return t.failure(input, context); + }, + String +); + +export type DefaultNamespaceArrayType = t.OutputOf; +export type DefaultNamespaceArrayTypeDecoded = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts new file mode 100644 index 000000000000..3cced7284425 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.test.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { UpdateCommentsArray } from '../update_comment'; +import { DefaultUpdateCommentsArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getUpdateCommentsArrayMock } from '../update_comment/index.mock'; + +describe('default_update_comments_array', () => { + test('it should pass validation when supplied an empty array', () => { + const payload: UpdateCommentsArray = []; + const decoded = DefaultUpdateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied an array of comments', () => { + const payload: UpdateCommentsArray = getUpdateCommentsArrayMock(); + const decoded = DefaultUpdateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an array of numbers', () => { + const payload = [1]; + const decoded = DefaultUpdateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "DefaultUpdateComments"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an array of strings', () => { + const payload = ['some string']; + const decoded = DefaultUpdateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "DefaultUpdateComments"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultUpdateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.ts new file mode 100644 index 000000000000..28edd4af353e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/default_update_comments_array/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { updateCommentsArray, UpdateCommentsArray } from '../update_comment'; + +/** + * Types the DefaultUpdateComments as: + * - If null or undefined, then a default array of type UpdateCommentsArray will be set + */ +export const DefaultUpdateCommentsArray = new t.Type< + UpdateCommentsArray, + UpdateCommentsArray, + unknown +>( + 'DefaultUpdateComments', + updateCommentsArray.is, + (input, context): Either => + input == null ? t.success([]) : updateCommentsArray.validate(input, context), + t.identity +); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts new file mode 100644 index 000000000000..adba3ae0ef4f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/description/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const description = t.string; +export type Description = t.TypeOf; +export const descriptionOrUndefined = t.union([description, t.undefined]); +export type DescriptionOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts new file mode 100644 index 000000000000..4956736b5cf4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/deserializer/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const deserializer = t.string; +export type Deserializer = t.TypeOf; +export const deserializerOrUndefined = t.union([deserializer, t.undefined]); +export type DeserializerOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.ts new file mode 100644 index 000000000000..1d46d6412e12 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EndpointEntriesArray } from '.'; +import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; +import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEndpointEntryNestedMock } from '../entry_nested/index.mock'; +import { getEndpointEntryMatchWildcardMock } from '../entry_match_wildcard/index.mock'; + +export const getEndpointEntriesArrayMock = (): EndpointEntriesArray => [ + getEndpointEntryMatchMock(), + getEndpointEntryMatchAnyMock(), + getEndpointEntryNestedMock(), + getEndpointEntryMatchWildcardMock(), +]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts new file mode 100644 index 000000000000..4a317d5c9152 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.test.ts @@ -0,0 +1,120 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { getEndpointEntryMatchMock } from '../entry_match/index.mock'; +import { + endpointEntriesArray, + nonEmptyEndpointEntriesArray, + NonEmptyEndpointEntriesArray, +} from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEndpointEntryNestedMock } from '../entry_nested/index.mock'; +import { getEndpointEntriesArrayMock } from './index.mock'; +import { getEntryListMock } from '../../entries_list/index.mock'; +import { getEntryExistsMock } from '../../entries_exist/index.mock'; +import { getEndpointEntryMatchWildcardMock } from '../entry_match_wildcard/index.mock'; + +describe('Endpoint', () => { + describe('entriesArray', () => { + test('it should validate an array with match entry', () => { + const payload = [getEndpointEntryMatchMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with match_any entry', () => { + const payload = [getEndpointEntryMatchAnyMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should NOT validate an empty array', () => { + const payload: NonEmptyEndpointEntriesArray = []; + const decoded = nonEmptyEndpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[]" supplied to "NonEmptyEndpointEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('type guard for nonEmptyEndpointNestedEntries should allow array of endpoint entries', () => { + const payload: NonEmptyEndpointEntriesArray = [getEndpointEntryMatchAnyMock()]; + const guarded = nonEmptyEndpointEntriesArray.is(payload); + expect(guarded).toBeTruthy(); + }); + + test('type guard for nonEmptyEndpointNestedEntries should disallow empty arrays', () => { + const payload: NonEmptyEndpointEntriesArray = []; + const guarded = nonEmptyEndpointEntriesArray.is(payload); + expect(guarded).toBeFalsy(); + }); + + test('it should NOT validate an array with exists entry', () => { + const payload = [getEntryExistsMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "exists" supplied to "type"', + 'Invalid value "undefined" supplied to "value"', + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate an array with list entry', () => { + const payload = [getEntryListMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "list" supplied to "type"', + 'Invalid value "undefined" supplied to "value"', + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate an array with nested entry', () => { + const payload = [getEndpointEntryNestedMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with wildcard entry', () => { + const payload = [getEndpointEntryMatchWildcardMock()]; + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with all types of entries', () => { + const payload = getEndpointEntriesArrayMock(); + const decoded = endpointEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.ts new file mode 100644 index 000000000000..c9a74ae52573 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entries/index.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { endpointEntryMatch } from '../entry_match'; +import { endpointEntryMatchAny } from '../entry_match_any'; +import { endpointEntryNested } from '../entry_nested'; +import { endpointEntryMatchWildcard } from '../entry_match_wildcard'; + +export const endpointEntriesArray = t.array( + t.union([ + endpointEntryMatch, + endpointEntryMatchAny, + endpointEntryMatchWildcard, + endpointEntryNested, + ]) +); +export type EndpointEntriesArray = t.TypeOf; + +/** + * Types the nonEmptyEndpointEntriesArray as: + * - An array of entries of length 1 or greater + * + */ +export const nonEmptyEndpointEntriesArray = new t.Type< + EndpointEntriesArray, + EndpointEntriesArray, + unknown +>( + 'NonEmptyEndpointEntriesArray', + (u: unknown): u is EndpointEntriesArray => endpointEntriesArray.is(u) && u.length > 0, + (input, context): Either => { + if (Array.isArray(input) && input.length === 0) { + return t.failure(input, context); + } else { + return endpointEntriesArray.validate(input, context); + } + }, + t.identity +); + +export type NonEmptyEndpointEntriesArray = t.OutputOf; +export type NonEmptyEndpointEntriesArrayDecoded = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts new file mode 100644 index 000000000000..ddcda0e1e2d9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EndpointEntryMatch } from '.'; +import { ENTRY_VALUE, FIELD, MATCH, OPERATOR } from '../../../constants/index.mock'; + +export const getEndpointEntryMatchMock = (): EndpointEntryMatch => ({ + field: FIELD, + operator: OPERATOR, + type: MATCH, + value: ENTRY_VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts new file mode 100644 index 000000000000..561a36ab194c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.test.ts @@ -0,0 +1,101 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getEndpointEntryMatchMock } from './index.mock'; +import { EndpointEntryMatch, endpointEntryMatch } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchMock } from '../../entry_match/index.mock'; + +describe('endpointEntryMatch', () => { + test('it should validate an entry', () => { + const payload = getEndpointEntryMatchMock(); + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should NOT validate when "operator" is "excluded"', () => { + // Use the generic entry mock so we can test operator: excluded + const payload = getEntryMatchMock(); + payload.operator = 'excluded'; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "excluded" supplied to "operator"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { field: string } = { + ...getEndpointEntryMatchMock(), + field: '', + }; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is not string', () => { + const payload: Omit & { value: string[] } = { + ...getEndpointEntryMatchMock(), + value: ['some value'], + }; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is empty string', () => { + const payload: Omit & { value: string } = { + ...getEndpointEntryMatchMock(), + value: '', + }; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "match"', () => { + const payload: Omit & { type: string } = { + ...getEndpointEntryMatchMock(), + type: 'match_any', + }; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "match_any" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EndpointEntryMatch & { + extraKey?: string; + } = getEndpointEntryMatchMock(); + payload.extraKey = 'some value'; + const decoded = endpointEntryMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/index.ts new file mode 100644 index 000000000000..7cc51636cf58 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString, operatorIncluded } from '@kbn/securitysolution-io-ts-types'; + +export const endpointEntryMatch = t.exact( + t.type({ + field: NonEmptyString, + operator: operatorIncluded, + type: t.keyof({ match: null }), + value: NonEmptyString, + }) +); +export type EndpointEntryMatch = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts new file mode 100644 index 000000000000..6c04a6b596d6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ENTRY_VALUE, FIELD, MATCH_ANY, OPERATOR } from '../../../constants/index.mock'; +import { EndpointEntryMatchAny } from '.'; + +export const getEndpointEntryMatchAnyMock = (): EndpointEntryMatchAny => ({ + field: FIELD, + operator: OPERATOR, + type: MATCH_ANY, + value: [ENTRY_VALUE], +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts new file mode 100644 index 000000000000..feb04606adf9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.test.ts @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getEndpointEntryMatchAnyMock } from './index.mock'; +import { EndpointEntryMatchAny, endpointEntryMatchAny } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchAnyMock } from '../../entry_match_any/index.mock'; + +describe('endpointEntryMatchAny', () => { + test('it should validate an entry', () => { + const payload = getEndpointEntryMatchAnyMock(); + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should NOT validate when operator is "excluded"', () => { + // Use the generic entry mock so we can test operator: excluded + const payload = getEntryMatchAnyMock(); + payload.operator = 'excluded'; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "excluded" supplied to "operator"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when field is empty string', () => { + const payload: Omit & { field: string } = { + ...getEndpointEntryMatchAnyMock(), + field: '', + }; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when value is empty array', () => { + const payload: Omit & { value: string[] } = { + ...getEndpointEntryMatchAnyMock(), + value: [], + }; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "[]" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when value is not string array', () => { + const payload: Omit & { value: string } = { + ...getEndpointEntryMatchAnyMock(), + value: 'some string', + }; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "match_any"', () => { + const payload: Omit & { type: string } = { + ...getEndpointEntryMatchAnyMock(), + type: 'match', + }; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EndpointEntryMatchAny & { + extraKey?: string; + } = getEndpointEntryMatchAnyMock(); + payload.extraKey = 'some extra key'; + const decoded = endpointEntryMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchAnyMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.ts new file mode 100644 index 000000000000..7d23e7338e71 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_any/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { + NonEmptyString, + nonEmptyOrNullableStringArray, + operatorIncluded, +} from '@kbn/securitysolution-io-ts-types'; + +export const endpointEntryMatchAny = t.exact( + t.type({ + field: NonEmptyString, + operator: operatorIncluded, + type: t.keyof({ match_any: null }), + value: nonEmptyOrNullableStringArray, + }) +); +export type EndpointEntryMatchAny = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts new file mode 100644 index 000000000000..ca8f01d3e30e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ENTRY_VALUE, FIELD, OPERATOR, WILDCARD } from '../../../constants/index.mock'; +import { EndpointEntryMatchWildcard } from '.'; + +export const getEndpointEntryMatchWildcardMock = (): EndpointEntryMatchWildcard => ({ + field: FIELD, + operator: OPERATOR, + type: WILDCARD, + value: ENTRY_VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts new file mode 100644 index 000000000000..95ea73b2aac1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.test.ts @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getEndpointEntryMatchWildcardMock } from './index.mock'; +import { EndpointEntryMatchWildcard, endpointEntryMatchWildcard } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchWildcardMock } from '../../entry_match_wildcard/index.mock'; + +describe('endpointEntryMatchWildcard', () => { + test('it should validate an entry', () => { + const payload = getEndpointEntryMatchWildcardMock(); + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "excluded"', () => { + const payload = getEntryMatchWildcardMock(); + payload.operator = 'excluded'; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { field: string } = { + ...getEndpointEntryMatchWildcardMock(), + field: '', + }; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is not string', () => { + const payload: Omit & { value: string[] } = { + ...getEndpointEntryMatchWildcardMock(), + value: ['some value'], + }; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is empty string', () => { + const payload: Omit & { value: string } = { + ...getEndpointEntryMatchWildcardMock(), + value: '', + }; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "wildcard"', () => { + const payload: Omit & { type: string } = { + ...getEndpointEntryMatchWildcardMock(), + type: 'match', + }; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EndpointEntryMatchWildcard & { + extraKey?: string; + } = getEndpointEntryMatchWildcardMock(); + payload.extraKey = 'some value'; + const decoded = endpointEntryMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchWildcardMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.ts new file mode 100644 index 000000000000..cfc96337b627 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_match_wildcard/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { + NonEmptyString, + operatorExcluded, + operatorIncluded, +} from '@kbn/securitysolution-io-ts-types'; + +export const endpointEntryMatchWildcard = t.exact( + t.type({ + field: NonEmptyString, + operator: t.union([operatorIncluded, operatorExcluded]), + type: t.keyof({ wildcard: null }), + value: NonEmptyString, + }) +); +export type EndpointEntryMatchWildcard = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts new file mode 100644 index 000000000000..93b99e71b0bc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EndpointEntryNested } from '.'; +import { FIELD, NESTED } from '../../../constants/index.mock'; +import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; +import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; + +export const getEndpointEntryNestedMock = (): EndpointEntryNested => ({ + entries: [getEndpointEntryMatchMock(), getEndpointEntryMatchAnyMock()], + field: FIELD, + type: NESTED, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts new file mode 100644 index 000000000000..d68a0686a439 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.test.ts @@ -0,0 +1,136 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { EndpointEntryNested, endpointEntryNested } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEndpointEntryNestedMock } from './index.mock'; +import { getEndpointEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { + nonEmptyEndpointNestedEntriesArray, + NonEmptyEndpointNestedEntriesArray, +} from '../non_empty_nested_entries_array'; +import { getEndpointEntryMatchMock } from '../entry_match/index.mock'; +import { getEntryExistsMock } from '../../entries_exist/index.mock'; + +describe('endpointEntryNested', () => { + test('it should validate a nested entry', () => { + const payload = getEndpointEntryNestedMock(); + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "type" is not "nested"', () => { + const payload: Omit & { type: 'match' } = { + ...getEndpointEntryNestedMock(), + type: 'match', + }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { + field: string; + } = { ...getEndpointEntryNestedMock(), field: '' }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "field" is not a string', () => { + const payload: Omit & { + field: number; + } = { ...getEndpointEntryNestedMock(), field: 1 }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "entries" is not an array', () => { + const payload: Omit & { + entries: string; + } = { ...getEndpointEntryNestedMock(), entries: 'im a string' }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "im a string" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate when "entries" contains an entry item that is type "match"', () => { + const payload = { ...getEndpointEntryNestedMock(), entries: [getEndpointEntryMatchAnyMock()] }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + entries: [ + { + field: 'host.name', + operator: 'included', + type: 'match_any', + value: ['some host name'], + }, + ], + field: 'host.name', + type: 'nested', + }); + }); + + test('it should NOT validate when "entries" contains an entry item that is type "exists"', () => { + const payload = { ...getEndpointEntryNestedMock(), entries: [getEntryExistsMock()] }; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "exists" supplied to "entries,type"', + 'Invalid value "undefined" supplied to "entries,value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EndpointEntryNested & { + extraKey?: string; + } = getEndpointEntryNestedMock(); + payload.extraKey = 'some extra key'; + const decoded = endpointEntryNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEndpointEntryNestedMock()); + }); + + test('type guard for nonEmptyEndpointNestedEntries should allow array of endpoint entries', () => { + const payload: NonEmptyEndpointNestedEntriesArray = [ + getEndpointEntryMatchMock(), + getEndpointEntryMatchAnyMock(), + ]; + const guarded = nonEmptyEndpointNestedEntriesArray.is(payload); + expect(guarded).toBeTruthy(); + }); + + test('type guard for nonEmptyEndpointNestedEntries should disallow empty arrays', () => { + const payload: NonEmptyEndpointNestedEntriesArray = []; + const guarded = nonEmptyEndpointNestedEntriesArray.is(payload); + expect(guarded).toBeFalsy(); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/index.ts new file mode 100644 index 000000000000..f02570af1013 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/entry_nested/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { nonEmptyEndpointNestedEntriesArray } from '../non_empty_nested_entries_array'; + +export const endpointEntryNested = t.exact( + t.type({ + entries: nonEmptyEndpointNestedEntriesArray, + field: NonEmptyString, + type: t.keyof({ nested: null }), + }) +); +export type EndpointEntryNested = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts new file mode 100644 index 000000000000..5138682f463b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './entries'; +export * from './non_empty_nested_entries_array'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts new file mode 100644 index 000000000000..5085b4fdacac --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/endpoint/non_empty_nested_entries_array/index.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { endpointEntryMatch } from '../entry_match'; +import { endpointEntryMatchAny } from '../entry_match_any'; + +export const endpointNestedEntriesArray = t.array( + t.union([endpointEntryMatch, endpointEntryMatchAny]) +); +export type EndpointNestedEntriesArray = t.TypeOf; + +/** + * Types the nonEmptyNestedEntriesArray as: + * - An array of entries of length 1 or greater + * + */ +export const nonEmptyEndpointNestedEntriesArray = new t.Type< + EndpointNestedEntriesArray, + EndpointNestedEntriesArray, + unknown +>( + 'NonEmptyEndpointNestedEntriesArray', + (u: unknown): u is EndpointNestedEntriesArray => endpointNestedEntriesArray.is(u) && u.length > 0, + (input, context): Either => { + if (Array.isArray(input) && input.length === 0) { + return t.failure(input, context); + } else { + return endpointNestedEntriesArray.validate(input, context); + } + }, + t.identity +); + +export type NonEmptyEndpointNestedEntriesArray = t.OutputOf< + typeof nonEmptyEndpointNestedEntriesArray +>; +export type NonEmptyEndpointNestedEntriesArrayDecoded = t.TypeOf< + typeof nonEmptyEndpointNestedEntriesArray +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.ts new file mode 100644 index 000000000000..1aeea284751b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.mock.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntriesArray } from '.'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; +import { getEntryListMock } from '../entries_list/index.mock'; +import { getEntryMatchMock } from '../entry_match/index.mock'; +import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEntryNestedMock } from '../entry_nested/index.mock'; + +export const getListAndNonListEntriesArrayMock = (): EntriesArray => [ + getEntryMatchMock(), + getEntryMatchAnyMock(), + getEntryListMock(), + getEntryExistsMock(), + getEntryNestedMock(), +]; + +export const getListEntriesArrayMock = (): EntriesArray => [getEntryListMock(), getEntryListMock()]; + +export const getEntriesArrayMock = (): EntriesArray => [ + getEntryMatchMock(), + getEntryMatchAnyMock(), + getEntryExistsMock(), + getEntryNestedMock(), +]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts new file mode 100644 index 000000000000..25c52b68a6f9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.test.ts @@ -0,0 +1,147 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getEntryMatchMock } from '../entry_match/index.mock'; +import { entriesArray, entriesArrayOrUndefined, entry } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; +import { getEntryListMock } from '../entries_list/index.mock'; +import { getEntryNestedMock } from '../entry_nested/index.mock'; +import { getEntriesArrayMock } from './index.mock'; + +describe('Entries', () => { + describe('entry', () => { + test('it should validate a match entry', () => { + const payload = getEntryMatchMock(); + const decoded = entry.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a match_any entry', () => { + const payload = getEntryMatchAnyMock(); + const decoded = entry.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a exists entry', () => { + const payload = getEntryExistsMock(); + const decoded = entry.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a list entry', () => { + const payload = getEntryListMock(); + const decoded = entry.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation of nested entry', () => { + const payload = getEntryNestedMock(); + const decoded = entry.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "operator"', + 'Invalid value "nested" supplied to "type"', + 'Invalid value "undefined" supplied to "value"', + 'Invalid value "undefined" supplied to "list"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('entriesArray', () => { + test('it should validate an array with match entry', () => { + const payload = [getEntryMatchMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with match_any entry', () => { + const payload = [getEntryMatchAnyMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with exists entry', () => { + const payload = [getEntryExistsMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with list entry', () => { + const payload = [getEntryListMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with nested entry', () => { + const payload = [getEntryNestedMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with all types of entries', () => { + const payload = [...getEntriesArrayMock()]; + const decoded = entriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + }); + + describe('entriesArrayOrUndefined', () => { + test('it should validate undefined', () => { + const payload = undefined; + const decoded = entriesArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array with nested entry', () => { + const payload = [getEntryNestedMock()]; + const decoded = entriesArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.ts new file mode 100644 index 000000000000..73340d2c0af5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries/index.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { entriesExists } from '../entries_exist'; +import { entriesList } from '../entries_list'; +import { entriesMatch } from '../entry_match'; +import { entriesMatchAny } from '../entry_match_any'; +import { entriesMatchWildcard } from '../entry_match_wildcard'; +import { entriesNested } from '../entry_nested'; + +// NOTE: Type nested is not included here to denote it's non-recursive nature. +// So a nested entry is really just a collection of `Entry` types. +export const entry = t.union([ + entriesMatch, + entriesMatchAny, + entriesList, + entriesExists, + entriesMatchWildcard, +]); +export type Entry = t.TypeOf; + +export const entriesArray = t.array( + t.union([ + entriesMatch, + entriesMatchAny, + entriesList, + entriesExists, + entriesNested, + entriesMatchWildcard, + ]) +); +export type EntriesArray = t.TypeOf; + +export const entriesArrayOrUndefined = t.union([entriesArray, t.undefined]); +export type EntriesArrayOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.ts new file mode 100644 index 000000000000..e66d14c3c7af --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.mock.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryExists } from '.'; +import { EXISTS, FIELD, OPERATOR } from '../../constants/index.mock'; + +export const getEntryExistsMock = (): EntryExists => ({ + field: FIELD, + operator: OPERATOR, + type: EXISTS, +}); + +export const getEntryExistsExcludedMock = (): EntryExists => ({ + ...getEntryExistsMock(), + operator: 'excluded', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts new file mode 100644 index 000000000000..dcc6d47a437a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.test.ts @@ -0,0 +1,78 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { getEntryExistsMock } from './index.mock'; +import { entriesExists, EntryExists } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('entriesExists', () => { + test('it should validate an entry', () => { + const payload = getEntryExistsMock(); + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "included"', () => { + const payload = getEntryExistsMock(); + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "excluded"', () => { + const payload = getEntryExistsMock(); + payload.operator = 'excluded'; + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { field: string } = { + ...getEntryExistsMock(), + field: '', + }; + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EntryExists & { + extraKey?: string; + } = getEntryExistsMock(); + payload.extraKey = 'some extra key'; + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryExistsMock()); + }); + + test('it should FAIL validation when "type" is not "exists"', () => { + const payload: Omit & { type: string } = { + ...getEntryExistsMock(), + type: 'match', + }; + const decoded = entriesExists.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts new file mode 100644 index 000000000000..44c83c3f5b64 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_exist/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { listOperator as operator } from '../list_operator'; + +export const entriesExists = t.exact( + t.type({ + field: NonEmptyString, + operator, + type: t.keyof({ exists: null }), + }) +); +export type EntryExists = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts new file mode 100644 index 000000000000..77c73d0bcfa3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryList } from '.'; +import { FIELD, LIST, LIST_ID, OPERATOR, TYPE } from '../../constants/index.mock'; + +export const getEntryListMock = (): EntryList => ({ + field: FIELD, + list: { id: LIST_ID, type: TYPE }, + operator: OPERATOR, + type: LIST, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts new file mode 100644 index 000000000000..a9b56207d959 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.test.ts @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { getEntryListMock } from './index.mock'; +import { entriesList, EntryList } from '.'; + +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('entriesList', () => { + test('it should validate an entry', () => { + const payload = getEntryListMock(); + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when operator is "included"', () => { + const payload = getEntryListMock(); + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "excluded"', () => { + const payload = getEntryListMock(); + payload.operator = 'excluded'; + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "list" is not expected value', () => { + const payload: Omit & { list: string } = { + ...getEntryListMock(), + list: 'someListId', + }; + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "someListId" supplied to "list"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "list.id" is empty string', () => { + const payload: Omit & { list: { id: string; type: 'ip' } } = { + ...getEntryListMock(), + list: { id: '', type: 'ip' }, + }; + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "list,id"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "lists"', () => { + const payload: Omit & { type: 'match_any' } = { + ...getEntryListMock(), + type: 'match_any', + }; + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "match_any" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EntryList & { + extraKey?: string; + } = getEntryListMock(); + payload.extraKey = 'some extra key'; + const decoded = entriesList.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryListMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/index.ts new file mode 100644 index 000000000000..214f0c92db22 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entries_list/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +import { type } from '../type'; +import { listOperator as operator } from '../list_operator'; + +export const entriesList = t.exact( + t.type({ + field: NonEmptyString, + list: t.exact(t.type({ id: NonEmptyString, type })), + operator, + type: t.keyof({ list: null }), + }) +); +export type EntryList = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.ts new file mode 100644 index 000000000000..9af6cf08090b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.mock.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryMatch } from '.'; +import { ENTRY_VALUE, FIELD, MATCH, OPERATOR } from '../../constants/index.mock'; + +export const getEntryMatchMock = (): EntryMatch => ({ + field: FIELD, + operator: OPERATOR, + type: MATCH, + value: ENTRY_VALUE, +}); + +export const getEntryMatchExcludeMock = (): EntryMatch => ({ + ...getEntryMatchMock(), + operator: 'excluded', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts new file mode 100644 index 000000000000..6f2fc7fd9e8d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.test.ts @@ -0,0 +1,106 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { getEntryMatchMock } from './index.mock'; +import { entriesMatch, EntryMatch } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('entriesMatch', () => { + test('it should validate an entry', () => { + const payload = getEntryMatchMock(); + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when operator is "included"', () => { + const payload = getEntryMatchMock(); + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "excluded"', () => { + const payload = getEntryMatchMock(); + payload.operator = 'excluded'; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { field: string } = { + ...getEntryMatchMock(), + field: '', + }; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is not string', () => { + const payload: Omit & { value: string[] } = { + ...getEntryMatchMock(), + value: ['some value'], + }; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is empty string', () => { + const payload: Omit & { value: string } = { + ...getEntryMatchMock(), + value: '', + }; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "match"', () => { + const payload: Omit & { type: string } = { + ...getEntryMatchMock(), + type: 'match_any', + }; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "match_any" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EntryMatch & { + extraKey?: string; + } = getEntryMatchMock(); + payload.extraKey = 'some value'; + const decoded = entriesMatch.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts new file mode 100644 index 000000000000..8e56991b977a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { listOperator as operator } from '../list_operator'; + +export const entriesMatch = t.exact( + t.type({ + field: NonEmptyString, + operator, + type: t.keyof({ match: null }), + value: NonEmptyString, + }) +); +export type EntryMatch = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.ts new file mode 100644 index 000000000000..a564d4e8fd95 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.mock.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryMatchAny } from '.'; +import { ENTRY_VALUE, FIELD, MATCH_ANY, OPERATOR } from '../../constants/index.mock'; + +export const getEntryMatchAnyMock = (): EntryMatchAny => ({ + field: FIELD, + operator: OPERATOR, + type: MATCH_ANY, + value: [ENTRY_VALUE], +}); + +export const getEntryMatchAnyExcludeMock = (): EntryMatchAny => ({ + ...getEntryMatchAnyMock(), + operator: 'excluded', + value: [ENTRY_VALUE, 'some other host name'], +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts new file mode 100644 index 000000000000..84844c432aa2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { getEntryMatchAnyMock } from './index.mock'; +import { entriesMatchAny, EntryMatchAny } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('entriesMatchAny', () => { + test('it should validate an entry', () => { + const payload = getEntryMatchAnyMock(); + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when operator is "included"', () => { + const payload = getEntryMatchAnyMock(); + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when operator is "excluded"', () => { + const payload = getEntryMatchAnyMock(); + payload.operator = 'excluded'; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when field is empty string', () => { + const payload: Omit & { field: string } = { + ...getEntryMatchAnyMock(), + field: '', + }; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when value is empty array', () => { + const payload: Omit & { value: string[] } = { + ...getEntryMatchAnyMock(), + value: [], + }; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "[]" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when value is not string array', () => { + const payload: Omit & { value: string } = { + ...getEntryMatchAnyMock(), + value: 'some string', + }; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "match_any"', () => { + const payload: Omit & { type: string } = { + ...getEntryMatchAnyMock(), + type: 'match', + }; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EntryMatchAny & { + extraKey?: string; + } = getEntryMatchAnyMock(); + payload.extraKey = 'some extra key'; + const decoded = entriesMatchAny.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchAnyMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts new file mode 100644 index 000000000000..989c729f8b1b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_any/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NonEmptyString, nonEmptyOrNullableStringArray } from '@kbn/securitysolution-io-ts-types'; +import { listOperator as operator } from '../list_operator'; + +export const entriesMatchAny = t.exact( + t.type({ + field: NonEmptyString, + operator, + type: t.keyof({ match_any: null }), + value: nonEmptyOrNullableStringArray, + }) +); +export type EntryMatchAny = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.ts new file mode 100644 index 000000000000..c279fe3ed45d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.mock.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryMatchWildcard } from '.'; +import { ENTRY_VALUE, FIELD, OPERATOR, WILDCARD } from '../../constants/index.mock'; + +export const getEntryMatchWildcardMock = (): EntryMatchWildcard => ({ + field: FIELD, + operator: OPERATOR, + type: WILDCARD, + value: ENTRY_VALUE, +}); + +export const getEntryMatchWildcardExcludeMock = (): EntryMatchWildcard => ({ + ...getEntryMatchWildcardMock(), + operator: 'excluded', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts new file mode 100644 index 000000000000..4bd2d146412a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { getEntryMatchWildcardMock } from './index.mock'; +import { entriesMatchWildcard, EntryMatchWildcard } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('entriesMatchWildcard', () => { + test('it should validate an entry', () => { + const payload = getEntryMatchWildcardMock(); + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when operator is "included"', () => { + const payload = getEntryMatchWildcardMock(); + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate when "operator" is "excluded"', () => { + const payload = getEntryMatchWildcardMock(); + payload.operator = 'excluded'; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { field: string } = { + ...getEntryMatchWildcardMock(), + field: '', + }; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is not string', () => { + const payload: Omit & { value: string[] } = { + ...getEntryMatchWildcardMock(), + value: ['some value'], + }; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["some value"]" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "value" is empty string', () => { + const payload: Omit & { value: string } = { + ...getEntryMatchWildcardMock(), + value: '', + }; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "value"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "type" is not "wildcard"', () => { + const payload: Omit & { type: string } = { + ...getEntryMatchWildcardMock(), + type: 'match', + }; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra keys', () => { + const payload: EntryMatchWildcard & { + extraKey?: string; + } = getEntryMatchWildcardMock(); + payload.extraKey = 'some value'; + const decoded = entriesMatchWildcard.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryMatchWildcardMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts new file mode 100644 index 000000000000..af168e33fa70 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_match_wildcard/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { listOperator as operator } from '../list_operator'; + +export const entriesMatchWildcard = t.exact( + t.type({ + field: NonEmptyString, + operator, + type: t.keyof({ wildcard: null }), + value: NonEmptyString, + }) +); +export type EntryMatchWildcard = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.ts new file mode 100644 index 000000000000..890c3d379d27 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EntryNested } from '.'; +import { NESTED, NESTED_FIELD } from '../../constants/index.mock'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; +import { getEntryMatchExcludeMock, getEntryMatchMock } from '../entry_match/index.mock'; +import { getEntryMatchAnyExcludeMock, getEntryMatchAnyMock } from '../entry_match_any/index.mock'; + +export const getEntryNestedMock = (): EntryNested => ({ + entries: [getEntryMatchMock(), getEntryMatchAnyMock()], + field: NESTED_FIELD, + type: NESTED, +}); + +export const getEntryNestedExcludeMock = (): EntryNested => ({ + ...getEntryNestedMock(), + entries: [getEntryMatchExcludeMock(), getEntryMatchAnyExcludeMock()], +}); + +export const getEntryNestedMixedEntries = (): EntryNested => ({ + ...getEntryNestedMock(), + entries: [getEntryMatchMock(), getEntryMatchAnyExcludeMock(), getEntryExistsMock()], +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts new file mode 100644 index 000000000000..be37a0273bce --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.test.ts @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { getEntryNestedMock } from './index.mock'; +import { entriesNested, EntryNested } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; + +describe('entriesNested', () => { + test('it should validate a nested entry', () => { + const payload = getEntryNestedMock(); + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when "type" is not "nested"', () => { + const payload: Omit & { type: 'match' } = { + ...getEntryNestedMock(), + type: 'match', + }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "match" supplied to "type"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "field" is empty string', () => { + const payload: Omit & { + field: string; + } = { ...getEntryNestedMock(), field: '' }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "field" is not a string', () => { + const payload: Omit & { + field: number; + } = { ...getEntryNestedMock(), field: 1 }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "field"']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when "entries" is not a an array', () => { + const payload: Omit & { + entries: string; + } = { ...getEntryNestedMock(), entries: 'im a string' }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "im a string" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate when "entries" contains an entry item that is type "match"', () => { + const payload = { ...getEntryNestedMock(), entries: [getEntryMatchAnyMock()] }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + entries: [ + { + field: 'host.name', + operator: 'included', + type: 'match_any', + value: ['some host name'], + }, + ], + field: 'parent.field', + type: 'nested', + }); + }); + + test('it should validate when "entries" contains an entry item that is type "exists"', () => { + const payload = { ...getEntryNestedMock(), entries: [getEntryExistsMock()] }; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + entries: [ + { + field: 'host.name', + operator: 'included', + type: 'exists', + }, + ], + field: 'parent.field', + type: 'nested', + }); + }); + + test('it should strip out extra keys', () => { + const payload: EntryNested & { + extraKey?: string; + } = getEntryNestedMock(); + payload.extraKey = 'some extra key'; + const decoded = entriesNested.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getEntryNestedMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/index.ts new file mode 100644 index 000000000000..dac5d6a3d5a8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/entry_nested/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { nonEmptyNestedEntriesArray } from '../non_empty_nested_entries_array'; + +export const entriesNested = t.exact( + t.type({ + entries: nonEmptyNestedEntriesArray, + field: NonEmptyString, + type: t.keyof({ nested: null }), + }) +); +export type EntryNested = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts new file mode 100644 index 000000000000..ded6a6bfbb8a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExportExceptionDetails } from '.'; + +export interface ExportExceptionDetailsMock { + listCount?: number; + missingListsCount?: number; + missingLists?: Array>; + itemCount?: number; + missingItemCount?: number; + missingItems?: Array>; +} + +export const getExceptionExportDetailsMock = ( + details?: ExportExceptionDetailsMock +): ExportExceptionDetails => ({ + exported_exception_list_count: details?.listCount ?? 0, + exported_exception_list_item_count: details?.itemCount ?? 0, + missing_exception_list_item_count: details?.missingItemCount ?? 0, + missing_exception_list_items: details?.missingItems ?? [], + missing_exception_lists: details?.missingLists ?? [], + missing_exception_lists_count: details?.missingListsCount ?? 0, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts new file mode 100644 index 000000000000..fe8150fd6f3b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getExceptionExportDetailsMock } from './index.mock'; +import { exportExceptionDetailsSchema, ExportExceptionDetails } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('exportExceptionDetails', () => { + test('it should validate export meta', () => { + const payload = getExceptionExportDetailsMock(); + const decoded = exportExceptionDetailsSchema.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should strip out extra keys', () => { + const payload: ExportExceptionDetails & { + extraKey?: string; + } = getExceptionExportDetailsMock(); + payload.extraKey = 'some extra key'; + const decoded = exportExceptionDetailsSchema.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getExceptionExportDetailsMock()); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts new file mode 100644 index 000000000000..358e987d8b17 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const exportExceptionDetails = { + exported_exception_list_count: t.number, + exported_exception_list_item_count: t.number, + missing_exception_list_item_count: t.number, + missing_exception_list_items: t.array( + t.exact( + t.type({ + item_id: NonEmptyString, + }) + ) + ), + missing_exception_lists: t.array( + t.exact( + t.type({ + list_id: NonEmptyString, + }) + ) + ), + missing_exception_lists_count: t.number, +}; + +export const exportExceptionDetailsSchema = t.exact(t.type(exportExceptionDetails)); + +export type ExportExceptionDetails = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.test.ts new file mode 100644 index 000000000000..ac57828355d3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.test.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exceptionListType, ExceptionListTypeEnum } from '.'; + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('exceptionListType', () => { + test('it should validate for "detection"', () => { + const payload = 'detection'; + const decoded = exceptionListType.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate for "rule_default"', () => { + const payload = 'rule_default'; + const decoded = exceptionListType.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate for "endpoint"', () => { + const payload = 'endpoint'; + const decoded = exceptionListType.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should contain same amount of keys as enum', () => { + // Might seem like a weird test, but its meant to + // ensure that if exceptionListType is updated, you + // also update the ExceptionListTypeEnum, a workaround + // for io-ts not yet supporting enums + // https://github.com/gcanti/io-ts/issues/67 + const keys = Object.keys(exceptionListType.keys).sort().join(',').toLowerCase(); + const enumKeys = Object.keys(ExceptionListTypeEnum).sort().join(',').toLowerCase(); + + expect(keys).toEqual(enumKeys); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.ts new file mode 100644 index 000000000000..50273a9c55a9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list/index.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const exceptionListType = t.keyof({ + detection: null, + rule_default: null, + endpoint: null, + endpoint_trusted_apps: null, + endpoint_events: null, + endpoint_host_isolation_exceptions: null, + endpoint_blocklists: null, +}); +export const exceptionListTypeOrUndefined = t.union([exceptionListType, t.undefined]); +export type ExceptionListType = t.TypeOf; +export type ExceptionListTypeOrUndefined = t.TypeOf; +export enum ExceptionListTypeEnum { + DETECTION = 'detection', // shared exception list type + RULE_DEFAULT = 'rule_default', // rule default, cannot be shared + ENDPOINT = 'endpoint', + ENDPOINT_TRUSTED_APPS = 'endpoint', + ENDPOINT_EVENTS = 'endpoint_events', + ENDPOINT_HOST_ISOLATION_EXCEPTIONS = 'endpoint_host_isolation_exceptions', + ENDPOINT_BLOCKLISTS = 'endpoint_blocklists', +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts new file mode 100644 index 000000000000..36857aec92df --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_list_item_type/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const exceptionListItemType = t.keyof({ simple: null }); +export const exceptionListItemTypeOrUndefined = t.union([exceptionListItemType, t.undefined]); +export type ExceptionListItemType = t.TypeOf; +export type ExceptionListItemTypeOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts new file mode 100644 index 000000000000..9a3f4db110ed --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/expire_time/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { IsoDateString } from '@kbn/securitysolution-io-ts-types'; + +export const expireTime = IsoDateString; +export const expireTimeOrUndefined = t.union([expireTime, t.undefined]); +export type ExpireTimeOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts new file mode 100644 index 000000000000..885d714de441 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/file/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const file = t.object; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts new file mode 100644 index 000000000000..43ac9592ed31 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/filter/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const filter = t.string; +export type Filter = t.TypeOf; +export const filterOrUndefined = t.union([filter, t.undefined]); +export type FilterOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts new file mode 100644 index 000000000000..967282c158a2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/id/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const id = NonEmptyString; +export type Id = t.TypeOf; +export const idOrUndefined = t.union([id, t.undefined]); +export type IdOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts new file mode 100644 index 000000000000..afeb2de36ea1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/immutable/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const immutable = t.boolean; +export type Immutable = t.TypeOf; +export const immutableOrUndefined = t.union([immutable, t.undefined]); +export type ImmutableOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts new file mode 100644 index 000000000000..a447d1f53507 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.test.ts @@ -0,0 +1,134 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getCommentsArrayMock, getCommentsMock } from '../comment/index.mock'; +import { getCreateCommentsArrayMock } from '../create_comment/index.mock'; +import { + importComment, + ImportCommentsArray, + importCommentsArray, + ImportCommentsArrayOrUndefined, + importCommentsArrayOrUndefined, +} from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('ImportComment', () => { + describe('importComment', () => { + test('it passes validation with a typical comment', () => { + const payload = getCommentsMock(); + const decoded = importComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation with a new comment', () => { + const payload = { comment: 'new comment' }; + const decoded = importComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = importComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('importCommentsArray', () => { + test('it passes validation an array of Comment', () => { + const payload = getCommentsArrayMock(); + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation an array of CreateComment', () => { + const payload = getCreateCommentsArrayMock(); + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation an array of Comment and CreateComment', () => { + const payload = [...getCommentsArrayMock(), ...getCreateCommentsArrayMock()]; + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when undefined', () => { + const payload = undefined; + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when array includes non ImportComment types', () => { + const payload = [1] as unknown as ImportCommentsArray; + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('importCommentsArrayOrUndefined', () => { + test('it passes validation an array of ImportComment', () => { + const payload = [...getCommentsArrayMock(), ...getCreateCommentsArrayMock()]; + const decoded = importCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it passes validation when undefined', () => { + const payload = undefined; + const decoded = importCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it fails validation when array includes non ImportComment types', () => { + const payload = [1] as unknown as ImportCommentsArrayOrUndefined; + const decoded = importCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<(({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: NonEmptyString |})>"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/index.ts new file mode 100644 index 000000000000..c4c906117ecd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/import_comment/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { createComment } from '../create_comment'; +import { comment } from '../comment'; + +export const importComment = t.union([comment, createComment]); + +export type ImportComment = t.TypeOf; +export const importCommentsArray = t.array(importComment); +export type ImportCommentsArray = t.TypeOf; +export const importCommentsArrayOrUndefined = t.union([importCommentsArray, t.undefined]); +export type ImportCommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/index.ts new file mode 100644 index 000000000000..0c3d5e4959bc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/include_expired_exceptions/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; 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'; + +export const include_expired_exceptions = t.keyof({ true: null, false: null }); +export const includeExpiredExceptionsOrUndefined = t.union([ + include_expired_exceptions, + t.undefined, +]); +export type IncludeExpiredExceptionsOrUndefined = t.TypeOf< + typeof includeExpiredExceptionsOrUndefined +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts new file mode 100644 index 000000000000..0ff54c5e5a72 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './comment'; +export * from './create_comment'; +export * from './created_at'; +export * from './created_by'; +export * from './cursor'; +export * from './default_namespace'; +export * from './default_namespace_array'; +export * from './default_create_comments_array'; +export * from './default_import_comments_array'; +export * from './description'; +export * from './deserializer'; +export * from './endpoint'; +export * from './entries'; +export * from './entries_exist'; +export * from './entries_list'; +export * from './entry_match'; +export * from './entry_match_any'; +export * from './entry_match_wildcard'; +export * from './entry_nested'; +export * from './exception_export_details'; +export * from './exception_list'; +export * from './exception_list_item_type'; +export * from './expire_time'; +export * from './filter'; +export * from './id'; +export * from './immutable'; +export * from './import_comment'; +export * from './item_id'; +export * from './list_id'; +export * from './list_operator'; +export * from './list_type'; +export * from './lists'; +export * from './lists_default_array'; +export * from './max_size'; +export * from './meta'; +export * from './name'; +export * from './namespace_type'; +export * from './non_empty_entries_array'; +export * from './non_empty_nested_entries_array'; +export * from './os_type'; +export * from './page'; +export * from './per_page'; +export * from './pit'; +export * from './search'; +export * from './search_after'; +export * from './serializer'; +export * from './sort_field'; +export * from './sort_order'; +export * from './tags'; +export * from './tie_breaker_id'; +export * from './timestamp'; +export * from './total'; +export * from './type'; +export * from './underscore_version'; +export * from './update_comment'; +export * from './updated_at'; +export * from './updated_by'; +export * from './refresh'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts new file mode 100644 index 000000000000..5a71e1242d26 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const item = t.string; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts new file mode 100644 index 000000000000..44ccc97d4666 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/item_id/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const item_id = NonEmptyString; +export type ItemId = t.TypeOf; +export const itemIdOrUndefined = t.union([item_id, t.undefined]); +export type ItemIdOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts new file mode 100644 index 000000000000..c813d7170e8a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_id/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const list_id = NonEmptyString; +export type ListId = t.TypeOf; +export const list_idOrUndefined = t.union([list_id, t.undefined]); +export type ListIdOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts new file mode 100644 index 000000000000..d3d67a8fd60a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.test.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { ListOperatorEnum as OperatorEnum, listOperator as operator } from '.'; + +describe('operator', () => { + test('it should validate for "included"', () => { + const payload = 'included'; + const decoded = operator.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate for "excluded"', () => { + const payload = 'excluded'; + const decoded = operator.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should contain same amount of keys as enum', () => { + // Might seem like a weird test, but its meant to + // ensure that if operator is updated, you + // also update the operatorEnum, a workaround + // for io-ts not yet supporting enums + // https://github.com/gcanti/io-ts/issues/67 + const keys = Object.keys(operator.keys).sort().join(',').toLowerCase(); + const enumKeys = Object.keys(OperatorEnum).sort().join(',').toLowerCase(); + + expect(keys).toEqual(enumKeys); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.ts new file mode 100644 index 000000000000..096b21ec20f9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_operator/index.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const listOperator = t.keyof({ excluded: null, included: null }); +export type ListOperator = t.TypeOf; +export enum ListOperatorEnum { + INCLUDED = 'included', + EXCLUDED = 'excluded', +} + +export const listOperatorType = t.keyof({ + nested: null, + match: null, + match_any: null, + wildcard: null, + exists: null, + list: null, +}); +export type ListOperatorType = t.TypeOf; +export enum ListOperatorTypeEnum { + NESTED = 'nested', + MATCH = 'match', + MATCH_ANY = 'match_any', + WILDCARD = 'wildcard', + EXISTS = 'exists', + LIST = 'list', +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts new file mode 100644 index 000000000000..7a160486c399 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/list_type/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const list_type = t.keyof({ item: null, list: null }); +export type ListType = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.ts new file mode 100644 index 000000000000..6ad3c6a371d1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.mock.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { List, ListArray } from '.'; +import { ENDPOINT_LIST_ID } from '@kbn/securitysolution-list-constants'; + +export const getListMock = (): List => ({ + id: 'some_uuid', + list_id: 'list_id_single', + namespace_type: 'single', + type: 'detection', +}); + +export const getEndpointListMock = (): List => ({ + id: ENDPOINT_LIST_ID, + list_id: ENDPOINT_LIST_ID, + namespace_type: 'agnostic', + type: 'endpoint', +}); + +export const getListArrayMock = (): ListArray => [getListMock(), getEndpointListMock()]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts new file mode 100644 index 000000000000..aecfe9501ac1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts @@ -0,0 +1,125 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getEndpointListMock, getListArrayMock, getListMock } from './index.mock'; +import { List, list, ListArray, listArray, ListArrayOrUndefined, listArrayOrUndefined } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +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" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", 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" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", namespace_type: "agnostic" | "single" |}> | undefined)"', + 'Invalid value "[1]" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "rule_default" | "endpoint" | "endpoint_trusted_apps" | "endpoint_events" | "endpoint_host_isolation_exceptions" | "endpoint_blocklists", namespace_type: "agnostic" | "single" |}> | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.ts new file mode 100644 index 000000000000..bbc99142ffc7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { exceptionListType } from '../exception_list'; +import { namespaceType } from '../default_namespace'; + +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/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.test.ts new file mode 100644 index 000000000000..b702f617d17c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { DefaultListArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getListArrayMock } from '../lists/index.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/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/index.ts new file mode 100644 index 000000000000..33ab281a6f17 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/lists_default_array/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; 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 { list, ListArray } from '../lists'; + +/** + * Types the DefaultListArray as: + * - If null or undefined, then a default array of type list will be set + */ +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/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.test.ts new file mode 100644 index 000000000000..2c733c93ee77 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.test.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { maxSizeOrUndefined } from '.'; + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +describe('maxSizeOrUndefined', () => { + test('it will validate a correct max value', () => { + const payload = 123; + const decoded = maxSizeOrUndefined.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 fail to validate a 0', () => { + const payload = 0; + const decoded = maxSizeOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "0" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it will fail to validate a -1', () => { + const payload = -1; + const decoded = maxSizeOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "-1" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it will fail to validate a string', () => { + const payload = '123'; + const decoded = maxSizeOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "123" supplied to "(PositiveIntegerGreaterThanZero | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts new file mode 100644 index 000000000000..c652ae81d6c4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/max_size/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; +import * as t from 'io-ts'; + +export const max_size = PositiveIntegerGreaterThanZero; +export type MaxSize = t.TypeOf; + +export const maxSizeOrUndefined = t.union([max_size, t.undefined]); +export type MaxSizeOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts new file mode 100644 index 000000000000..547b45969be7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/meta/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const meta = t.object; +export type Meta = t.TypeOf; +export const metaOrUndefined = t.union([meta, t.undefined]); +export type MetaOrUndefined = t.TypeOf; + +export const nullableMetaOrUndefined = t.union([metaOrUndefined, t.null]); +export type NullableMetaOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts new file mode 100644 index 000000000000..020f3642306a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/name/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const name = t.string; +export type Name = t.TypeOf; +export const nameOrUndefined = t.union([name, t.undefined]); +export type NameOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts new file mode 100644 index 000000000000..ae16f8b4521c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/namespace_type/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import { DefaultNamespace } from '../default_namespace'; + +export const namespace_type = DefaultNamespace; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts new file mode 100644 index 000000000000..321a57dd4fee --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.test.ts @@ -0,0 +1,130 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { EntriesArray } from '../entries'; +import { nonEmptyEntriesArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchMock } from '../entry_match/index.mock'; +import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; +import { + getEntriesArrayMock, + getListAndNonListEntriesArrayMock, + getListEntriesArrayMock, +} from '../entries/index.mock'; +import { getEntryNestedMock } from '../entry_nested/index.mock'; + +describe('non_empty_entries_array', () => { + test('it should FAIL validation when given an empty array', () => { + const payload: EntriesArray = []; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[]" supplied to "NonEmptyEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when given "undefined"', () => { + const payload = undefined; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "NonEmptyEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when given "null"', () => { + const payload = null; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "null" supplied to "NonEmptyEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate an array of "match" entries', () => { + const payload: EntriesArray = [getEntryMatchMock(), getEntryMatchMock()]; + const decoded = nonEmptyEntriesArray.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 "match_any" entries', () => { + const payload: EntriesArray = [getEntryMatchAnyMock(), getEntryMatchAnyMock()]; + const decoded = nonEmptyEntriesArray.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 "exists" entries', () => { + const payload: EntriesArray = [getEntryExistsMock(), getEntryExistsMock()]; + const decoded = nonEmptyEntriesArray.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 "list" entries', () => { + const payload: EntriesArray = [...getListEntriesArrayMock()]; + const decoded = nonEmptyEntriesArray.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 "nested" entries', () => { + const payload: EntriesArray = [getEntryNestedMock(), getEntryNestedMock()]; + const decoded = nonEmptyEntriesArray.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 entries', () => { + const payload: EntriesArray = [...getEntriesArrayMock()]; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when given an array of entries of value list and non-value list entries', () => { + const payload: EntriesArray = [...getListAndNonListEntriesArrayMock()]; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Cannot have entry of type list and other']); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when given an array of non entries', () => { + const payload = [1]; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "NonEmptyEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.ts new file mode 100644 index 000000000000..8d6812077d4e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_entries_array/index.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { entriesArray, EntriesArray } from '../entries'; +import { entriesList } from '../entries_list'; + +/** + * Types the nonEmptyEntriesArray as: + * - An array of entries of length 1 or greater + * + */ +export const nonEmptyEntriesArray = new t.Type( + 'NonEmptyEntriesArray', + entriesArray.is, + (input, context): Either => { + if (Array.isArray(input) && input.length === 0) { + return t.failure(input, context); + } else { + if ( + Array.isArray(input) && + input.some((entry) => entriesList.is(entry)) && + input.some((entry) => !entriesList.is(entry)) + ) { + // fail when an exception item contains both a value list entry and a non-value list entry + return t.failure(input, context, 'Cannot have entry of type list and other'); + } + return entriesArray.validate(input, context); + } + }, + t.identity +); + +export type NonEmptyEntriesArray = t.OutputOf; +export type NonEmptyEntriesArrayDecoded = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts new file mode 100644 index 000000000000..1d1d659f028c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.test.ts @@ -0,0 +1,115 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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 { EntriesArray } from '../entries'; +import { nonEmptyNestedEntriesArray } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getEntryMatchMock } from '../entry_match/index.mock'; +import { getEntryMatchAnyMock } from '../entry_match_any/index.mock'; +import { getEntryExistsMock } from '../entries_exist/index.mock'; +import { getEntryNestedMock } from '../entry_nested/index.mock'; + +describe('non_empty_nested_entries_array', () => { + test('it should FAIL validation when given an empty array', () => { + const payload: EntriesArray = []; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[]" supplied to "NonEmptyNestedEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when given "undefined"', () => { + const payload = undefined; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "NonEmptyNestedEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should FAIL validation when given "null"', () => { + const payload = null; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "null" supplied to "NonEmptyNestedEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate an array of "match" entries', () => { + const payload: EntriesArray = [getEntryMatchMock(), getEntryMatchMock()]; + const decoded = nonEmptyNestedEntriesArray.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 "match_any" entries', () => { + const payload: EntriesArray = [getEntryMatchAnyMock(), getEntryMatchAnyMock()]; + const decoded = nonEmptyNestedEntriesArray.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 "exists" entries', () => { + const payload: EntriesArray = [getEntryExistsMock(), getEntryExistsMock()]; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when given an array of "nested" entries', () => { + const payload: EntriesArray = [getEntryNestedMock(), getEntryNestedMock()]; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "operator"', + 'Invalid value "nested" supplied to "type"', + 'Invalid value "undefined" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate an array of entries', () => { + const payload: EntriesArray = [ + getEntryExistsMock(), + getEntryMatchAnyMock(), + getEntryMatchMock(), + ]; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should FAIL validation when given an array of non entries', () => { + const payload = [1]; + const decoded = nonEmptyNestedEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "NonEmptyNestedEntriesArray"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.ts new file mode 100644 index 000000000000..eb2d1074b9f4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/non_empty_nested_entries_array/index.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { entriesMatch } from '../entry_match'; +import { entriesMatchAny } from '../entry_match_any'; +import { entriesExists } from '../entries_exist'; + +export const nestedEntryItem = t.union([entriesMatch, entriesMatchAny, entriesExists]); +export const nestedEntriesArray = t.array(nestedEntryItem); +export type NestedEntriesArray = t.TypeOf; + +/** + * Types the nonEmptyNestedEntriesArray as: + * - An array of entries of length 1 or greater + * + */ +export const nonEmptyNestedEntriesArray = new t.Type< + NestedEntriesArray, + NestedEntriesArray, + unknown +>( + 'NonEmptyNestedEntriesArray', + nestedEntriesArray.is, + (input, context): Either => { + if (Array.isArray(input) && input.length === 0) { + return t.failure(input, context); + } else { + return nestedEntriesArray.validate(input, context); + } + }, + t.identity +); + +export type NonEmptyNestedEntriesArray = t.OutputOf; +export type NonEmptyNestedEntriesArrayDecoded = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts new file mode 100644 index 000000000000..3b8ca29afa4e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.test.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { osType, osTypeArrayOrUndefined } from '.'; + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +describe('osType', () => { + test('it will validate a correct osType', () => { + const payload = 'windows'; + const decoded = osType.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 fail to validate an incorrect osType', () => { + const payload = 'foo'; + const decoded = osType.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "foo" supplied to ""linux" | "macos" | "windows""', + ]); + expect(message.schema).toEqual({}); + }); + + test('it will default to an empty array when osTypeArrayOrUndefined is used', () => { + const payload = undefined; + const decoded = osTypeArrayOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_type/index.ts new file mode 100644 index 000000000000..6e8cbb85b631 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/os_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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { DefaultArray } from '@kbn/securitysolution-io-ts-types'; + +export const osType = t.keyof({ + linux: null, + macos: null, + windows: null, +}); +export type OsType = t.TypeOf; + +export const osTypeArray = DefaultArray(osType); +export type OsTypeArray = t.TypeOf; + +export const osTypeArrayOrUndefined = t.union([osTypeArray, t.undefined]); +export type OsTypeArrayOrUndefined = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts new file mode 100644 index 000000000000..36faf8e7e5e2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/page/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const page = t.number; // TODO: Change this out for PositiveNumber from siem +export type Page = t.TypeOf; + +export const pageOrUndefined = t.union([page, t.undefined]); +export type PageOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts new file mode 100644 index 000000000000..669e0699b366 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/per_page/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +export const per_page = t.number; // TODO: Change this out for PositiveNumber from siem +export type PerPage = t.TypeOf; + +export const perPageOrUndefined = t.union([per_page, t.undefined]); +export type PerPageOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts new file mode 100644 index 000000000000..9cafd8ed5ec0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { pitOrUndefined } from '.'; + +import * as t from 'io-ts'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +describe('pitOrUndefined', () => { + test('it will validate a correct pit', () => { + const payload = { id: '123', keepAlive: '1m' }; + const decoded = pitOrUndefined.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 validate with the value of "undefined"', () => { + const obj = t.exact( + t.type({ + pit_id: pitOrUndefined, + }) + ); + const payload: t.TypeOf = { + pit_id: undefined, + }; + const decoded = obj.decode({ + pit_id: undefined, + }); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it will validate a correct pit without having a "keepAlive"', () => { + const payload = { id: '123' }; + const decoded = pitOrUndefined.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 fail to validate an incorrect pit', () => { + const payload = 'foo'; + const decoded = pitOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "foo" supplied to "({| id: string, keepAlive: (string | undefined) |} | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts new file mode 100644 index 000000000000..97b6957e07e5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/pit/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const pitId = t.string; +export const pit = t.exact( + t.type({ + id: pitId, + keepAlive: t.union([t.string, t.undefined]), + }) +); +export const pitOrUndefined = t.union([pit, t.undefined]); + +export type Pit = t.TypeOf; +export type PitId = t.TypeOf; +export type PitOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts new file mode 100644 index 000000000000..d1a7fe34fc70 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/refresh/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const refresh = t.union([t.literal('true'), t.literal('false')]); +export const refreshWithWaitFor = t.union([ + t.literal('true'), + t.literal('false'), + t.literal('wait_for'), +]); +export type Refresh = t.TypeOf; +export type RefreshWithWaitFor = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.ts new file mode 100644 index 000000000000..5854fc42a3a7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/required_keep_undefined/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/** + * This makes any optional property the same as Required would but also has the + * added benefit of keeping your undefined. + * + * For example: + * type A = RequiredKeepUndefined<{ a?: undefined; b: number }>; + * + * will yield a type of: + * type A = { a: undefined; b: number; } + * @deprecated This has no replacement. We should stop using/relying on this and just remove it. + */ +export type RequiredKeepUndefined = { [K in keyof T]-?: [T[K]] } extends infer U + ? U extends Record + ? { [K in keyof U]: U[K][0] } + : never + : never; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.test.ts new file mode 100644 index 000000000000..6c45f50c9c89 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.test.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { searchOrUndefined } from '.'; + +import * as t from 'io-ts'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +describe('search', () => { + test('it will validate a correct search', () => { + const payload = 'name:foo'; + const decoded = searchOrUndefined.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 validate with the value of "undefined"', () => { + const obj = t.exact( + t.type({ + search: searchOrUndefined, + }) + ); + const payload: t.TypeOf = { + search: undefined, + }; + const decoded = obj.decode({ + pit_id: undefined, + }); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it will fail to validate an incorrect search', () => { + const payload = ['foo']; + const decoded = searchOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "["foo"]" supplied to "(string | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts new file mode 100644 index 000000000000..b93c4631cd22 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const search = t.string; +export type Search = t.TypeOf; + +export const searchOrUndefined = t.union([search, t.undefined]); +export type SearchOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.test.ts new file mode 100644 index 000000000000..bc176af4fa30 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.test.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { searchAfterOrUndefined } from '.'; + +import * as t from 'io-ts'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +describe('searchAfter', () => { + test('it will validate a correct search_after', () => { + const payload = ['test-1', 'test-2']; + const decoded = searchAfterOrUndefined.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 validate with the value of "undefined"', () => { + const obj = t.exact( + t.type({ + search_after: searchAfterOrUndefined, + }) + ); + const payload: t.TypeOf = { + search_after: undefined, + }; + const decoded = obj.decode({ + pit_id: undefined, + }); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it will fail to validate an incorrect search_after', () => { + const payload = 'foo'; + const decoded = searchAfterOrUndefined.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "foo" supplied to "(Array | undefined)"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts new file mode 100644 index 000000000000..17735728d341 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/search_after/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +export const search_after = t.array(t.string); +export type SearchAfter = t.TypeOf; + +export const searchAfterOrUndefined = t.union([search_after, t.undefined]); +export type SearchAfterOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts new file mode 100644 index 000000000000..28322ff2e991 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/serializer/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const serializer = t.string; +export type Serializer = t.TypeOf; +export const serializerOrUndefined = t.union([serializer, t.undefined]); +export type SerializerOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts new file mode 100644 index 000000000000..762fdf80c227 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_field/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +export const sort_field = t.string; +export const sortFieldOrUndefined = t.union([sort_field, t.undefined]); +export type SortFieldOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts new file mode 100644 index 000000000000..a849e45c316e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/sort_order/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +export const sort_order = t.keyof({ asc: null, desc: null }); +export const sortOrderOrUndefined = t.union([sort_order, t.undefined]); +export type SortOrderOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts new file mode 100644 index 000000000000..0ad756f05771 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tags/index.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { DefaultStringArray } from '@kbn/securitysolution-io-ts-types'; + +export const tags = DefaultStringArray; +export type Tags = t.TypeOf; +export const tagsOrUndefined = t.union([tags, t.undefined]); +export type TagsOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts new file mode 100644 index 000000000000..362e50089081 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/tie_breaker_id/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const tie_breaker_id = t.string; // TODO: Use UUID for this instead of a string for validation diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts new file mode 100644 index 000000000000..30472bcd101f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/timestamp/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { IsoDateString } from '@kbn/securitysolution-io-ts-types'; + +export const timestamp = IsoDateString; +export const timestampOrUndefined = t.union([IsoDateString, t.undefined]); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts new file mode 100644 index 000000000000..f67ca0f2fc5e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/total/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const total = t.number; // TODO: Change this out for PositiveNumber from siem +export const totalUndefined = t.union([total, t.undefined]); +export type TotalOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts new file mode 100644 index 000000000000..d87ea94728b1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.test.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { Type, type } from '.'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('type', () => { + test('it will work with a given expected type', () => { + const payload: Type = 'keyword'; + const decoded = type.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 give an error if given a type that does not exist', () => { + const payload: Type | 'madeup' = 'madeup'; + const decoded = type.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "madeup" supplied to ""binary" | "boolean" | "byte" | "date" | "date_nanos" | "date_range" | "double" | "double_range" | "float" | "float_range" | "geo_point" | "geo_shape" | "half_float" | "integer" | "integer_range" | "ip" | "ip_range" | "keyword" | "long" | "long_range" | "shape" | "short" | "text""', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts new file mode 100644 index 000000000000..5a1d234d5f2f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/type/index.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +/** + * Types of all the regular single value list items but not exception list + * or exception list types. Those types are in the list_types folder. + */ +export const type = t.keyof({ + binary: null, + boolean: null, + byte: null, + date: null, + date_nanos: null, + date_range: null, + double: null, + double_range: null, + float: null, + float_range: null, + geo_point: null, + geo_shape: null, + half_float: null, + integer: null, + integer_range: null, + ip: null, + ip_range: null, + keyword: null, + long: null, + long_range: null, + shape: null, + short: null, + text: null, +}); + +export const typeOrUndefined = t.union([type, t.undefined]); +export type Type = t.TypeOf; +export type TypeOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/underscore_version/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/underscore_version/index.ts new file mode 100644 index 000000000000..6e47b89af816 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/underscore_version/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const _version = t.string; +export const _versionOrUndefined = t.union([_version, t.undefined]); +export type _VersionOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.ts new file mode 100644 index 000000000000..c0cbfe5e3019 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { UpdateComment, UpdateCommentsArray } from '.'; +import { ID } from '../../constants/index.mock'; + +export const getUpdateCommentMock = (): UpdateComment => ({ + comment: 'some comment', + id: ID, +}); + +export const getUpdateCommentsArrayMock = (): UpdateCommentsArray => [ + getUpdateCommentMock(), + getUpdateCommentMock(), +]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts new file mode 100644 index 000000000000..c1f1be8be9c1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts @@ -0,0 +1,148 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 { getUpdateCommentMock, getUpdateCommentsArrayMock } from './index.mock'; +import { + UpdateComment, + updateComment, + UpdateCommentsArray, + updateCommentsArray, + UpdateCommentsArrayOrUndefined, + updateCommentsArrayOrUndefined, +} from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('UpdateComment', () => { + describe('updateComment', () => { + test('it should pass validation when supplied typical comment update', () => { + const payload = getUpdateCommentMock(); + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an undefined for "comment"', () => { + const payload = getUpdateCommentMock(); + // @ts-expect-error + delete payload.comment; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "comment"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an empty string for "comment"', () => { + const payload = { ...getUpdateCommentMock(), comment: '' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "id"', () => { + const payload = getUpdateCommentMock(); + delete payload.id; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an empty string for "id"', () => { + const payload = { ...getUpdateCommentMock(), id: '' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra key passed in', () => { + const payload: UpdateComment & { + extraKey?: string; + } = { ...getUpdateCommentMock(), extraKey: 'some new value' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getUpdateCommentMock()); + }); + }); + + describe('updateCommentsArray', () => { + test('it should pass validation when supplied an array of comments', () => { + const payload = getUpdateCommentsArrayMock(); + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when undefined', () => { + const payload = undefined; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when array includes non comments types', () => { + const payload = [1] as unknown as UpdateCommentsArray; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('updateCommentsArrayOrUndefined', () => { + test('it should pass validation when supplied an array of comments', () => { + const payload = getUpdateCommentsArrayMock(); + const decoded = updateCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied when undefined', () => { + const payload = undefined; + const decoded = updateCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when array includes non comments types', () => { + const payload = [1] as unknown as UpdateCommentsArrayOrUndefined; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts new file mode 100644 index 000000000000..6a0b4b08c772 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; +import { id } from '../id'; + +export const updateComment = t.intersection([ + t.exact( + t.type({ + comment: NonEmptyString, + }) + ), + t.exact( + t.partial({ + id, + }) + ), +]); + +export type UpdateComment = t.TypeOf; +export const updateCommentsArray = t.array(updateComment); +export type UpdateCommentsArray = t.TypeOf; +export const updateCommentsArrayOrUndefined = t.union([updateCommentsArray, t.undefined]); +export type UpdateCommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts new file mode 100644 index 000000000000..bafbadcd8f09 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_at/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const updated_at = t.string; // TODO: Make this into an ISO Date string check diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts new file mode 100644 index 000000000000..58c5b2d666bd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/updated_by/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; 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'; + +export const updated_by = t.string; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts new file mode 100644 index 000000000000..38530a942275 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/common/value/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const value = t.string; +export const valueOrUndefined = t.union([value, t.undefined]); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts new file mode 100644 index 000000000000..ae91d63d6b7e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/constants/index.mock.ts @@ -0,0 +1,113 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EndpointEntriesArray } from '../common/endpoint/entries'; +import { EntriesArray, Entry } from '../common/entries'; +import { EntryMatch } from '../common/entry_match'; +import { EntryNested } from '../common/entry_nested'; +import { OsTypeArray } from '../common/os_type'; + +export const DATE_NOW = '2020-04-20T15:25:31.830Z'; +export const OLD_DATE_RELATIVE_TO_DATE_NOW = '2020-04-19T15:25:31.830Z'; +export const USER = 'some user'; +export const ELASTIC_USER = 'elastic'; +export const LIST_INDEX = '.lists'; +export const LIST_ITEM_INDEX = '.items'; +export const NAME = 'some name'; +export const DESCRIPTION = 'some description'; +export const LIST_ID = 'some-list-id'; +export const LIST_ITEM_ID = 'some-list-item-id'; +export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; +export const TIE_BREAKERS = [ + '21530991-4051-46ec-bc35-2afa09a1b0b5', + '3c662054-ae37-4aa9-9936-3e8e2ea26775', + '60e49a20-3a23-48b6-8bf9-ed5e3b70f7a0', + '38814080-a40f-4358-992a-3b875f9b7dec', + '29fa61be-aaaf-411c-a78a-7059e3f723f1', + '9c19c959-cb9d-4cd2-99e4-1ea2baf0ef0e', + 'd409308c-f94b-4b3a-8234-bbd7a80c9140', + '87824c99-cd83-45c4-8aa6-4ad95dfea62c', + '7b940c17-9355-479f-b882-f3e575718f79', + '5983ad0c-4ef4-4fa0-8308-80ab9ecc4f74', +]; +export const META = {}; +export const TYPE = 'ip'; +export const VALUE = '127.0.0.1'; +export const VALUE_2 = '255.255.255'; +export const NAMESPACE_TYPE = 'single'; +export const NESTED_FIELD = 'parent.field'; + +// Exception List specific +export const ID = 'uuid_here'; +export const ITEM_ID = 'some-list-item-id'; +export const DETECTION_TYPE = 'detection'; +export const ENDPOINT_TYPE = 'endpoint'; +export const FIELD = 'host.name'; +export const OPERATOR = 'included'; +export const OPERATOR_EXCLUDED = 'excluded'; +export const ENTRY_VALUE = 'some host name'; +export const MATCH = 'match'; +export const MATCH_ANY = 'match_any'; +export const WILDCARD = 'wildcard'; +export const MAX_IMPORT_PAYLOAD_BYTES = 9000000; +export const IMPORT_BUFFER_SIZE = 1000; +export const LIST = 'list'; +export const EXISTS = 'exists'; +export const NESTED = 'nested'; +export const ENTRIES: EntriesArray = [ + { + entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], + field: 'some.parentField', + type: 'nested', + }, + { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, +]; +export const ENDPOINT_ENTRIES: EndpointEntriesArray = [ + { + entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], + field: 'some.parentField', + type: 'nested', + }, + { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, +]; +// ENTRIES_WITH_IDS should only be used to mock out functionality of a collection of transforms +// that are UI specific and useful for UI concerns that are inserted between the +// API and the actual user interface. In some ways these might be viewed as +// technical debt or to compensate for the differences and preferences +// of how ReactJS might prefer data vs. how we want to model data. +export const ENTRIES_WITH_IDS: EntriesArray = [ + { + entries: [ + { + field: 'nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as EntryMatch & { id: string }, + ], + field: 'some.parentField', + id: '123', + type: 'nested', + } as EntryNested & { id: string }, + { + field: 'some.not.nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as Entry & { id: string }, +]; +export const ITEM_TYPE = 'simple'; +export const OS_TYPES: OsTypeArray = ['windows']; +export const TAGS = []; +export const COMMENTS = []; +export const FILTER = 'name:Nicolas Bourbaki'; +export const CURSOR = 'c29tZXN0cmluZ2ZvcnlvdQ=='; +export const _VERSION = 'WzI5NywxXQ=='; +export const VERSION = 1; +export const IMMUTABLE = false; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..0efac9d4de7f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.mock.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { CreateEndpointListItemSchema } from '.'; +import { + COMMENTS, + DESCRIPTION, + ENDPOINT_ENTRIES, + ITEM_TYPE, + META, + NAME, + OS_TYPES, + TAGS, +} from '../../constants/index.mock'; + +export const getCreateEndpointListItemSchemaMock = (): CreateEndpointListItemSchema => ({ + comments: COMMENTS, + description: DESCRIPTION, + entries: ENDPOINT_ENTRIES, + item_id: undefined, + meta: META, + name: NAME, + os_types: OS_TYPES, + tags: TAGS, + type: ITEM_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts new file mode 100644 index 000000000000..78d578dd5d47 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.test.ts @@ -0,0 +1,205 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { getCreateEndpointListItemSchemaMock } from './index.mock'; +import { CreateEndpointListItemSchema, createEndpointListItemSchema } from '.'; +import { getCreateCommentsArrayMock } from '../../common/create_comment/index.mock'; +import { getCommentsMock } from '../../common/comment/index.mock'; +import { CommentsArray } from '../../common/comment'; + +describe('create_endpoint_list_item_schema', () => { + test('it should pass validation when supplied a typical list item request not counting the auto generated uuid', () => { + const payload = getCreateEndpointListItemSchemaMock(); + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an undefined for "description"', () => { + const payload = getCreateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "name"', () => { + const payload = getCreateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "type"', () => { + const payload = getCreateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied a "list_id" since it does not required one', () => { + const inputPayload: CreateEndpointListItemSchema & { list_id: string } = { + ...getCreateEndpointListItemSchemaMock(), + list_id: 'list-123', + }; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied a "namespace_type" since it does not required one', () => { + const inputPayload: CreateEndpointListItemSchema & { namespace_type: string } = { + ...getCreateEndpointListItemSchemaMock(), + namespace_type: 'single', + }; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "namespace_type"']); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { + const payload = getCreateEndpointListItemSchemaMock(); + const outputPayload = getCreateEndpointListItemSchemaMock(); + delete payload.meta; + delete outputPayload.meta; + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { + const inputPayload = getCreateEndpointListItemSchemaMock(); + const outputPayload = getCreateEndpointListItemSchemaMock(); + delete inputPayload.comments; + outputPayload.comments = []; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied "comments" array', () => { + const inputPayload = { + ...getCreateEndpointListItemSchemaMock(), + comments: getCreateCommentsArrayMock(), + }; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(inputPayload); + }); + + test('it should fail validation when supplied "comments" with "created_at", "created_by", or "id" values', () => { + const inputPayload: Omit & { + comments?: CommentsArray; + } = { + ...getCreateEndpointListItemSchemaMock(), + comments: [getCommentsMock()], + }; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "entries"', () => { + const inputPayload = getCreateEndpointListItemSchemaMock(); + const outputPayload = getCreateEndpointListItemSchemaMock(); + // @ts-expect-error + delete inputPayload.entries; + outputPayload.entries = []; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + const inputPayload = getCreateEndpointListItemSchemaMock(); + const outputPayload = getCreateEndpointListItemSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { + const inputPayload = getCreateEndpointListItemSchemaMock(); + delete inputPayload.item_id; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as CreateEndpointListItemSchema).item_id).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 + ); + }); + + test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { + const inputPayload = getCreateEndpointListItemSchemaMock(); + delete inputPayload.item_id; + const decoded = createEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateEndpointListItemSchema).item_id; + expect(message.schema).toEqual(inputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: CreateEndpointListItemSchema & { + extraKey: string; + } = { ...getCreateEndpointListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = createEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts new file mode 100644 index 000000000000..08fd5e339ade --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_endpoint_list_item_schema/index.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; +import { nonEmptyEndpointEntriesArray } from '../../common/endpoint/entries'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { DefaultCreateCommentsArray } from '../../common/default_create_comments_array'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { CreateCommentsArray } from '../../common/create_comment'; +import { Tags, tags } from '../../common/tags'; +import { ItemId } from '../../common/item_id'; +import { EntriesArray } from '../../common/entries'; +import { description } from '../../common/description'; +import { name } from '../../common/name'; +import { meta } from '../../common/meta'; + +export const createEndpointListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEndpointEntriesArray, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode + item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode + meta, // defaults to undefined if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type CreateEndpointListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateEndpointListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'item_id' | 'entries' | 'comments' | 'os_types' +> & { + comments: CreateCommentsArray; + tags: Tags; + item_id: ItemId; + entries: EntriesArray; + os_types: OsTypeArray; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..4ccc82bf2af0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts @@ -0,0 +1,61 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { CreateExceptionListItemSchema } from '.'; +import { + COMMENTS, + DESCRIPTION, + ENTRIES, + ITEM_ID, + ITEM_TYPE, + LIST_ID, + META, + NAME, + NAMESPACE_TYPE, + OS_TYPES, + TAGS, +} from '../../constants/index.mock'; + +export const getCreateExceptionListItemSchemaMock = (): CreateExceptionListItemSchema => ({ + comments: COMMENTS, + description: DESCRIPTION, + entries: ENTRIES, + item_id: undefined, + list_id: LIST_ID, + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: OS_TYPES, + tags: TAGS, + type: ITEM_TYPE, +}); + +/** + * Useful for end to end testing + */ +export const getCreateExceptionListItemMinimalSchemaMock = (): CreateExceptionListItemSchema => ({ + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + list_id: LIST_ID, + name: NAME, + os_types: OS_TYPES, + type: ITEM_TYPE, +}); + +/** + * Useful for end to end testing + */ +export const getCreateExceptionListItemMinimalSchemaMockWithoutId = + (): CreateExceptionListItemSchema => ({ + description: DESCRIPTION, + entries: ENTRIES, + list_id: LIST_ID, + name: NAME, + os_types: OS_TYPES, + type: ITEM_TYPE, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..4d03b83112a3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.test.ts @@ -0,0 +1,209 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getCreateExceptionListItemSchemaMock } from './index.mock'; +import { CreateExceptionListItemSchema, createExceptionListItemSchema } from '.'; +import { getCreateCommentsArrayMock } from '../../common/create_comment/index.mock'; +import { getCommentsMock } from '../../common/comment/index.mock'; +import { CommentsArray } from '../../common/comment'; + +describe('create_exception_list_item_schema', () => { + test('it should pass validation when supplied a typical exception list item request not counting the auto generated uuid', () => { + const payload = getCreateExceptionListItemSchemaMock(); + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an undefined for "description"', () => { + const payload = getCreateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "name"', () => { + const payload = getCreateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "type"', () => { + const payload = getCreateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "list_id"', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + // @ts-expect-error + delete inputPayload.list_id; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { + const payload = getCreateExceptionListItemSchemaMock(); + const outputPayload = getCreateExceptionListItemSchemaMock(); + delete payload.meta; + delete outputPayload.meta; + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + const outputPayload = getCreateExceptionListItemSchemaMock(); + delete inputPayload.comments; + outputPayload.comments = []; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied "comments" array', () => { + const inputPayload = { + ...getCreateExceptionListItemSchemaMock(), + comments: getCreateCommentsArrayMock(), + }; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(inputPayload); + }); + + test('it should fail validation when supplied "comments" with "created_at" or "created_by" values', () => { + const inputPayload: Omit & { + comments?: CommentsArray; + } = { + ...getCreateExceptionListItemSchemaMock(), + comments: [getCommentsMock()], + }; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an undefined for "entries"', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + const outputPayload = getCreateExceptionListItemSchemaMock(); + // @ts-expect-error + delete inputPayload.entries; + outputPayload.entries = []; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "namespace_type" but return enum "single" and generate a correct body not counting the auto generated uuid', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + const outputPayload = getCreateExceptionListItemSchemaMock(); + delete inputPayload.namespace_type; + outputPayload.namespace_type = 'single'; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + const outputPayload = getCreateExceptionListItemSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + delete inputPayload.item_id; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as CreateExceptionListItemSchema).item_id).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 + ); + }); + + test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { + const inputPayload = getCreateExceptionListItemSchemaMock(); + delete inputPayload.item_id; + const decoded = createExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListItemSchema).item_id; + expect(message.schema).toEqual(inputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: CreateExceptionListItemSchema & { + extraKey?: string; + } = getCreateExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..9276a0dafa8b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; + +import { DefaultCreateCommentsArray } from '../../common/default_create_comments_array'; +import { CreateCommentsArray } from '../../common/create_comment'; +import { Tags, tags } from '../../common/tags'; +import { ItemId } from '../../common/item_id'; +import { EntriesArray } from '../../common/entries'; +import { NamespaceType } from '../../common/default_namespace'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { description } from '../../common/description'; +import { list_id } from '../../common/list_id'; +import { name } from '../../common/name'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { meta } from '../../common/meta'; +import { namespace_type } from '../../common/namespace_type'; +import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; +import { ExpireTimeOrUndefined, expireTimeOrUndefined } from '../../common'; + +export const createExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEntriesArray, + list_id, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode + expire_time: expireTimeOrUndefined, + item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type CreateExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' +> & { + comments: CreateCommentsArray; + expire_time: ExpireTimeOrUndefined; + tags: Tags; + item_id: ItemId; + entries: EntriesArray; + namespace_type: NamespaceType; + os_types: OsTypeArray; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..2110a0056f0c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.mock.ts @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + DESCRIPTION, + ENDPOINT_TYPE, + LIST_ID, + META, + NAME, + NAMESPACE_TYPE, + VERSION, +} from '../../constants/index.mock'; + +import { CreateExceptionListSchema } from '.'; + +export const getCreateExceptionListSchemaMock = (): CreateExceptionListSchema => ({ + description: DESCRIPTION, + list_id: undefined, + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: [], + tags: [], + type: ENDPOINT_TYPE, + version: VERSION, +}); + +/** + * Useful for end to end testing + */ +export const getCreateExceptionListMinimalSchemaMock = (): CreateExceptionListSchema => ({ + description: DESCRIPTION, + list_id: LIST_ID, + name: NAME, + type: ENDPOINT_TYPE, +}); + +/** + * Useful for end to end testing + */ +export const getCreateExceptionListMinimalSchemaMockWithoutId = (): CreateExceptionListSchema => ({ + description: DESCRIPTION, + name: NAME, + type: ENDPOINT_TYPE, +}); + +/** + * Useful for end to end testing with detections + */ +export const getCreateExceptionListDetectionSchemaMock = (): CreateExceptionListSchema => ({ + description: DESCRIPTION, + list_id: LIST_ID, + name: NAME, + type: 'detection', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..26399804591e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { CreateExceptionListSchema, createExceptionListSchema } from '.'; +import { getCreateExceptionListSchemaMock } from './index.mock'; + +describe('create_exception_list_schema', () => { + test('it should validate a typical exception lists request and generate a correct body not counting the uuid', () => { + const payload = getCreateExceptionListSchemaMock(); + const decoded = createExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListSchema).list_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "meta" and generate a correct body not counting the uuid', () => { + const payload = getCreateExceptionListSchemaMock(); + delete payload.meta; + const decoded = createExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListSchema).list_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "tags" but return an array and generate a correct body not counting the uuid', () => { + const inputPayload = getCreateExceptionListSchemaMock(); + const outputPayload = getCreateExceptionListSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = createExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListSchema).list_id; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "list_id" and auto generate a uuid', () => { + const inputPayload = getCreateExceptionListSchemaMock(); + delete inputPayload.list_id; + const decoded = createExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as CreateExceptionListSchema).list_id).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 + ); + }); + + test('it should accept an undefined for "list_id" and generate a correct body not counting the uuid', () => { + const inputPayload = getCreateExceptionListSchemaMock(); + delete inputPayload.list_id; + const decoded = createExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as CreateExceptionListSchema).list_id; + expect(message.schema).toEqual(inputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: CreateExceptionListSchema & { + extraKey?: string; + } = getCreateExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.ts new file mode 100644 index 000000000000..000b4c65a01f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_schema/index.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { + DefaultUuid, + DefaultVersionNumber, + DefaultVersionNumberDecoded, +} from '@kbn/securitysolution-io-ts-types'; + +import { exceptionListType } from '../../common/exception_list'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { Tags, tags } from '../../common/tags'; +import { ListId } from '../../common/list_id'; +import { NamespaceType } from '../../common/default_namespace'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; +import { namespace_type } from '../../common/namespace_type'; +import { meta } from '../../common/meta'; + +export const createExceptionListSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type: exceptionListType, + }) + ), + t.exact( + t.partial({ + list_id: DefaultUuid, // defaults to a GUID (UUID v4) string if not set during decode + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + version: DefaultVersionNumber, // defaults to numerical 1 if not set during decode + }) + ), +]); + +export type CreateExceptionListSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'list_id' | 'namespace_type' | 'os_types' +> & { + tags: Tags; + list_id: ListId; + namespace_type: NamespaceType; + os_types: OsTypeArray; + version: DefaultVersionNumberDecoded; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..03085b3cfa8e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.mock.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID, LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; + +import { CreateListItemSchema } from '.'; + +export const getCreateListItemSchemaMock = (): CreateListItemSchema => ({ + id: LIST_ITEM_ID, + list_id: LIST_ID, + meta: META, + value: VALUE, +}); + +/** + * Useful for end to end testing + */ +export const getCreateMinimalListItemSchemaMock = (): CreateListItemSchema => ({ + id: LIST_ITEM_ID, + list_id: LIST_ID, + value: VALUE, +}); + +/** + * Useful for end to end testing + */ +export const getCreateMinimalListItemSchemaMockWithoutId = (): CreateListItemSchema => ({ + list_id: LIST_ID, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts new file mode 100644 index 000000000000..509cbdbf0465 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.test.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getCreateListItemSchemaMock } from './index.mock'; +import { CreateListItemSchema, createListItemSchema } from '.'; + +describe('create_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getCreateListItemSchemaMock(); + const decoded = createListItemSchema.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 accept an undefined for an id', () => { + const payload = getCreateListItemSchemaMock(); + delete payload.id; + const decoded = createListItemSchema.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 accept an undefined for meta', () => { + const payload = getCreateListItemSchemaMock(); + delete payload.meta; + const decoded = createListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: CreateListItemSchema & { extraKey?: string } = getCreateListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.ts new file mode 100644 index 000000000000..d18e7930c3ee --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_item_schema/index.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { list_id } from '../../common/list_id'; +import { value } from '../../common/value'; +import { id } from '../../common/id'; +import { meta } from '../../common/meta'; +import { refreshWithWaitFor } from '../../common/refresh'; + +export const createListItemSchema = t.intersection([ + t.exact( + t.type({ + list_id, + value, + }) + ), + t.exact(t.partial({ id, meta, refresh: refreshWithWaitFor })), +]); + +export type CreateListItemSchema = t.OutputOf; +export type CreateListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.ts new file mode 100644 index 000000000000..aa4f45d74f4a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.mock.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DESCRIPTION, LIST_ID, META, NAME, TYPE, VERSION } from '../../constants/index.mock'; + +import { CreateListSchema } from '.'; + +export const getCreateListSchemaMock = (): CreateListSchema => ({ + description: DESCRIPTION, + deserializer: undefined, + id: LIST_ID, + meta: META, + name: NAME, + serializer: undefined, + type: TYPE, + version: VERSION, +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + */ +export const getCreateMinimalListSchemaMock = (): CreateListSchema => ({ + description: DESCRIPTION, + id: LIST_ID, + name: NAME, + type: TYPE, +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + */ +export const getCreateMinimalListSchemaMockWithoutId = (): CreateListSchema => ({ + description: DESCRIPTION, + name: NAME, + type: TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.test.ts new file mode 100644 index 000000000000..a6043addd72a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.test.ts @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { CreateListSchema, createListSchema } from '.'; +import { getCreateListSchemaMock } from './index.mock'; + +describe('create_list_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getCreateListSchemaMock(); + const decoded = createListSchema.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 accept an undefined for an id', () => { + const payload = getCreateListSchemaMock(); + delete payload.id; + const decoded = createListSchema.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 accept an undefined for meta', () => { + const payload = getCreateListSchemaMock(); + delete payload.meta; + const decoded = createListSchema.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 accept an undefined for serializer', () => { + const payload = getCreateListSchemaMock(); + delete payload.serializer; + const decoded = createListSchema.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 accept an undefined for deserializer', () => { + const payload = getCreateListSchemaMock(); + delete payload.deserializer; + const decoded = createListSchema.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 not allow an extra key to be sent in', () => { + const payload: CreateListSchema & { extraKey?: string } = getCreateListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts new file mode 100644 index 000000000000..fd771d40a501 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_list_schema/index.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { + DefaultVersionNumber, + DefaultVersionNumberDecoded, +} from '@kbn/securitysolution-io-ts-types'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; +import { type } from '../../common/type'; +import { deserializer } from '../../common/deserializer'; +import { id } from '../../common/id'; +import { meta } from '../../common/meta'; +import { serializer } from '../../common/serializer'; + +export const createListSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type, + }) + ), + t.exact( + t.partial({ + deserializer, // defaults to undefined if not set during decode + id, // defaults to undefined if not set during decode + meta, // defaults to undefined if not set during decode + serializer, // defaults to undefined if not set during decode + version: DefaultVersionNumber, // defaults to a numerical 1 if not set during decode + }) + ), +]); + +export type CreateListSchema = t.OutputOf; +export type CreateListSchemaDecoded = RequiredKeepUndefined< + Omit, 'version'> +> & { version: DefaultVersionNumberDecoded }; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts new file mode 100644 index 000000000000..bd95fdd0e086 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.test.ts @@ -0,0 +1,125 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { CreateRuleExceptionListItemSchema, createRuleExceptionListItemSchema } from '.'; +import { CreateExceptionListItemSchema } from '../create_exception_list_item_schema'; + +const getCreateExceptionListItemSchemaMock = (): CreateExceptionListItemSchema => ({ + comments: [], + description: 'some description', + entries: [ + { + field: 'host.name', + operator: 'included', + type: 'match_any', + value: ['foo', 'bar'], + }, + ], + item_id: undefined, + list_id: 'some-list-id', + name: 'some name', + namespace_type: 'single', + os_types: [], + tags: [], + type: 'simple', +}); + +describe('createRuleExceptionListItemSchema', () => { + test('empty objects do not validate', () => { + const payload = {} as CreateRuleExceptionListItemSchema; + + const decoded = createRuleExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "entries"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('items without list_id validate', () => { + const payload: CreateRuleExceptionListItemSchema = { + description: 'Exception item for rule default exception list', + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + name: 'Sample exception item', + type: 'simple', + }; + + const decoded = createRuleExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual( + expect.objectContaining({ + comments: [], + description: 'Exception item for rule default exception list', + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + name: 'Sample exception item', + os_types: [], + tags: [], + type: 'simple', + }) + ); + }); + + test('items with list_id do not validate', () => { + const payload = + getCreateExceptionListItemSchemaMock() as unknown as CreateRuleExceptionListItemSchema; + + const decoded = createRuleExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some-list-id" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('made up parameters do not validate', () => { + const payload: Partial & { madeUp: string } = { + description: 'Exception item for rule default exception list', + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + name: 'Sample exception item', + type: 'simple', + madeUp: 'invalid value', + }; + + const decoded = createRuleExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts new file mode 100644 index 000000000000..ef0446d9207a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/create_rule_exception_item_schema/index.ts @@ -0,0 +1,71 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; + +import { + CreateCommentsArray, + DefaultCreateCommentsArray, + description, + EntriesArray, + exceptionListItemType, + ItemId, + meta, + NamespaceType, + namespaceType, + nonEmptyEntriesArray, + OsTypeArray, + osTypeArrayOrUndefined, + Tags, + tags, + name, + ExpireTimeOrUndefined, + expireTimeOrUndefined, +} from '../../common'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; + +export const createRuleExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEntriesArray, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode + item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode + list_id: t.undefined, + meta, // defaults to undefined if not set during decode + namespace_type: namespaceType, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + expire_time: expireTimeOrUndefined, + }) + ), +]); + +export type CreateRuleExceptionListItemSchema = t.OutputOf< + typeof createRuleExceptionListItemSchema +>; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateRuleExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' +> & { + comments: CreateCommentsArray; + tags: Tags; + item_id: ItemId; + entries: EntriesArray; + namespace_type: NamespaceType; + os_types: OsTypeArray; + expire_time: ExpireTimeOrUndefined; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..2547180e114f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID } from '../../constants/index.mock'; + +import { DeleteEndpointListItemSchema } from '.'; + +export const getDeleteEndpointListItemSchemaMock = (): DeleteEndpointListItemSchema => ({ + id: ID, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.test.ts new file mode 100644 index 000000000000..09697db0c5f4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.test.ts @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DeleteEndpointListItemSchema, deleteEndpointListItemSchema } from '.'; +import { getDeleteEndpointListItemSchemaMock } from './index.mock'; + +describe('delete_endpoint_list_item_schema', () => { + test('it should validate a typical endpoint list item request', () => { + const payload = getDeleteEndpointListItemSchemaMock(); + const decoded = deleteEndpointListItemSchema.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 NOT accept a value for "namespace_type" since it does not require one', () => { + const payload: DeleteEndpointListItemSchema & { + namespace_type: string; + } = { ...getDeleteEndpointListItemSchemaMock(), namespace_type: 'single' }; + // @ts-expect-error + delete payload.namespace_type; + const decoded = deleteEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getDeleteEndpointListItemSchemaMock()); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: DeleteEndpointListItemSchema & { + extraKey?: string; + } = { ...getDeleteEndpointListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = deleteEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.ts new file mode 100644 index 000000000000..9825b7414238 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_endpoint_list_item_schema/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { id } from '../../common/id'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { item_id } from '../../common/item_id'; + +export const deleteEndpointListItemSchema = t.exact( + t.partial({ + id, + item_id, + }) +); + +export type DeleteEndpointListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type DeleteEndpointListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..98404e189beb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.mock.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { DeleteExceptionListItemSchema } from '.'; + +export const getDeleteExceptionListItemSchemaMock = (): DeleteExceptionListItemSchema => ({ + id: ID, + namespace_type: NAMESPACE_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..7131a969a795 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.test.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DeleteExceptionListItemSchema, deleteExceptionListItemSchema } from '.'; +import { getDeleteExceptionListItemSchemaMock } from './index.mock'; + +describe('delete_exception_list_item_schema', () => { + test('it should validate a typical exception list item request', () => { + const payload = getDeleteExceptionListItemSchemaMock(); + const decoded = deleteExceptionListItemSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { + const payload = getDeleteExceptionListItemSchemaMock(); + delete payload.namespace_type; + const decoded = deleteExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getDeleteExceptionListItemSchemaMock()); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: DeleteExceptionListItemSchema & { + extraKey?: string; + } = getDeleteExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = deleteExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..02bcd800712e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_item_schema/index.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NamespaceType } from '../../common/default_namespace'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { item_id } from '../../common/item_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const deleteExceptionListItemSchema = t.exact( + t.partial({ + id, + item_id, + namespace_type, // defaults to 'single' if not set during decode + }) +); + +export type DeleteExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type DeleteExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceType; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..7eca83a9d713 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.mock.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { DeleteExceptionListSchema } from '.'; + +export const getDeleteExceptionListSchemaMock = (): DeleteExceptionListSchema => ({ + id: ID, + namespace_type: NAMESPACE_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..a439ac040322 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.test.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DeleteExceptionListSchema, deleteExceptionListSchema } from '.'; +import { getDeleteExceptionListSchemaMock } from './index.mock'; + +describe('delete_exception_list_schema', () => { + test('it should validate a typical exception list request', () => { + const payload = getDeleteExceptionListSchemaMock(); + const decoded = deleteExceptionListSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { + const payload = getDeleteExceptionListSchemaMock(); + delete payload.namespace_type; + const decoded = deleteExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getDeleteExceptionListSchemaMock()); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: DeleteExceptionListSchema & { + extraKey?: string; + } = getDeleteExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = deleteExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.ts new file mode 100644 index 000000000000..1c04c0fdc17a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_exception_list_schema/index.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NamespaceType } from '../../common/default_namespace'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const deleteExceptionListSchema = t.exact( + t.partial({ + id, + list_id, + namespace_type, // defaults to 'single' if not set during decode + }) +); + +export type DeleteExceptionListSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type DeleteExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceType; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..ef4ff721119a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, LIST_ID, VALUE } from '../../constants/index.mock'; + +import { DeleteListItemSchema } from '.'; + +export const getDeleteListItemSchemaMock = (): DeleteListItemSchema => ({ + id: ID, + list_id: LIST_ID, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.ts new file mode 100644 index 000000000000..07db295d3ef2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.test.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DeleteListItemSchema, deleteListItemSchema } from '.'; +import { getDeleteListItemSchemaMock } from './index.mock'; + +describe('delete_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getDeleteListItemSchemaMock(); + const decoded = deleteListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: DeleteListItemSchema & { + extraKey?: string; + } = { ...getDeleteListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = deleteListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.ts new file mode 100644 index 000000000000..4b9ef6763014 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_item_schema/index.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { valueOrUndefined } from '../../common/value'; +import { refresh } from '../../common/refresh'; + +export const deleteListItemSchema = t.intersection([ + t.exact( + t.type({ + value: valueOrUndefined, + }) + ), + t.exact(t.partial({ id, list_id, refresh })), +]); + +export type DeleteListItemSchema = t.OutputOf; +export type DeleteListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts new file mode 100644 index 000000000000..19b7a2aa15b9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID } from '../../constants/index.mock'; + +import { DeleteListSchema } from '.'; + +export const getDeleteListSchemaMock = (): DeleteListSchema => ({ + deleteReferences: false, + id: LIST_ID, + ignoreReferences: true, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts new file mode 100644 index 000000000000..5077c0795df3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.test.ts @@ -0,0 +1,46 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DeleteListSchema, deleteListSchema } from '.'; +import { getDeleteListSchemaMock } from './index.mock'; + +describe('delete_list_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getDeleteListSchemaMock(); + const decoded = deleteListSchema.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 NOT accept an undefined for an id', () => { + const payload = getDeleteListSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = deleteListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: DeleteListSchema & { extraKey?: string } = getDeleteListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = deleteListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts new file mode 100644 index 000000000000..da1d252d9e36 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/delete_list_schema/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { DefaultStringBooleanFalse } from '@kbn/securitysolution-io-ts-types'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; + +export const deleteListSchema = t.intersection([ + t.exact( + t.type({ + id, + }) + ), + t.exact( + t.partial({ + deleteReferences: DefaultStringBooleanFalse, + ignoreReferences: DefaultStringBooleanFalse, + }) + ), +]); + +export type DeleteListSchema = RequiredKeepUndefined>; +export type DeleteListSchemaEncoded = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts new file mode 100644 index 000000000000..d3f9b59d5cf0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { DuplicateExceptionListQuerySchema } from '.'; + +export const getDuplicateExceptionListQuerySchemaMock = (): DuplicateExceptionListQuerySchema => ({ + list_id: LIST_ID, + namespace_type: NAMESPACE_TYPE, + include_expired_exceptions: 'true', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts new file mode 100644 index 000000000000..73762793e3d2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.test.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { DuplicateExceptionListQuerySchema, duplicateExceptionListQuerySchema } from '.'; +import { getDuplicateExceptionListQuerySchemaMock } from './index.mock'; + +describe('duplicate_exceptionList_query_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getDuplicateExceptionListQuerySchemaMock(); + const decoded = duplicateExceptionListQuerySchema.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 default namespace_type to "single" if an undefined given for namespacetype', () => { + const payload = getDuplicateExceptionListQuerySchemaMock(); + delete payload.namespace_type; + const decoded = duplicateExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(message.schema).toEqual({ + include_expired_exceptions: 'true', + list_id: 'some-list-id', + namespace_type: 'single', + }); + }); + + test('it should NOT accept an undefined for an list_id', () => { + const payload = getDuplicateExceptionListQuerySchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = duplicateExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: DuplicateExceptionListQuerySchema & { + extraKey?: string; + } = getDuplicateExceptionListQuerySchemaMock(); + payload.extraKey = 'some new value'; + const decoded = duplicateExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.ts new file mode 100644 index 000000000000..2a90eb4aeb05 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/duplicate_exception_list_query_schema/index.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { NamespaceType } from '../../common'; + +import { includeExpiredExceptionsOrUndefined } from '../../common/include_expired_exceptions'; +import { list_id } from '../../common/list_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const duplicateExceptionListQuerySchema = t.exact( + t.type({ + list_id, + namespace_type, + include_expired_exceptions: includeExpiredExceptionsOrUndefined, + }) +); + +export type DuplicateExceptionListQuerySchema = t.OutputOf< + typeof duplicateExceptionListQuerySchema +>; + +// This type is used after a decode since some things are defaults after a decode. +export type DuplicateExceptionListQuerySchemaDecoded = Omit< + t.TypeOf, + 'namespace_type' +> & { + namespace_type: NamespaceType; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts new file mode 100644 index 000000000000..2b1d6a439064 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { ExportExceptionListQuerySchema } from '.'; + +export const getExportExceptionListQuerySchemaMock = (): ExportExceptionListQuerySchema => ({ + id: ID, + list_id: LIST_ID, + namespace_type: NAMESPACE_TYPE, + include_expired_exceptions: 'true', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts new file mode 100644 index 000000000000..dea087dca36d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.test.ts @@ -0,0 +1,78 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { ExportExceptionListQuerySchema, exportExceptionListQuerySchema } from '.'; +import { getExportExceptionListQuerySchemaMock } from './index.mock'; + +describe('export_exception_list_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getExportExceptionListQuerySchemaMock(); + const decoded = exportExceptionListQuerySchema.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 NOT accept an undefined for an id', () => { + const payload = getExportExceptionListQuerySchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = exportExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should default namespace_type to "single" if an undefined given for namespacetype', () => { + const payload = getExportExceptionListQuerySchemaMock(); + delete payload.namespace_type; + const decoded = exportExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(message.schema).toEqual({ + id: 'uuid_here', + include_expired_exceptions: 'true', + list_id: 'some-list-id', + namespace_type: 'single', + }); + }); + + test('it should NOT accept an undefined for an list_id', () => { + const payload = getExportExceptionListQuerySchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = exportExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ExportExceptionListQuerySchema & { + extraKey?: string; + } = getExportExceptionListQuerySchemaMock(); + payload.extraKey = 'some new value'; + const decoded = exportExceptionListQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.ts new file mode 100644 index 000000000000..8967e45c5a61 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_exception_list_query_schema/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { id } from '../../common/id'; +import { includeExpiredExceptionsOrUndefined } from '../../common/include_expired_exceptions'; +import { list_id } from '../../common/list_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const exportExceptionListQuerySchema = t.exact( + t.type({ + id, + list_id, + namespace_type, + include_expired_exceptions: includeExpiredExceptionsOrUndefined, + // TODO: Add file_name here with a default value + }) +); + +export type ExportExceptionListQuerySchema = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts new file mode 100644 index 000000000000..85076f592d16 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID } from '../../constants/index.mock'; + +import { ExportListItemQuerySchema } from '.'; + +export const getExportListItemQuerySchemaMock = (): ExportListItemQuerySchema => ({ + list_id: LIST_ID, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts new file mode 100644 index 000000000000..f05e530cbb41 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { ExportListItemQuerySchema, exportListItemQuerySchema } from '.'; +import { getExportListItemQuerySchemaMock } from './index.mock'; + +describe('export_list_item_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getExportListItemQuerySchemaMock(); + const decoded = exportListItemQuerySchema.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 NOT accept an undefined for an id', () => { + const payload = getExportListItemQuerySchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = exportListItemQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ExportListItemQuerySchema & { + extraKey?: string; + } = getExportListItemQuerySchemaMock(); + payload.extraKey = 'some new value'; + const decoded = exportListItemQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.ts new file mode 100644 index 000000000000..a07e6c73434e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/export_list_item_query_schema/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { list_id } from '../../common/list_id'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; + +export const exportListItemQuerySchema = t.exact( + t.type({ + list_id, + // TODO: Add file_name here with a default value + }) +); + +export type ExportListItemQuerySchema = RequiredKeepUndefined< + t.TypeOf +>; +export type ExportListItemQuerySchemaEncoded = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..5df0322cc803 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.mock.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FILTER } from '../../constants/index.mock'; + +import { FindEndpointListItemSchema, FindEndpointListItemSchemaDecoded } from '.'; + +export const getFindEndpointListItemSchemaMock = (): FindEndpointListItemSchema => ({ + filter: FILTER, + page: '1', + per_page: '25', + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindEndpointListItemSchemaDecodedMock = (): FindEndpointListItemSchemaDecoded => ({ + filter: FILTER, + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts new file mode 100644 index 000000000000..1ce9618781c4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.test.ts @@ -0,0 +1,107 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { + getFindEndpointListItemSchemaDecodedMock, + getFindEndpointListItemSchemaMock, +} from './index.mock'; +import { FindEndpointListItemSchema, findEndpointListItemSchema } from '.'; + +describe('find_endpoint_list_item_schema', () => { + test('it should validate a typical find item request', () => { + const payload = getFindEndpointListItemSchemaMock(); + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindEndpointListItemSchemaDecodedMock()); + }); + + test('it should validate and empty object since everything is optional and has defaults', () => { + const payload: FindEndpointListItemSchema = {}; + const decoded = findEndpointListItemSchema.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 validate with page missing', () => { + const payload = getFindEndpointListItemSchemaMock(); + delete payload.page; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindEndpointListItemSchemaDecodedMock(); + delete expected.page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with pre_page missing', () => { + const payload = getFindEndpointListItemSchemaMock(); + delete payload.per_page; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindEndpointListItemSchemaDecodedMock(); + delete expected.per_page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with filter missing', () => { + const payload = getFindEndpointListItemSchemaMock(); + delete payload.filter; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindEndpointListItemSchemaDecodedMock(); + delete expected.filter; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_field missing', () => { + const payload = getFindEndpointListItemSchemaMock(); + delete payload.sort_field; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindEndpointListItemSchemaDecodedMock(); + delete expected.sort_field; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_order missing', () => { + const payload = getFindEndpointListItemSchemaMock(); + delete payload.sort_order; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindEndpointListItemSchemaDecodedMock(); + delete expected.sort_order; + expect(message.schema).toEqual(expected); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FindEndpointListItemSchema & { + extraKey: string; + } = { ...getFindEndpointListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = findEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.ts new file mode 100644 index 000000000000..05f32f452f5d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_endpoint_list_item_schema/index.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { filter } from '../../common/filter'; +import { sort_field } from '../../common/sort_field'; +import { sort_order } from '../../common/sort_order'; + +export const findEndpointListItemSchema = t.exact( + t.partial({ + filter, // defaults to undefined if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) +); + +export type FindEndpointListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindEndpointListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..16b2ee7a8a37 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FILTER, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { FindExceptionListItemSchema, FindExceptionListItemSchemaDecoded } from '.'; + +export const getFindExceptionListItemSchemaMock = (): FindExceptionListItemSchema => ({ + filter: FILTER, + list_id: LIST_ID, + namespace_type: NAMESPACE_TYPE, + page: '1', + per_page: '25', + search: undefined, + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindExceptionListItemSchemaMultipleMock = (): FindExceptionListItemSchema => ({ + filter: 'name:Sofia Kovalevskaya,name:Hypatia,name:Sophie Germain', + list_id: 'list-1,list-2,list-3', + namespace_type: 'single,single,agnostic', + page: '1', + per_page: '25', + search: undefined, + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindExceptionListItemSchemaDecodedMock = + (): FindExceptionListItemSchemaDecoded => ({ + filter: [FILTER], + list_id: [LIST_ID], + namespace_type: [NAMESPACE_TYPE], + page: 1, + per_page: 25, + search: undefined, + sort_field: undefined, + sort_order: undefined, + }); + +export const getFindExceptionListItemSchemaDecodedMultipleMock = + (): FindExceptionListItemSchemaDecoded => ({ + filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'], + list_id: ['list-1', 'list-2', 'list-3'], + namespace_type: ['single', 'single', 'agnostic'], + page: 1, + per_page: 25, + search: undefined, + sort_field: undefined, + sort_order: undefined, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..1d6696933321 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.test.ts @@ -0,0 +1,148 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { LIST_ID } from '../../constants/index.mock'; + +import { + getFindExceptionListItemSchemaDecodedMock, + getFindExceptionListItemSchemaDecodedMultipleMock, + getFindExceptionListItemSchemaMock, + getFindExceptionListItemSchemaMultipleMock, +} from './index.mock'; +import { + FindExceptionListItemSchema, + FindExceptionListItemSchemaDecoded, + findExceptionListItemSchema, +} from '.'; + +describe('find_list_item_schema', () => { + test('it should validate a typical find item request', () => { + const payload = getFindExceptionListItemSchemaMock(); + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindExceptionListItemSchemaDecodedMock()); + }); + + test('it should validate a typical find item request with multiple input strings turned into array elements', () => { + const payload = getFindExceptionListItemSchemaMultipleMock(); + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindExceptionListItemSchemaDecodedMultipleMock()); + }); + + test('it should validate just a list_id where it decodes into an array for list_id and adds a namespace_type of "single" as an array', () => { + const payload: FindExceptionListItemSchema = { list_id: LIST_ID }; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: FindExceptionListItemSchemaDecoded = { + filter: [], + list_id: [LIST_ID], + namespace_type: ['single'], + page: undefined, + per_page: undefined, + search: undefined, + sort_field: undefined, + sort_order: undefined, + }; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with page missing', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.page; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListItemSchemaDecodedMock(); + delete expected.page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with per_page missing', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.per_page; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListItemSchemaDecodedMock(); + delete expected.per_page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with filter missing and add filter as an empty array', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.filter; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: FindExceptionListItemSchemaDecoded = { + ...getFindExceptionListItemSchemaDecodedMock(), + filter: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_field missing', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.sort_field; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListItemSchemaDecodedMock(); + delete expected.sort_field; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_order missing', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.sort_order; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListItemSchemaDecodedMock(); + delete expected.sort_order; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with search missing', () => { + const payload = getFindExceptionListItemSchemaMock(); + delete payload.search; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListItemSchemaDecodedMock(); + delete expected.search; + expect(message.schema).toEqual(expected); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FindExceptionListItemSchema & { + extraKey: string; + } = { ...getFindExceptionListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = findExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..7177a7144c7f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { + EmptyStringArray, + EmptyStringArrayDecoded, + NonEmptyStringArray, + StringToPositiveNumber, +} from '@kbn/securitysolution-io-ts-types'; + +import { + DefaultNamespaceArray, + DefaultNamespaceArrayTypeDecoded, +} from '../../common/default_namespace_array'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { sort_field } from '../../common/sort_field'; +import { sort_order } from '../../common/sort_order'; +import { search } from '../../common/search'; + +export const findExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + list_id: NonEmptyStringArray, + }) + ), + t.exact( + t.partial({ + filter: EmptyStringArray, // defaults to an empty array [] if not set during decode + namespace_type: DefaultNamespaceArray, // defaults to ['single'] if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + search, + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) + ), +]); + +export type FindExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' | 'filter' +> & { + filter: EmptyStringArrayDecoded; + namespace_type: DefaultNamespaceArrayTypeDecoded; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..f963c6650cf2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FILTER, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { FindExceptionListSchema, FindExceptionListSchemaDecoded } from '.'; + +export const getFindExceptionListSchemaMock = (): FindExceptionListSchema => ({ + filter: FILTER, + namespace_type: NAMESPACE_TYPE, + page: '1', + per_page: '25', + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindExceptionListSchemaDecodedMock = (): FindExceptionListSchemaDecoded => ({ + filter: FILTER, + namespace_type: [NAMESPACE_TYPE], + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..8669a3657f02 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.test.ts @@ -0,0 +1,119 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { + getFindExceptionListSchemaDecodedMock, + getFindExceptionListSchemaMock, +} from './index.mock'; +import { + FindExceptionListSchema, + FindExceptionListSchemaDecoded, + findExceptionListSchema, +} from '.'; + +describe('find_exception_list_schema', () => { + test('it should validate a typical find item request', () => { + const payload = getFindExceptionListSchemaMock(); + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindExceptionListSchemaDecodedMock()); + }); + + test('it should validate and empty object since everything is optional and will respond only with namespace_type filled out to be "single"', () => { + const payload: FindExceptionListSchema = {}; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: FindExceptionListSchemaDecoded = { + filter: undefined, + namespace_type: ['single'], + page: undefined, + per_page: undefined, + sort_field: undefined, + sort_order: undefined, + }; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with page missing', () => { + const payload = getFindExceptionListSchemaMock(); + delete payload.page; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListSchemaDecodedMock(); + delete expected.page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with pre_page missing', () => { + const payload = getFindExceptionListSchemaMock(); + delete payload.per_page; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListSchemaDecodedMock(); + delete expected.per_page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with filter missing', () => { + const payload = getFindExceptionListSchemaMock(); + delete payload.filter; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListSchemaDecodedMock(); + delete expected.filter; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_field missing', () => { + const payload = getFindExceptionListSchemaMock(); + delete payload.sort_field; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListSchemaDecodedMock(); + delete expected.sort_field; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_order missing', () => { + const payload = getFindExceptionListSchemaMock(); + delete payload.sort_order; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindExceptionListSchemaDecodedMock(); + delete expected.sort_order; + expect(message.schema).toEqual(expected); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FindExceptionListSchema & { + extraKey: string; + } = { ...getFindExceptionListSchemaMock(), extraKey: 'some new value' }; + const decoded = findExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.ts new file mode 100644 index 000000000000..dc9acdefd7a9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_schema/index.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; + +import { DefaultNamespaceArray, NamespaceTypeArray } from '../../common/default_namespace_array'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { filter } from '../../common/filter'; +import { sort_field } from '../../common/sort_field'; +import { sort_order } from '../../common/sort_order'; + +export const findExceptionListSchema = t.exact( + t.partial({ + filter, // defaults to undefined if not set during decode + namespace_type: DefaultNamespaceArray, // defaults to 'single' if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) +); + +export type FindExceptionListSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceTypeArray; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..44c952a9a382 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.mock.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { CURSOR, FILTER, LIST_ID } from '../../constants/index.mock'; + +import { FindListItemSchema, FindListItemSchemaDecoded } from '.'; + +export const getFindListItemSchemaMock = (): FindListItemSchema => ({ + cursor: CURSOR, + filter: FILTER, + list_id: LIST_ID, + page: '1', + per_page: '25', + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindListItemSchemaDecodedMock = (): FindListItemSchemaDecoded => ({ + cursor: CURSOR, + filter: FILTER, + list_id: LIST_ID, + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts new file mode 100644 index 000000000000..589a40f641c6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.test.ts @@ -0,0 +1,103 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { LIST_ID } from '../../constants/index.mock'; + +import { FindListItemSchema, FindListItemSchemaDecoded, findListItemSchema } from '.'; +import { getFindListItemSchemaDecodedMock, getFindListItemSchemaMock } from './index.mock'; + +describe('find_list_item_schema', () => { + test('it should validate a typical find item request', () => { + const payload = getFindListItemSchemaMock(); + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindListItemSchemaDecodedMock()); + }); + + test('it should validate just a list_id where it decodes into an array for list_id and adds a namespace_type of "single"', () => { + const payload: FindListItemSchema = { list_id: LIST_ID }; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: FindListItemSchemaDecoded = { + cursor: undefined, + filter: undefined, + list_id: LIST_ID, + page: undefined, + per_page: undefined, + sort_field: undefined, + sort_order: undefined, + }; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with page missing', () => { + const payload = getFindListItemSchemaMock(); + delete payload.page; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListItemSchemaDecodedMock(); + delete expected.page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with pre_page missing', () => { + const payload = getFindListItemSchemaMock(); + delete payload.per_page; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListItemSchemaDecodedMock(); + delete expected.per_page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_field missing', () => { + const payload = getFindListItemSchemaMock(); + delete payload.sort_field; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListItemSchemaDecodedMock(); + delete expected.sort_field; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_order missing', () => { + const payload = getFindListItemSchemaMock(); + delete payload.sort_order; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListItemSchemaDecodedMock(); + delete expected.sort_order; + expect(message.schema).toEqual(expected); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FindListItemSchema & { + extraKey: string; + } = { ...getFindListItemSchemaMock(), extraKey: 'some new value' }; + const decoded = findListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts new file mode 100644 index 000000000000..4279d5ef4a07 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_item_schema/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; +import { filter } from '../../common/filter'; +import { cursor } from '../../common/cursor'; +import { sort_field } from '../../common/sort_field'; +import { sort_order } from '../../common/sort_order'; +import { list_id } from '../../common/list_id'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; + +export const findListItemSchema = t.intersection([ + t.exact(t.type({ list_id })), + t.exact( + t.partial({ + cursor, // defaults to undefined if not set during decode + filter, // defaults to undefined if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) + ), +]); + +export type FindListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindListItemSchemaDecoded = RequiredKeepUndefined>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.ts new file mode 100644 index 000000000000..b80369fb6b43 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.mock.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FILTER } from '../../constants/index.mock'; + +import { FindListSchema, FindListSchemaEncoded } from '.'; + +export const getFindListSchemaMock = (): FindListSchemaEncoded => ({ + filter: FILTER, + page: '1', + per_page: '25', + sort_field: undefined, + sort_order: undefined, +}); + +export const getFindListSchemaDecodedMock = (): FindListSchema => ({ + cursor: undefined, + filter: FILTER, + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts new file mode 100644 index 000000000000..06b37bacf845 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getFindListSchemaDecodedMock, getFindListSchemaMock } from './index.mock'; +import { FindListSchemaEncoded, findListSchema } from '.'; + +describe('find_list_schema', () => { + test('it should validate a typical find item request', () => { + const payload = getFindListSchemaMock(); + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getFindListSchemaDecodedMock()); + }); + + test('it should validate and empty object since everything is optional and will respond with an empty object', () => { + const payload: FindListSchemaEncoded = {}; + const decoded = findListSchema.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 validate with page missing', () => { + const payload = getFindListSchemaMock(); + delete payload.page; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListSchemaDecodedMock(); + delete expected.page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with pre_page missing', () => { + const payload = getFindListSchemaMock(); + delete payload.per_page; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListSchemaDecodedMock(); + delete expected.per_page; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with filter missing', () => { + const payload = getFindListSchemaMock(); + delete payload.filter; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListSchemaDecodedMock(); + delete expected.filter; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_field missing', () => { + const payload = getFindListSchemaMock(); + delete payload.sort_field; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListSchemaDecodedMock(); + delete expected.sort_field; + expect(message.schema).toEqual(expected); + }); + + test('it should validate with sort_order missing', () => { + const payload = getFindListSchemaMock(); + delete payload.sort_order; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected = getFindListSchemaDecodedMock(); + delete expected.sort_order; + expect(message.schema).toEqual(expected); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FindListSchemaEncoded & { + extraKey: string; + } = { ...getFindListSchemaMock(), extraKey: 'some new value' }; + const decoded = findListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts new file mode 100644 index 000000000000..8f1520d0caf1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/find_list_schema/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { StringToPositiveNumber } from '@kbn/securitysolution-io-ts-types'; +import { cursor } from '../../common/cursor'; +import { filter } from '../../common/filter'; +import { sort_field } from '../../common/sort_field'; +import { sort_order } from '../../common/sort_order'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; + +export const findListSchema = t.exact( + t.partial({ + cursor, // defaults to undefined if not set during decode + filter, // defaults to undefined if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) +); + +export type FindListSchema = RequiredKeepUndefined>; +export type FindListSchemaEncoded = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/index.ts new file mode 100644 index 000000000000..656d6cea6164 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/get_exception_filter_schema/index.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { namespaceType } from '../../common/default_namespace'; +import { exceptionListItemSchema } from '../../response'; +import { createExceptionListItemSchema } from '../create_exception_list_item_schema'; + +const exceptionListId = t.type({ + exception_list_id: t.string, + namespace_type: namespaceType, +}); + +export const exceptionListIds = t.type({ + exception_list_ids: t.array(exceptionListId), + type: t.literal('exception_list_ids'), +}); + +export const exceptions = t.type({ + exceptions: t.array(t.union([exceptionListItemSchema, createExceptionListItemSchema])), + type: t.literal('exception_items'), +}); + +const optionalExceptionParams = t.exact( + t.partial({ alias: t.string, chunk_size: t.number, exclude_exceptions: t.boolean }) +); + +export const getExceptionFilterSchema = t.intersection([ + t.union([exceptions, exceptionListIds]), + optionalExceptionParams, +]); + +export type GetExceptionFilterSchema = t.TypeOf; +export type ExceptionListId = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts new file mode 100644 index 000000000000..a50c455a9d60 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.mock.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ENTRIES } from '../../constants/index.mock'; +import { ImportExceptionListItemSchema, ImportExceptionListItemSchemaDecoded } from '.'; + +export const getImportExceptionsListItemSchemaMock = ( + itemId = 'item_id_1', + listId = 'detection_list_id' +): ImportExceptionListItemSchema => ({ + description: 'some description', + entries: ENTRIES, + item_id: itemId, + list_id: listId, + name: 'Query with a rule id', + type: 'simple', +}); + +export const getImportExceptionsListItemSchemaDecodedMock = ( + itemId = 'item_id_1', + listId = 'detection_list_id' +): ImportExceptionListItemSchemaDecoded => ({ + ...getImportExceptionsListItemSchemaMock(itemId, listId), + comments: [], + meta: undefined, + namespace_type: 'single', + os_types: [], + tags: [], + expire_time: undefined, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts new file mode 100644 index 000000000000..61e135bfd59a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.test.ts @@ -0,0 +1,172 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { importExceptionListItemSchema, ImportExceptionListItemSchema } from '.'; +import { + getImportExceptionsListItemSchemaDecodedMock, + getImportExceptionsListItemSchemaMock, +} from './index.mock'; +import { getCommentsArrayMock } from '../../common/comment/index.mock'; + +describe('import_list_item_schema', () => { + test('it should validate a typical item request', () => { + const payload = getImportExceptionsListItemSchemaMock(); + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getImportExceptionsListItemSchemaDecodedMock()); + }); + + test('it should validate a typical item request with comments', () => { + const payload = { + ...getImportExceptionsListItemSchemaMock(), + comments: getCommentsArrayMock(), + }; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + ...getImportExceptionsListItemSchemaDecodedMock(), + comments: [ + { + comment: 'some old comment', + created_at: '2020-04-20T15:25:31.830Z', + created_by: 'some user', + id: 'uuid_here', + }, + { + comment: 'some old comment', + created_at: '2020-04-20T15:25:31.830Z', + created_by: 'some user', + id: 'uuid_here', + }, + ], + }); + }); + + test('it should NOT accept an undefined for "item_id"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.item_id; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "item_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "list_id"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.list_id; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "description"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.description; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "name"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.name; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.type; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "entries"', () => { + const payload: Partial> = + getImportExceptionsListItemSchemaMock(); + delete payload.entries; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept any partial fields', () => { + const payload: ImportExceptionListItemSchema = { + ...getImportExceptionsListItemSchemaMock(), + id: '123', + namespace_type: 'single', + comments: [], + os_types: [], + tags: ['123'], + created_at: '2018-08-24T17:49:30.145142000', + created_by: 'elastic', + updated_at: '2018-08-24T17:49:30.145142000', + updated_by: 'elastic', + tie_breaker_id: '123', + _version: '3', + meta: undefined, + }; + + const decoded = importExceptionListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: ImportExceptionListItemSchema & { + extraKey?: string; + } = getImportExceptionsListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = importExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.ts new file mode 100644 index 000000000000..a2d60e292aff --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_item_schema/index.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { Tags, tags } from '../../common/tags'; +import { NamespaceType } from '../../common/default_namespace'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; +import { namespace_type } from '../../common/namespace_type'; +import { meta } from '../../common/meta'; +import { list_id } from '../../common/list_id'; +import { item_id, ItemId } from '../../common/item_id'; +import { id } from '../../common/id'; +import { created_at } from '../../common/created_at'; +import { created_by } from '../../common/created_by'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; +import { _version } from '../../common/underscore_version'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; +import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { EntriesArray } from '../../common/entries'; +import { DefaultImportCommentsArray } from '../../common/default_import_comments_array'; +import { ExpireTimeOrUndefined, expireTimeOrUndefined, ImportCommentsArray } from '../../common'; + +/** + * Differences from this and the createExceptionsListItemSchema are + * - item_id is required + * - id is optional (but ignored in the import code - item_id is exclusively used for imports) + * - immutable is optional but if it is any value other than false it will be rejected + * - created_at is optional (but ignored in the import code) + * - updated_at is optional (but ignored in the import code) + * - created_by is optional (but ignored in the import code) + * - updated_by is optional (but ignored in the import code) + */ +export const importExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEntriesArray, + item_id, + list_id, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + id, // defaults to undefined if not set during decode + comments: DefaultImportCommentsArray, // defaults to empty array if not set during decode + created_at, // defaults undefined if not set during decode + updated_at, // defaults undefined if not set during decode + created_by, // defaults undefined if not set during decode + updated_by, // defaults undefined if not set during decode + _version, // defaults to undefined if not set during decode + tie_breaker_id, + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + expire_time: expireTimeOrUndefined, + }) + ), +]); + +export type ImportExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ImportExceptionListItemSchemaDecoded = Omit< + ImportExceptionListItemSchema, + 'tags' | 'item_id' | 'entries' | 'namespace_type' | 'comments' | 'expire_time' +> & { + comments: ImportCommentsArray; + tags: Tags; + item_id: ItemId; + entries: EntriesArray; + namespace_type: NamespaceType; + os_types: OsTypeArray; + expire_time: ExpireTimeOrUndefined; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..438b0cd54fb0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.mock.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ImportExceptionListSchemaDecoded, ImportExceptionsListSchema } from '.'; + +export const getImportExceptionsListSchemaMock = ( + listId = 'detection_list_id' +): ImportExceptionsListSchema => ({ + description: 'some description', + list_id: listId, + name: 'Query with a rule id', + type: 'detection', +}); + +export const getImportExceptionsListSchemaDecodedMock = ( + listId = 'detection_list_id' +): ImportExceptionListSchemaDecoded => ({ + ...getImportExceptionsListSchemaMock(listId), + immutable: false, + meta: undefined, + namespace_type: 'single', + os_types: [], + tags: [], + version: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..e1d0a55a1770 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.test.ts @@ -0,0 +1,131 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { importExceptionsListSchema, ImportExceptionsListSchema } from '.'; +import { + getImportExceptionsListSchemaMock, + getImportExceptionsListSchemaDecodedMock, +} from './index.mock'; + +describe('import_list_item_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getImportExceptionsListSchemaMock(); + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getImportExceptionsListSchemaDecodedMock()); + }); + + test('it should NOT accept an undefined for "list_id"', () => { + const payload: Partial> = + getImportExceptionsListSchemaMock(); + delete payload.list_id; + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "description"', () => { + const payload: Partial> = + getImportExceptionsListSchemaMock(); + delete payload.description; + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "name"', () => { + const payload: Partial> = + getImportExceptionsListSchemaMock(); + delete payload.name; + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload: Partial> = + getImportExceptionsListSchemaMock(); + delete payload.type; + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept value of "true" for "immutable"', () => { + const payload: ImportExceptionsListSchema = { + ...getImportExceptionsListSchemaMock(), + immutable: true, + }; + + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "true" supplied to "immutable"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept any partial fields', () => { + const payload: ImportExceptionsListSchema = { + ...getImportExceptionsListSchemaMock(), + namespace_type: 'single', + immutable: false, + os_types: [], + tags: ['123'], + created_at: '2018-08-24T17:49:30.145142000', + created_by: 'elastic', + updated_at: '2018-08-24T17:49:30.145142000', + updated_by: 'elastic', + version: 3, + tie_breaker_id: '123', + _version: '3', + meta: undefined, + }; + + const decoded = importExceptionsListSchema.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 not allow an extra key to be sent in', () => { + const payload: ImportExceptionsListSchema & { + extraKey?: string; + } = getImportExceptionsListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = importExceptionsListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts new file mode 100644 index 000000000000..98f5988daf1c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_exception_list_schema/index.ts @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { + DefaultVersionNumber, + DefaultVersionNumberDecoded, + OnlyFalseAllowed, +} from '@kbn/securitysolution-io-ts-types'; + +import { exceptionListType } from '../../common/exception_list'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { Tags, tags } from '../../common/tags'; +import { ListId, list_id } from '../../common/list_id'; +import { NamespaceType } from '../../common/default_namespace'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; +import { namespace_type } from '../../common/namespace_type'; +import { meta } from '../../common/meta'; +import { id } from '../../common/id'; +import { created_at } from '../../common/created_at'; +import { created_by } from '../../common/created_by'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; +import { _version } from '../../common/underscore_version'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; + +/** + * Differences from this and the createExceptionsSchema are + * - list_id is required + * - id is optional (but ignored in the import code - list_id is exclusively used for imports) + * - immutable is optional but if it is any value other than false it will be rejected + * - created_at is optional (but ignored in the import code) + * - updated_at is optional (but ignored in the import code) + * - created_by is optional (but ignored in the import code) + * - updated_by is optional (but ignored in the import code) + */ +export const importExceptionsListSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type: exceptionListType, + list_id, + }) + ), + t.exact( + t.partial({ + id, // defaults to undefined if not set during decode + immutable: OnlyFalseAllowed, + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + created_at, // defaults "undefined" if not set during decode + updated_at, // defaults "undefined" if not set during decode + created_by, // defaults "undefined" if not set during decode + updated_by, // defaults "undefined" if not set during decode + _version, // defaults to undefined if not set during decode + tie_breaker_id, + version: DefaultVersionNumber, // defaults to numerical 1 if not set during decode + }) + ), +]); + +export type ImportExceptionsListSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ImportExceptionListSchemaDecoded = Omit< + ImportExceptionsListSchema, + 'tags' | 'list_id' | 'namespace_type' | 'os_types' | 'immutable' +> & { + immutable: false; + tags: Tags; + list_id: ListId; + namespace_type: NamespaceType; + os_types: OsTypeArray; + version: DefaultVersionNumberDecoded; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.ts new file mode 100644 index 000000000000..fc5fc0ca703b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID, TYPE } from '../../constants/index.mock'; + +import { ImportListItemQuerySchema } from '.'; + +export const getImportListItemQuerySchemaMock = (): ImportListItemQuerySchema => ({ + deserializer: undefined, + list_id: LIST_ID, + serializer: undefined, + type: TYPE, + refresh: 'false', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts new file mode 100644 index 000000000000..26d1ba486468 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.test.ts @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { ImportListItemQuerySchema, importListItemQuerySchema } from '.'; +import { getImportListItemQuerySchemaMock } from './index.mock'; + +describe('import_list_item_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getImportListItemQuerySchemaMock(); + const decoded = importListItemQuerySchema.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 accept an undefined for "list_id"', () => { + const payload = getImportListItemQuerySchemaMock(); + delete payload.list_id; + const decoded = importListItemQuerySchema.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 accept an undefined for "type"', () => { + const payload = getImportListItemQuerySchemaMock(); + delete payload.type; + const decoded = importListItemQuerySchema.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 accept an undefined for "type" and "list_id', () => { + const payload = getImportListItemQuerySchemaMock(); + delete payload.type; + delete payload.list_id; + const decoded = importListItemQuerySchema.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 accept an undefined for "serializer"', () => { + const payload = getImportListItemQuerySchemaMock(); + delete payload.serializer; + const decoded = importListItemQuerySchema.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 accept an undefined for "deserializer"', () => { + const payload = getImportListItemQuerySchemaMock(); + delete payload.deserializer; + const decoded = importListItemQuerySchema.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 not allow an extra key to be sent in', () => { + const payload: ImportListItemQuerySchema & { + extraKey?: string; + } = getImportListItemQuerySchemaMock(); + payload.extraKey = 'some new value'; + const decoded = importListItemQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.ts new file mode 100644 index 000000000000..19cd873825d2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_query_schema/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { deserializer } from '../../common/deserializer'; +import { list_id } from '../../common/list_id'; +import { type } from '../../common/type'; +import { serializer } from '../../common/serializer'; +import { refreshWithWaitFor } from '../../common/refresh'; + +export const importListItemQuerySchema = t.exact( + t.partial({ deserializer, list_id, serializer, type, refresh: refreshWithWaitFor }) +); + +export type ImportListItemQuerySchema = RequiredKeepUndefined< + t.TypeOf +>; +export type ImportListItemQuerySchemaEncoded = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..32fee251c078 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.mock.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ImportListItemSchema } from '.'; + +export const getImportListItemSchemaMock = (): ImportListItemSchema => ({ + file: {}, +}); + +/** + * This is useful for end to end tests, it will return a buffer given a string array + * of things to import. + * @param input Array of strings of things to import + */ +export const getImportListItemAsBuffer = (input: string[]): Buffer => { + return Buffer.from(input.join('\r\n')); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts new file mode 100644 index 000000000000..0e572255b574 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { ImportListItemSchema, importListItemSchema } from '.'; +import { getImportListItemSchemaMock } from './index.mock'; + +describe('import_list_item_schema', () => { + test('it should validate a typical lists request', () => { + const payload = getImportListItemSchemaMock(); + const decoded = importListItemSchema.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 NOT accept an undefined for a file', () => { + const payload = getImportListItemSchemaMock(); + // @ts-expect-error + delete payload.file; + const decoded = importListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "file"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ImportListItemSchema & { + extraKey?: string; + } = getImportListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = importListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts new file mode 100644 index 000000000000..4072cf029bae --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/import_list_item_schema/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { file } from '../../common/file'; + +export const importListItemSchema = t.exact( + t.type({ + file, + }) +); + +export type ImportListItemSchema = RequiredKeepUndefined>; +export type ImportListItemSchemaEncoded = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/index.ts new file mode 100644 index 000000000000..a6a3099ddde8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/index.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './create_endpoint_list_item_schema'; +export * from './create_exception_list_item_schema'; +export * from './create_exception_list_schema'; +export * from './create_rule_exception_item_schema'; +export * from './create_list_item_schema'; +export * from './create_list_schema'; +export * from './delete_endpoint_list_item_schema'; +export * from './delete_exception_list_schema'; +export * from './delete_exception_list_item_schema'; +export * from './delete_list_item_schema'; +export * from './delete_list_schema'; +export * from './duplicate_exception_list_query_schema'; +export * from './export_exception_list_query_schema'; +export * from './export_list_item_query_schema'; +export * from './find_endpoint_list_item_schema'; +export * from './find_exception_list_schema'; +export * from './find_exception_list_item_schema'; +export * from './find_list_item_schema'; +export * from './find_list_schema'; +export * from './get_exception_filter_schema'; +export * from './import_list_item_query_schema'; +export * from './import_exception_list_schema'; +export * from './import_exception_item_schema'; +export * from './import_list_item_schema'; +export * from './patch_list_item_schema'; +export * from './patch_list_schema'; +export * from './read_endpoint_list_item_schema'; +export * from './read_exception_list_item_schema'; +export * from './read_exception_list_schema'; +export * from './read_list_item_schema'; +export * from './read_list_schema'; +export * from './summary_exception_list_schema'; +export * from './update_endpoint_list_item_schema'; +export * from './update_exception_list_item_schema'; +export * from './update_exception_list_schema'; +export * from './update_list_item_schema'; +export * from './update_list_schema'; + +// Internal routes +export * from './internal/create_exception_list_schema'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..8ab58a7b0bdd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.test.ts @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; + +import { ExceptionListTypeEnum } from '../../../common/exception_list'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { internalCreateExceptionListSchema } from '.'; +import { getCreateExceptionListSchemaMock } from '../../create_exception_list_schema/index.mock'; + +describe('create_exception_list_schema', () => { + test('it should accept artifact list_id', () => { + const payload = { + ...getCreateExceptionListSchemaMock(), + list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, + }; + const decoded = internalCreateExceptionListSchema.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 when invalid list_id', () => { + const payload = { + ...getCreateExceptionListSchemaMock(), + list_id: ExceptionListTypeEnum.DETECTION, + }; + const decoded = internalCreateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "detection" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + test('it should accept artifact type', () => { + const payload = { + ...getCreateExceptionListSchemaMock(), + list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, + type: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, + }; + const decoded = internalCreateExceptionListSchema.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 when invalid type', () => { + const payload = { + ...getCreateExceptionListSchemaMock(), + list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS, + type: ExceptionListTypeEnum.DETECTION, + }; + const decoded = internalCreateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "detection" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts new file mode 100644 index 000000000000..ff8f9670a4e0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/internal/create_exception_list_schema/index.ts @@ -0,0 +1,46 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ENDPOINT_ARTIFACT_LIST_IDS } from '@kbn/securitysolution-list-constants'; +import * as t from 'io-ts'; + +import { + createExceptionListSchema, + CreateExceptionListSchemaDecoded, +} from '../../create_exception_list_schema'; + +export const internalCreateExceptionListSchema = t.intersection([ + t.exact( + t.type({ + type: t.keyof({ + endpoint: null, + endpoint_events: null, + endpoint_host_isolation_exceptions: null, + endpoint_blocklists: null, + }), + }) + ), + t.exact( + t.partial({ + list_id: t.keyof( + ENDPOINT_ARTIFACT_LIST_IDS.reduce>((mapOfListIds, listId) => { + mapOfListIds[listId] = null; + + return mapOfListIds; + }, {}) + ), + }) + ), + createExceptionListSchema, +]); + +export type InternalCreateExceptionListSchema = t.OutputOf< + typeof internalCreateExceptionListSchema +>; + +// This type is used after a decode since some things are defaults after a decode. +export type InternalCreateExceptionListSchemaDecoded = CreateExceptionListSchemaDecoded; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..fd30cba20439 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; + +import { PatchListItemSchema } from '.'; + +export const getPathListItemSchemaMock = (): PatchListItemSchema => ({ + id: LIST_ITEM_ID, + meta: META, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts new file mode 100644 index 000000000000..55050ea6eab8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.test.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getPathListItemSchemaMock } from './index.mock'; +import { PatchListItemSchema, patchListItemSchema } from '.'; + +describe('patch_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getPathListItemSchemaMock(); + const decoded = patchListItemSchema.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 NOT accept an undefined for "id"', () => { + const payload = getPathListItemSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = patchListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getPathListItemSchemaMock(); + delete payload.meta; + const decoded = patchListItemSchema.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 accept an undefined for "value"', () => { + const payload = getPathListItemSchemaMock(); + delete payload.value; + const decoded = patchListItemSchema.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 accept an undefined for "meta" and "value"', () => { + const payload = getPathListItemSchemaMock(); + delete payload.meta; + delete payload.value; + const decoded = patchListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: PatchListItemSchema & { extraKey?: string } = getPathListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = patchListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts new file mode 100644 index 000000000000..caa0d62f003f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_item_schema/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { _version } from '../../common/underscore_version'; +import { id } from '../../common/id'; +import { meta } from '../../common/meta'; +import { value } from '../../common/value'; +import { refresh } from '../../common/refresh'; + +export const patchListItemSchema = t.intersection([ + t.exact( + t.type({ + id, + }) + ), + t.exact(t.partial({ _version, meta, value, refresh })), +]); + +export type PatchListItemSchema = t.OutputOf; +export type PatchListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts new file mode 100644 index 000000000000..2b71a46c4665 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DESCRIPTION, LIST_ITEM_ID, META, NAME } from '../../constants/index.mock'; + +import { PatchListSchema } from '.'; + +export const getPathListSchemaMock = (): PatchListSchema => ({ + description: DESCRIPTION, + id: LIST_ITEM_ID, + meta: META, + name: NAME, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts new file mode 100644 index 000000000000..be0dd3b2f6ea --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.test.ts @@ -0,0 +1,129 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getPathListSchemaMock } from './index.mock'; +import { PatchListSchema, patchListSchema } from '.'; + +describe('patch_list_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getPathListSchemaMock(); + const decoded = patchListSchema.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 NOT accept an undefined for "id"', () => { + const payload = getPathListSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = patchListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getPathListSchemaMock(); + delete payload.meta; + const decoded = patchListSchema.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 accept an undefined for "name"', () => { + const payload = getPathListSchemaMock(); + delete payload.name; + const decoded = patchListSchema.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 accept an undefined for "description"', () => { + const payload = getPathListSchemaMock(); + delete payload.description; + const decoded = patchListSchema.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 accept an undefined for "description", "meta", "name', () => { + const payload = getPathListSchemaMock(); + delete payload.description; + delete payload.name; + delete payload.meta; + const decoded = patchListSchema.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 accept an undefined for "description", "meta"', () => { + const payload = getPathListSchemaMock(); + delete payload.description; + delete payload.meta; + const decoded = patchListSchema.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 accept an undefined for "description", "name"', () => { + const payload = getPathListSchemaMock(); + delete payload.description; + delete payload.name; + const decoded = patchListSchema.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 accept an undefined for "meta", "name"', () => { + const payload = getPathListSchemaMock(); + delete payload.meta; + delete payload.name; + const decoded = patchListSchema.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 not allow an extra key to be sent in', () => { + const payload: PatchListSchema & { extraKey?: string } = getPathListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = patchListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.ts new file mode 100644 index 000000000000..cb72d902f189 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/patch_list_schema/index.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { version } from '@kbn/securitysolution-io-ts-types'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { _version } from '../../common/underscore_version'; +import { meta } from '../../common/meta'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; + +export const patchListSchema = t.intersection([ + t.exact( + t.type({ + id, + }) + ), + t.exact( + t.partial({ + _version, // is undefined if not set during decode + description, // is undefined if not set during decode + meta, // is undefined if not set during decode + name, // is undefined if not set during decode + version, // is undefined if not set during decode + }) + ), +]); + +export type PatchListSchema = t.OutputOf; +export type PatchListSchemaDecoded = RequiredKeepUndefined>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..7b83368ad73e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.mock.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, ITEM_ID } from '../../constants/index.mock'; + +import { ReadEndpointListItemSchema } from '.'; + +export const getReadEndpointListItemSchemaMock = (): ReadEndpointListItemSchema => ({ + id: ID, + item_id: ITEM_ID, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.ts new file mode 100644 index 000000000000..dc8a14b2ef10 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.test.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getReadEndpointListItemSchemaMock } from './index.mock'; +import { ReadEndpointListItemSchema, readEndpointListItemSchema } from '.'; + +describe('read_endpoint_list_item_schema', () => { + test('it should validate a typical list request', () => { + const payload = getReadEndpointListItemSchemaMock(); + const decoded = readEndpointListItemSchema.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 accept an undefined for "id"', () => { + const payload = getReadEndpointListItemSchemaMock(); + delete payload.id; + const decoded = readEndpointListItemSchema.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 accept an undefined for "item_id"', () => { + const payload = getReadEndpointListItemSchemaMock(); + delete payload.item_id; + const decoded = readEndpointListItemSchema.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 NOT accept "namespace_type" since endpoint list items do not need it', () => { + const payload: ReadEndpointListItemSchema & { + namespace_type: string; + } = { ...getReadEndpointListItemSchemaMock(), namespace_type: 'single' }; + // @ts-expect-error + delete payload.namespace_type; + const decoded = readEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getReadEndpointListItemSchemaMock()); + }); + + test('it should accept an undefined for "id", "item_id"', () => { + const payload = getReadEndpointListItemSchemaMock(); + delete payload.id; + delete payload.item_id; + const decoded = readEndpointListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: ReadEndpointListItemSchema & { + extraKey?: string; + } = getReadEndpointListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = readEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.ts new file mode 100644 index 000000000000..6e32b1fe5186 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_endpoint_list_item_schema/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { item_id } from '../../common/item_id'; + +export const readEndpointListItemSchema = t.exact( + t.partial({ + id, + item_id, + }) +); + +export type ReadEndpointListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ReadEndpointListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..6ce6e68ec6e0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, ITEM_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { ReadExceptionListItemSchema } from '.'; + +export const getReadExceptionListItemSchemaMock = (): ReadExceptionListItemSchema => ({ + id: ID, + item_id: ITEM_ID, + namespace_type: NAMESPACE_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..68f636ccb870 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.test.ts @@ -0,0 +1,126 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getReadExceptionListItemSchemaMock } from './index.mock'; +import { ReadExceptionListItemSchema, readExceptionListItemSchema } from '.'; + +describe('read_exception_list_item_schema', () => { + test('it should validate a typical exception list request', () => { + const payload = getReadExceptionListItemSchemaMock(); + const decoded = readExceptionListItemSchema.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 accept an undefined for "id"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.id; + const decoded = readExceptionListItemSchema.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 accept an undefined for "item_id"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.item_id; + const decoded = readExceptionListItemSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.namespace_type; + const decoded = readExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getReadExceptionListItemSchemaMock()); + }); + + test('it should accept an undefined for "id", "item_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.id; + delete payload.namespace_type; + delete payload.item_id; + const output = getReadExceptionListItemSchemaMock(); + delete output.id; + delete output.item_id; + const decoded = readExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "id", "item_id"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.id; + delete payload.item_id; + const decoded = readExceptionListItemSchema.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 accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.id; + delete payload.namespace_type; + const output = getReadExceptionListItemSchemaMock(); + delete output.id; + const decoded = readExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "item_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListItemSchemaMock(); + delete payload.namespace_type; + delete payload.item_id; + const output = getReadExceptionListItemSchemaMock(); + delete output.item_id; + const decoded = readExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ReadExceptionListItemSchema & { + extraKey?: string; + } = getReadExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = readExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..9111587af7e9 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_item_schema/index.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NamespaceType } from '../../common/default_namespace'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { item_id } from '../../common/item_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const readExceptionListItemSchema = t.exact( + t.partial({ + id, + item_id, + namespace_type, // defaults to 'single' if not set during decode + }) +); + +export type ReadExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ReadExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceType; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..f122f1d20339 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { ReadExceptionListSchema } from '.'; + +export const getReadExceptionListSchemaMock = (): ReadExceptionListSchema => ({ + id: ID, + list_id: LIST_ID, + namespace_type: NAMESPACE_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..89cd869bd17c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.test.ts @@ -0,0 +1,126 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getReadExceptionListSchemaMock } from './index.mock'; +import { ReadExceptionListSchema, readExceptionListSchema } from '.'; + +describe('read_exception_list_schema', () => { + test('it should validate a typical exception list request', () => { + const payload = getReadExceptionListSchemaMock(); + const decoded = readExceptionListSchema.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 accept an undefined for "id"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.id; + const decoded = readExceptionListSchema.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 accept an undefined for "list_id"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.list_id; + const decoded = readExceptionListSchema.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 accept an undefined for "namespace_type" but default to "single"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.namespace_type; + const decoded = readExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getReadExceptionListSchemaMock()); + }); + + test('it should accept an undefined for "id", "list_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.id; + delete payload.namespace_type; + delete payload.list_id; + const output = getReadExceptionListSchemaMock(); + delete output.id; + delete output.list_id; + const decoded = readExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "id", "list_id"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.id; + delete payload.list_id; + const decoded = readExceptionListSchema.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 accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.id; + delete payload.namespace_type; + const output = getReadExceptionListSchemaMock(); + delete output.id; + const decoded = readExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "list_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getReadExceptionListSchemaMock(); + delete payload.namespace_type; + delete payload.list_id; + const output = getReadExceptionListSchemaMock(); + delete output.list_id; + const decoded = readExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ReadExceptionListSchema & { + extraKey?: string; + } = getReadExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = readExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.ts new file mode 100644 index 000000000000..b4d9b7309fb5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_exception_list_schema/index.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NamespaceType } from '../../common/default_namespace'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const readExceptionListSchema = t.exact( + t.partial({ + id, + list_id, + namespace_type, // defaults to 'single' if not set during decode + }) +); + +export type ReadExceptionListSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ReadExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceType; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..a23911123140 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID, LIST_ITEM_ID, VALUE } from '../../constants/index.mock'; + +import { ReadListItemSchema } from '.'; + +export const getReadListItemSchemaMock = (): ReadListItemSchema => ({ + id: LIST_ITEM_ID, + list_id: LIST_ID, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts new file mode 100644 index 000000000000..9370aa5e3d45 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.test.ts @@ -0,0 +1,117 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getReadListItemSchemaMock } from './index.mock'; +import { ReadListItemSchema, readListItemSchema } from '.'; + +describe('read_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getReadListItemSchemaMock(); + const decoded = readListItemSchema.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 accept an undefined for "id"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.id; + const decoded = readListItemSchema.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 accept an undefined for "list_id"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.list_id; + const decoded = readListItemSchema.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 accept an undefined for "value"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.value; + const decoded = readListItemSchema.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 accept an undefined for "id", "list_id", "value"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.id; + delete payload.value; + delete payload.list_id; + const decoded = readListItemSchema.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 accept an undefined for "id", "list_id"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.id; + delete payload.list_id; + const decoded = readListItemSchema.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 accept an undefined for "id", "value"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.id; + delete payload.value; + const decoded = readListItemSchema.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 accept an undefined for "list_id", "value"', () => { + const payload = getReadListItemSchemaMock(); + delete payload.value; + delete payload.list_id; + const decoded = readListItemSchema.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 not allow an extra key to be sent in', () => { + const payload: ReadListItemSchema & { extraKey?: string } = getReadListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = readListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/index.ts new file mode 100644 index 000000000000..571f37ff403e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_item_schema/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { value } from '../../common/value'; + +export const readListItemSchema = t.exact(t.partial({ id, list_id, value })); + +export type ReadListItemSchema = t.OutputOf; +export type ReadListItemSchemaDecoded = RequiredKeepUndefined>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts new file mode 100644 index 000000000000..c82b34381554 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { LIST_ID } from '../../constants/index.mock'; + +import { ReadListSchema } from '.'; + +export const getReadListSchemaMock = (): ReadListSchema => ({ + id: LIST_ID, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.test.ts new file mode 100644 index 000000000000..1953341d2be4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.test.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getReadListSchemaMock } from './index.mock'; +import { ReadListSchema, readListSchema } from '.'; + +describe('read_list_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getReadListSchemaMock(); + const decoded = readListSchema.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 NOT accept an undefined for "id"', () => { + const payload = getReadListSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = readListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ReadListSchema & { extraKey?: string } = getReadListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = readListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/index.ts new file mode 100644 index 000000000000..6382a7c0ad97 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/read_list_schema/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { id } from '../../common/id'; + +export const readListSchema = t.exact( + t.type({ + id, + }) +); + +export type ReadListSchema = t.OutputOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..af6dc55b61da --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FILTER, ID, LIST_ID, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { SummaryExceptionListSchema } from '.'; + +export const getSummaryExceptionListSchemaMock = (): SummaryExceptionListSchema => ({ + filter: FILTER, + id: ID, + list_id: LIST_ID, + namespace_type: NAMESPACE_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..53a734ed034e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.test.ts @@ -0,0 +1,136 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getSummaryExceptionListSchemaMock } from './index.mock'; +import { SummaryExceptionListSchema, summaryExceptionListSchema } from '.'; + +describe('summary_exception_list_schema', () => { + test('it should validate a typical exception list request', () => { + const payload = getSummaryExceptionListSchemaMock(); + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "filter"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.filter; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "id"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "list_id"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.list_id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "namespace_type" but default to "single"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.namespace_type; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getSummaryExceptionListSchemaMock()); + }); + + test('it should accept an undefined for "id", "list_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.id; + delete payload.namespace_type; + delete payload.list_id; + const output = getSummaryExceptionListSchemaMock(); + delete output.id; + delete output.list_id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "id", "list_id"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.id; + delete payload.list_id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an undefined for "id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.id; + delete payload.namespace_type; + const output = getSummaryExceptionListSchemaMock(); + delete output.id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should accept an undefined for "list_id", "namespace_type" but default "namespace_type" to "single"', () => { + const payload = getSummaryExceptionListSchemaMock(); + delete payload.namespace_type; + delete payload.list_id; + const output = getSummaryExceptionListSchemaMock(); + delete output.list_id; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(output); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: SummaryExceptionListSchema & { + extraKey?: string; + } = getSummaryExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = summaryExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = foldLeftRight(checked); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts new file mode 100644 index 000000000000..6be4f0c57b08 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/summary_exception_list_schema/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { NamespaceType } from '../../common/default_namespace'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { filter, Filter } from '../../common/filter'; +import { list_id } from '../../common/list_id'; +import { namespace_type } from '../../common/namespace_type'; + +export const summaryExceptionListSchema = t.exact( + t.partial({ + filter, + id, + list_id, + namespace_type, // defaults to 'single' if not set during decode + }) +); + +export type SummaryExceptionListSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type SummaryExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'namespace_type' +> & { + namespace_type: NamespaceType; + filter: Filter; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..57244aac0426 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.mock.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + COMMENTS, + DESCRIPTION, + ENTRIES, + ID, + ITEM_TYPE, + LIST_ITEM_ID, + META, + NAME, + OS_TYPES, + TAGS, +} from '../../constants/index.mock'; + +import { UpdateEndpointListItemSchema } from '.'; + +export const getUpdateEndpointListItemSchemaMock = (): UpdateEndpointListItemSchema => ({ + _version: undefined, + comments: COMMENTS, + description: DESCRIPTION, + entries: ENTRIES, + id: ID, + item_id: LIST_ITEM_ID, + meta: META, + name: NAME, + os_types: OS_TYPES, + tags: TAGS, + type: ITEM_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts new file mode 100644 index 000000000000..1def91ca1a8e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.test.ts @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { UpdateEndpointListItemSchema, updateEndpointListItemSchema } from '.'; +import { getUpdateEndpointListItemSchemaMock } from './index.mock'; + +describe('update_endpoint_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getUpdateEndpointListItemSchemaMock(); + const decoded = updateEndpointListItemSchema.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 not accept an undefined for "description"', () => { + const payload = getUpdateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "name"', () => { + const payload = getUpdateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "type"', () => { + const payload = getUpdateEndpointListItemSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept a value for "list_id"', () => { + const payload: UpdateEndpointListItemSchema & { + list_id?: string; + } = getUpdateEndpointListItemSchemaMock(); + payload.list_id = 'some new list_id'; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta" but strip it out', () => { + const payload = getUpdateEndpointListItemSchemaMock(); + const outputPayload = getUpdateEndpointListItemSchemaMock(); + delete payload.meta; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete outputPayload.meta; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "comments" but return an array', () => { + const inputPayload = getUpdateEndpointListItemSchemaMock(); + const outputPayload = getUpdateEndpointListItemSchemaMock(); + delete inputPayload.comments; + outputPayload.comments = []; + const decoded = updateEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should NOT accept an undefined for "entries"', () => { + const inputPayload = getUpdateEndpointListItemSchemaMock(); + const outputPayload = getUpdateEndpointListItemSchemaMock(); + // @ts-expect-error + delete inputPayload.entries; + outputPayload.entries = []; + const decoded = updateEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "tags" but return an array', () => { + const inputPayload = getUpdateEndpointListItemSchemaMock(); + const outputPayload = getUpdateEndpointListItemSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = updateEndpointListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: UpdateEndpointListItemSchema & { + extraKey?: string; + } = getUpdateEndpointListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = updateEndpointListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts new file mode 100644 index 000000000000..e301137058af --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_endpoint_list_item_schema/index.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { DefaultUpdateCommentsArray } from '../../common/default_update_comments_array'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { description } from '../../common/description'; +import { name } from '../../common/name'; +import { _version } from '../../common/underscore_version'; +import { id } from '../../common/id'; +import { meta } from '../../common/meta'; +import { Tags, tags } from '../../common/tags'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { UpdateCommentsArray } from '../../common/update_comment'; +import { EntriesArray } from '../../common/entries'; + +export const updateEndpointListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEntriesArray, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + _version, // defaults to undefined if not set during decode + comments: DefaultUpdateCommentsArray, // defaults to empty array if not set during decode + id, // defaults to undefined if not set during decode + item_id: t.union([t.string, t.undefined]), + meta, // defaults to undefined if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type UpdateEndpointListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type UpdateEndpointListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'entries' | 'comments' +> & { + comments: UpdateCommentsArray; + tags: Tags; + entries: EntriesArray; + os_types: OsTypeArray; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..c7560348179d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.mock.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + COMMENTS, + DESCRIPTION, + ENTRIES, + ID, + ITEM_ID, + ITEM_TYPE, + LIST_ITEM_ID, + META, + NAME, + NAMESPACE_TYPE, + OS_TYPES, + TAGS, +} from '../../constants/index.mock'; + +import { UpdateExceptionListItemSchema } from '.'; + +export const getUpdateExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ + _version: undefined, + comments: COMMENTS, + description: DESCRIPTION, + entries: ENTRIES, + id: ID, + item_id: LIST_ITEM_ID, + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: ['linux'], + tags: TAGS, + type: ITEM_TYPE, +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + * after doing a get of the structure. + */ +export const getUpdateMinimalExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + name: NAME, + os_types: OS_TYPES, + type: ITEM_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..0adbf1224d72 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.test.ts @@ -0,0 +1,160 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { UpdateExceptionListItemSchema, updateExceptionListItemSchema } from '.'; +import { getUpdateExceptionListItemSchemaMock } from './index.mock'; + +describe('update_exception_list_item_schema', () => { + test('it should validate a typical exception list item request', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + const decoded = updateExceptionListItemSchema.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 not accept an undefined for "description"', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "name"', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "type"', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept a value for "list_id"', () => { + const payload: UpdateExceptionListItemSchema & { + list_id?: string; + } = getUpdateExceptionListItemSchemaMock(); + payload.list_id = 'some new list_id'; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "list_id"']); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta" but strip it out', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + const outputPayload = getUpdateExceptionListItemSchemaMock(); + delete payload.meta; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete outputPayload.meta; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "comments" but return an array', () => { + const inputPayload = getUpdateExceptionListItemSchemaMock(); + const outputPayload = getUpdateExceptionListItemSchemaMock(); + delete inputPayload.comments; + outputPayload.comments = []; + const decoded = updateExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should NOT accept an undefined for "entries"', () => { + const inputPayload = getUpdateExceptionListItemSchemaMock(); + const outputPayload = getUpdateExceptionListItemSchemaMock(); + // @ts-expect-error + delete inputPayload.entries; + outputPayload.entries = []; + const decoded = updateExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "namespace_type" but return enum "single"', () => { + const inputPayload = getUpdateExceptionListItemSchemaMock(); + const outputPayload = getUpdateExceptionListItemSchemaMock(); + delete inputPayload.namespace_type; + outputPayload.namespace_type = 'single'; + const decoded = updateExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "tags" but return an array', () => { + const inputPayload = getUpdateExceptionListItemSchemaMock(); + const outputPayload = getUpdateExceptionListItemSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = updateExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "item_id" and generate a correct body not counting the uuid', () => { + const inputPayload = getUpdateExceptionListItemSchemaMock(); + delete inputPayload.item_id; + const decoded = updateExceptionListItemSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as UpdateExceptionListItemSchema).item_id; + expect(message.schema).toEqual(inputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: UpdateExceptionListItemSchema & { + extraKey?: string; + } = getUpdateExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = updateExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..910acbe2c942 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_item_schema/index.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { ExceptionListItemEntryArray } from '@kbn/securitysolution-exceptions-common/api'; +import { NamespaceType } from '../../common/default_namespace'; +import { DefaultUpdateCommentsArray } from '../../common/default_update_comments_array'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { nonEmptyEntriesArray } from '../../common/non_empty_entries_array'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { Tags, tags } from '../../common/tags'; +import { UpdateCommentsArray } from '../../common/update_comment'; +import { description } from '../../common/description'; +import { name } from '../../common/name'; +import { _version } from '../../common/underscore_version'; +import { id } from '../../common/id'; +import { item_id } from '../../common/item_id'; +import { meta } from '../../common/meta'; +import { namespace_type } from '../../common/namespace_type'; +import { ExpireTimeOrUndefined, expireTimeOrUndefined } from '../../common'; + +export const updateExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + entries: nonEmptyEntriesArray, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + _version, // defaults to undefined if not set during decode + comments: DefaultUpdateCommentsArray, // defaults to empty array if not set during decode + expire_time: expireTimeOrUndefined, + id, // defaults to undefined if not set during decode + item_id, + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type UpdateExceptionListItemSchema = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type UpdateExceptionListItemSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags' | 'entries' | 'namespace_type' | 'comments' | 'os_types' | 'expire_time' +> & { + comments: UpdateCommentsArray; + tags: Tags; + entries: ExceptionListItemEntryArray; + namespace_type: NamespaceType; + os_types: OsTypeArray; + expire_time: ExpireTimeOrUndefined; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..9aac2453a7be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.mock.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DESCRIPTION, ID, LIST_ID, META, NAME, NAMESPACE_TYPE } from '../../constants/index.mock'; + +import { UpdateExceptionListSchema } from '.'; + +export const getUpdateExceptionListSchemaMock = (): UpdateExceptionListSchema => ({ + _version: undefined, + description: DESCRIPTION, + id: ID, + list_id: LIST_ID, + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: [], + tags: ['malware'], + type: 'endpoint', +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + * after doing a get of the structure. + */ +export const getUpdateMinimalExceptionListSchemaMock = (): UpdateExceptionListSchema => ({ + description: DESCRIPTION, + list_id: LIST_ID, + name: NAME, + type: 'endpoint', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..029751ac4d14 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.test.ts @@ -0,0 +1,121 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { UpdateExceptionListSchema, updateExceptionListSchema } from '.'; +import { getUpdateExceptionListSchemaMock } from './index.mock'; + +describe('update_exception_list_schema', () => { + test('it should validate a typical exception list request', () => { + const payload = getUpdateExceptionListSchemaMock(); + const decoded = updateExceptionListSchema.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 not accept an undefined for "description"', () => { + const payload = getUpdateExceptionListSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = updateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "name"', () => { + const payload = getUpdateExceptionListSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = updateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not accept an undefined for "type"', () => { + const payload = getUpdateExceptionListSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = updateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta" but strip it out', () => { + const payload = getUpdateExceptionListSchemaMock(); + const outputPayload = getUpdateExceptionListSchemaMock(); + delete payload.meta; + const decoded = updateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete outputPayload.meta; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "namespace_type" but return enum "single"', () => { + const inputPayload = getUpdateExceptionListSchemaMock(); + const outputPayload = getUpdateExceptionListSchemaMock(); + delete inputPayload.namespace_type; + outputPayload.namespace_type = 'single'; + const decoded = updateExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "tags" but return an array', () => { + const inputPayload = getUpdateExceptionListSchemaMock(); + const outputPayload = getUpdateExceptionListSchemaMock(); + delete inputPayload.tags; + outputPayload.tags = []; + const decoded = updateExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should accept an undefined for "list_id" and generate a correct body not counting the uuid', () => { + const inputPayload = getUpdateExceptionListSchemaMock(); + delete inputPayload.list_id; + const decoded = updateExceptionListSchema.decode(inputPayload); + const checked = exactCheck(inputPayload, decoded); + const message = pipe(checked, foldLeftRight); + delete (message.schema as UpdateExceptionListSchema).list_id; + expect(message.schema).toEqual(inputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: UpdateExceptionListSchema & { + extraKey?: string; + } = getUpdateExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = updateExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts new file mode 100644 index 000000000000..be4006c3efa1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_exception_list_schema/index.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { version } from '@kbn/securitysolution-io-ts-types'; +import { OsTypeArray, osTypeArrayOrUndefined } from '../../common/os_type'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { Tags, tags } from '../../common/tags'; +import { NamespaceType } from '../../common/default_namespace'; +import { description } from '../../common/description'; +import { name } from '../../common/name'; +import { _version } from '../../common/underscore_version'; +import { exceptionListType } from '../../common/exception_list'; +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { meta } from '../../common/meta'; +import { namespace_type } from '../../common/namespace_type'; + +export const updateExceptionListSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type: exceptionListType, + }) + ), + t.exact( + t.partial({ + _version, // defaults to undefined if not set during decode + id, // defaults to undefined if not set during decode + list_id, // defaults to undefined if not set during decode + meta, // defaults to undefined if not set during decode + namespace_type, // defaults to 'single' if not set during decode + os_types: osTypeArrayOrUndefined, // defaults to empty array if not set during decode + tags, // defaults to empty array if not set during decode + version, // defaults to undefined if not set during decode + }) + ), +]); + +export type UpdateExceptionListSchema = t.OutputOf; + +// This type is used after a decode since the arrays turn into defaults of empty arrays. +export type UpdateExceptionListSchemaDecoded = Omit< + RequiredKeepUndefined>, + 'tags | namespace_type' | 'os_types' +> & { + tags: Tags; + namespace_type: NamespaceType; + os_types: OsTypeArray; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..7d65f59aa8cd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.mock.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ID, LIST_ITEM_ID, META, VALUE } from '../../constants/index.mock'; + +import { UpdateListItemSchema } from '.'; + +export const getUpdateListItemSchemaMock = (): UpdateListItemSchema => ({ + id: ID, + meta: META, + value: VALUE, +}); + +/** + * Useful for end to end testing + */ +export const getUpdateMinimalListItemSchemaMock = (): UpdateListItemSchema => ({ + id: LIST_ITEM_ID, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.ts new file mode 100644 index 000000000000..ca6402455aab --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { UpdateListItemSchema, updateListItemSchema } from '.'; +import { getUpdateListItemSchemaMock } from './index.mock'; + +describe('update_list_item_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getUpdateListItemSchemaMock(); + const decoded = updateListItemSchema.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 accept an undefined for "meta" but strip it out', () => { + const payload = getUpdateListItemSchemaMock(); + const outputPayload = getUpdateListItemSchemaMock(); + delete payload.meta; + const decoded = updateListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete outputPayload.meta; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: UpdateListItemSchema & { + extraKey?: string; + } = getUpdateListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = updateListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.ts new file mode 100644 index 000000000000..2df22b5c57b7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_item_schema/index.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { _version } from '../../common/underscore_version'; +import { id } from '../../common/id'; +import { value } from '../../common/value'; +import { meta } from '../../common/meta'; + +export const updateListItemSchema = t.intersection([ + t.exact( + t.type({ + id, + value, + }) + ), + t.exact( + t.partial({ + _version, // defaults to undefined if not set during decode + meta, // defaults to undefined if not set during decode + }) + ), +]); + +export type UpdateListItemSchema = t.OutputOf; +export type UpdateListItemSchemaDecoded = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.ts new file mode 100644 index 000000000000..99362d8ef8a7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DESCRIPTION, LIST_ID, META, NAME, _VERSION } from '../../constants/index.mock'; + +import { UpdateListSchema } from '.'; + +export const getUpdateListSchemaMock = (): UpdateListSchema => ({ + _version: _VERSION, + description: DESCRIPTION, + id: LIST_ID, + meta: META, + name: NAME, +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + * after doing a get of the structure. + */ +export const getUpdateMinimalListSchemaMock = (): UpdateListSchema => ({ + description: DESCRIPTION, + id: LIST_ID, + name: NAME, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.ts new file mode 100644 index 000000000000..c35861f66e91 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { UpdateListSchema, updateListSchema } from '.'; +import { getUpdateListSchemaMock } from './index.mock'; + +describe('update_list_schema', () => { + test('it should validate a typical list request', () => { + const payload = getUpdateListSchemaMock(); + const decoded = updateListSchema.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 accept an undefined for "meta" but strip it out', () => { + const payload = getUpdateListSchemaMock(); + const outputPayload = getUpdateListSchemaMock(); + delete payload.meta; + const decoded = updateListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + delete outputPayload.meta; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(outputPayload); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: UpdateListSchema & { + extraKey?: string; + } = getUpdateListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = updateListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.ts new file mode 100644 index 000000000000..c6182af2f23f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/request/update_list_schema/index.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { version } from '@kbn/securitysolution-io-ts-types'; +import { RequiredKeepUndefined } from '../../common/required_keep_undefined'; +import { id } from '../../common/id'; +import { name } from '../../common/name'; +import { description } from '../../common/description'; +import { _version } from '../../common/underscore_version'; +import { meta } from '../../common/meta'; + +export const updateListSchema = t.intersection([ + t.exact( + t.type({ + description, + id, + name, + }) + ), + t.exact( + t.partial({ + _version, // defaults to undefined if not set during decode + meta, // defaults to undefined if not set during decode + version, // defaults to undefined if not set during decode + }) + ), +]); + +export type UpdateListSchema = t.OutputOf; +export type UpdateListSchemaDecoded = RequiredKeepUndefined>; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts new file mode 100644 index 000000000000..2c4ac68f4613 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.mock.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { AcknowledgeSchema } from '.'; + +export const getAcknowledgeSchemaResponseMock = (): AcknowledgeSchema => ({ + acknowledged: true, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.ts new file mode 100644 index 000000000000..4fd4adf861bb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getAcknowledgeSchemaResponseMock } from './index.mock'; +import { AcknowledgeSchema, acknowledgeSchema } from '.'; + +describe('acknowledge_schema', () => { + test('it should validate a typical response', () => { + const payload = getAcknowledgeSchemaResponseMock(); + const decoded = acknowledgeSchema.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 NOT accept an undefined for "ok"', () => { + const payload = getAcknowledgeSchemaResponseMock(); + // @ts-expect-error + delete payload.acknowledged; + const decoded = acknowledgeSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "acknowledged"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: AcknowledgeSchema & { extraKey?: string } = getAcknowledgeSchemaResponseMock(); + payload.extraKey = 'some new value'; + const decoded = acknowledgeSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts new file mode 100644 index 000000000000..97a0dc23682c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/acknowledge_schema/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const acknowledgeSchema = t.exact(t.type({ acknowledged: t.boolean })); + +export type AcknowledgeSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts new file mode 100644 index 000000000000..2ac63d9719e2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.test.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { CreateEndpointListSchema, createEndpointListSchema } from '.'; +import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; + +describe('create_endpoint_list_schema', () => { + test('it should validate a typical endpoint list response', () => { + const payload = getExceptionListSchemaMock(); + const decoded = createEndpointListSchema.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 accept an empty object when an endpoint list already exists', () => { + const payload: CreateEndpointListSchema = {}; + const decoded = createEndpointListSchema.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 NOT accept an undefined for "list_id"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'invalid keys "_version,created_at,created_by,description,id,immutable,meta,{},name,namespace_type,os_types,["linux"],tags,["user added string for a tag","malware"],tie_breaker_id,type,updated_at,updated_by,version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT allow missing fields', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors)).length).toEqual(1); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: CreateEndpointListSchema & { + extraKey?: string; + } = getExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts new file mode 100644 index 000000000000..44f3629973a0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/create_endpoint_list_schema/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { exceptionListSchema } from '../exception_list_schema'; + +export const createEndpointListSchema = t.union([exceptionListSchema, t.exact(t.type({}))]); + +export type CreateEndpointListSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..fad9dc5990a8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts @@ -0,0 +1,70 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + COMMENTS, + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + ENTRIES, + ITEM_ID, + ITEM_TYPE, + LIST_ID, + META, + NAME, + NAMESPACE_TYPE, + OS_TYPES, + TIE_BREAKER, + USER, +} from '../../constants/index.mock'; + +import { ExceptionListItemSchema } from '.'; + +export const getExceptionListItemSchemaMock = ( + overrides?: Partial +): ExceptionListItemSchema => ({ + _version: undefined, + comments: COMMENTS, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + entries: ENTRIES, + expire_time: undefined, + id: '1', + item_id: 'endpoint_list_item', + list_id: 'endpoint_list_id', + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: ['linux'], + tags: ['user added string for a tag', 'malware'], + tie_breaker_id: TIE_BREAKER, + type: ITEM_TYPE, + updated_at: DATE_NOW, + updated_by: USER, + ...(overrides || {}), +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = + (): Partial => ({ + comments: [], + created_by: ELASTIC_USER, + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + list_id: LIST_ID, + name: NAME, + namespace_type: 'single', + os_types: OS_TYPES, + tags: [], + type: ITEM_TYPE, + updated_by: ELASTIC_USER, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..1231764ae7f5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.test.ts @@ -0,0 +1,240 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getExceptionListItemSchemaMock } from './index.mock'; +import { ExceptionListItemSchema, exceptionListItemSchema } from '.'; + +describe('exception_list_item_schema', () => { + test('it should validate a typical exception list item response', () => { + const payload = getExceptionListItemSchemaMock(); + const decoded = exceptionListItemSchema.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 NOT accept an undefined for "id"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "list_id"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "item_id"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.item_id; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "item_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "comments"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.comments; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "comments"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "entries"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.entries; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "name"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "namespace_type" and return "single" as a default value for "namespace_type"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.namespace_type; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as ExceptionListItemSchema).namespace_type).toEqual('single'); + }); + + test('it should NOT accept an undefined for "description"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getExceptionListItemSchemaMock(); + delete payload.meta; + const decoded = exceptionListItemSchema.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 NOT accept an undefined for "created_at"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.created_at; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "created_by"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.created_by; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "tie_breaker_id"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.tie_breaker_id; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tie_breaker_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_at"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.updated_at; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_by"', () => { + const payload = getExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.updated_by; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ExceptionListItemSchema & { + extraKey?: string; + } = getExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = exceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts new file mode 100644 index 000000000000..f3f3986c4ea3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { namespace_type } from '../../common/namespace_type'; +import { metaOrUndefined } from '../../common/meta'; +import { name } from '../../common/name'; +import { created_at } from '../../common/created_at'; +import { created_by } from '../../common/created_by'; +import { id } from '../../common/id'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; +import { list_id } from '../../common/list_id'; +import { description } from '../../common/description'; +import { osTypeArray } from '../../common/os_type'; +import { tags } from '../../common/tags'; +import { _versionOrUndefined } from '../../common/underscore_version'; +import { commentsArray } from '../../common/comment'; +import { entriesArray } from '../../common/entries'; +import { item_id } from '../../common/item_id'; +import { exceptionListItemType } from '../../common/exception_list_item_type'; +import { expireTimeOrUndefined } from '../../common/expire_time'; + +export const exceptionListItemSchema = t.exact( + t.type({ + _version: _versionOrUndefined, + comments: commentsArray, + created_at, + created_by, + description, + entries: entriesArray, + expire_time: expireTimeOrUndefined, + id, + item_id, + list_id, + meta: metaOrUndefined, + name, + namespace_type, + os_types: osTypeArray, + tags, + tie_breaker_id, + type: exceptionListItemType, + updated_at, + updated_by, + }) +); + +export type ExceptionListItemSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..07b47f91fead --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + ENDPOINT_TYPE, + IMMUTABLE, + LIST_ID, + META, + NAME, + TIE_BREAKER, + USER, + VERSION, + _VERSION, +} from '../../constants/index.mock'; +import { + ENDPOINT_LIST_ID, + ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION, + ENDPOINT_TRUSTED_APPS_LIST_ID, + ENDPOINT_TRUSTED_APPS_LIST_NAME, +} from '@kbn/securitysolution-list-constants'; + +import { ExceptionListSchema } from '.'; + +export const getExceptionListSchemaMock = (): ExceptionListSchema => ({ + _version: _VERSION, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + id: '1', + immutable: IMMUTABLE, + list_id: ENDPOINT_LIST_ID, + meta: META, + name: 'Sample Endpoint Exception List', + namespace_type: 'agnostic', + os_types: ['linux'], + tags: ['user added string for a tag', 'malware'], + tie_breaker_id: TIE_BREAKER, + type: ENDPOINT_TYPE, + updated_at: DATE_NOW, + updated_by: 'user_name', + version: VERSION, +}); + +export const getTrustedAppsListSchemaMock = (): ExceptionListSchema => { + return { + ...getExceptionListSchemaMock(), + description: ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION, + list_id: ENDPOINT_TRUSTED_APPS_LIST_ID, + name: ENDPOINT_TRUSTED_APPS_LIST_NAME, + }; +}; + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getExceptionResponseMockWithoutAutoGeneratedValues = + (): Partial => ({ + created_by: ELASTIC_USER, + description: DESCRIPTION, + immutable: IMMUTABLE, + list_id: LIST_ID, + name: NAME, + namespace_type: 'single', + os_types: [], + tags: [], + type: ENDPOINT_TYPE, + updated_by: ELASTIC_USER, + version: VERSION, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts new file mode 100644 index 000000000000..b043cde4c3f0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.test.ts @@ -0,0 +1,198 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getExceptionListSchemaMock } from './index.mock'; +import { ExceptionListSchema, exceptionListSchema } from '.'; + +describe('exception_list_schema', () => { + test('it should validate a typical exception list response', () => { + const payload = getExceptionListSchemaMock(); + const decoded = exceptionListSchema.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 NOT accept an undefined for "id"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.id; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "list_id"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "name"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.name; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "namespace_type" and make "namespace_type" that of "single"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.namespace_type; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as ExceptionListSchema).namespace_type).toEqual('single'); + }); + + test('it should NOT accept an undefined for "description"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.description; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getExceptionListSchemaMock(); + delete payload.meta; + const decoded = exceptionListSchema.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 NOT accept an undefined for "created_at"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.created_at; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "created_by"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.created_by; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "tie_breaker_id"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.tie_breaker_id; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tie_breaker_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.type; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_at"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.updated_at; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_by"', () => { + const payload = getExceptionListSchemaMock(); + // @ts-expect-error + delete payload.updated_by; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ExceptionListSchema & { + extraKey?: string; + } = getExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = exceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts new file mode 100644 index 000000000000..e04eadb70765 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { version } from '@kbn/securitysolution-io-ts-types'; +import { _versionOrUndefined } from '../../common/underscore_version'; +import { namespace_type } from '../../common/namespace_type'; +import { metaOrUndefined } from '../../common/meta'; +import { name } from '../../common/name'; +import { created_at } from '../../common/created_at'; +import { created_by } from '../../common/created_by'; +import { id } from '../../common/id'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; +import { immutable } from '../../common/immutable'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; +import { list_id } from '../../common/list_id'; +import { description } from '../../common/description'; +import { osTypeArray } from '../../common/os_type'; +import { exceptionListType } from '../../common/exception_list'; +import { tags } from '../../common/tags'; + +export const exceptionListSchema = t.exact( + t.type({ + _version: _versionOrUndefined, + created_at, + created_by, + description, + id, + immutable, + list_id, + meta: metaOrUndefined, + name, + namespace_type, + os_types: osTypeArray, + tags, + tie_breaker_id, + type: exceptionListType, + updated_at, + updated_by, + version, + }) +); + +export type ExceptionListSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts new file mode 100644 index 000000000000..0acac1da648d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.mock.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExceptionListSummarySchema } from '.'; + +export const getListSummaryResponseMock = (): ExceptionListSummarySchema => ({ + windows: 0, + linux: 1, + macos: 2, + total: 3, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.test.ts new file mode 100644 index 000000000000..b4b6de2e25d1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.test.ts @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getListSummaryResponseMock } from './index.mock'; +import { ExceptionListSummarySchema, exceptionListSummarySchema } from '.'; + +describe('list_summary_schema', () => { + test('it should validate a typical list summary response', () => { + const payload = getListSummaryResponseMock(); + const decoded = exceptionListSummarySchema.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 NOT accept an undefined for "windows"', () => { + const payload = getListSummaryResponseMock(); + // @ts-expect-error + delete payload.windows; + const decoded = exceptionListSummarySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "windows"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "linux"', () => { + const payload = getListSummaryResponseMock(); + // @ts-expect-error + delete payload.linux; + const decoded = exceptionListSummarySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "linux"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "macos"', () => { + const payload = getListSummaryResponseMock(); + // @ts-expect-error + delete payload.macos; + const decoded = exceptionListSummarySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "macos"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "total"', () => { + const payload = getListSummaryResponseMock(); + // @ts-expect-error + delete payload.total; + const decoded = exceptionListSummarySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "total"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ExceptionListSummarySchema & { + extraKey?: string; + } = getListSummaryResponseMock(); + payload.extraKey = 'some new value'; + const decoded = exceptionListSummarySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts new file mode 100644 index 000000000000..7414ca257fbd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_summary_schema/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; +import * as t from 'io-ts'; + +export const exceptionListSummarySchema = t.exact( + t.type({ + windows: PositiveInteger, + linux: PositiveInteger, + macos: PositiveInteger, + total: PositiveInteger, + }) +); + +export type ExceptionListSummarySchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts new file mode 100644 index 000000000000..75330f493743 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundAllListItemsSchema } from '.'; +import { getListItemResponseMock } from '../list_item_schema/index.mock'; + +export const getFoundAllListItemsSchemaMock = (): FoundAllListItemsSchema => ({ + data: [getListItemResponseMock()], + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts new file mode 100644 index 000000000000..c5812499b3e7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_all_list_items_schema/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { listItemSchema } from '../list_item_schema'; +import { total } from '../../common/total'; + +export const foundAllListItemsSchema = t.exact( + t.type({ + data: t.array(listItemSchema), + total, + }) +); + +export type FoundAllListItemsSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..6f8592320895 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundExceptionListItemSchema } from '.'; +import { getExceptionListItemSchemaMock } from '../exception_list_item_schema/index.mock'; + +export const getFoundExceptionListItemSchemaMock = (): FoundExceptionListItemSchema => ({ + data: [getExceptionListItemSchemaMock()], + page: 1, + per_page: 1, + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts new file mode 100644 index 000000000000..33d26ca32a5b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.test.ts @@ -0,0 +1,152 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getFoundExceptionListItemSchemaMock } from './index.mock'; +import { FoundExceptionListItemSchema, foundExceptionListItemSchema } from '.'; +import { ExceptionListItemSchema } from '../exception_list_item_schema'; +import { getExceptionListItemSchemaMock } from '../exception_list_item_schema/index.mock'; + +describe('found_exception_list_item_schema', () => { + test('it should validate a typical exception list response', () => { + const payload = getFoundExceptionListItemSchemaMock(); + const decoded = foundExceptionListItemSchema.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 NOT accept a malformed exception list item within "data"', () => { + const item: Omit & { + entries?: string; + } = { ...getExceptionListItemSchemaMock(), entries: 'I should be an array' }; + const payload: Omit & { + data?: Array< + Omit & { + entries?: string; + } + >; + } = { ...getFoundExceptionListItemSchemaMock(), data: [item] }; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "I should be an array" supplied to "data,entries"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "page"', () => { + const payload: Omit & { + page?: string; + } = { ...getFoundExceptionListItemSchemaMock(), page: '1' }; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "page"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "per_page"', () => { + const payload: Omit & { + per_page?: string; + } = { ...getFoundExceptionListItemSchemaMock(), per_page: '20' }; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "20" supplied to "per_page"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "total"', () => { + const payload: Omit & { + total?: string; + } = { ...getFoundExceptionListItemSchemaMock(), total: '1' }; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "total"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "page"', () => { + const payload = getFoundExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.page; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "page"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "per_page"', () => { + const payload = getFoundExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.per_page; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "per_page"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "total"', () => { + const payload = getFoundExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.total; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "total"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "data"', () => { + const payload = getFoundExceptionListItemSchemaMock(); + // @ts-expect-error + delete payload.data; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "data"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FoundExceptionListItemSchema & { + extraKey?: string; + } = getFoundExceptionListItemSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = foundExceptionListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.ts new file mode 100644 index 000000000000..50f57bf42459 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_item_schema/index.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { page } from '../../common/page'; +import { per_page } from '../../common/per_page'; +import { pitId } from '../../common/pit'; +import { total } from '../../common/total'; +import { exceptionListItemSchema } from '../exception_list_item_schema'; + +export const foundExceptionListItemSchema = t.intersection([ + t.exact( + t.type({ + data: t.array(exceptionListItemSchema), + page, + per_page, + total, + }) + ), + t.exact( + t.partial({ + pit: pitId, + }) + ), +]); + +export type FoundExceptionListItemSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts new file mode 100644 index 000000000000..8a6d9fe2d2a7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.mock.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundExceptionListSchema } from '.'; +import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; + +export const getFoundExceptionListSchemaMock = (): FoundExceptionListSchema => ({ + data: [getExceptionListSchemaMock()], + page: 1, + per_page: 1, + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts new file mode 100644 index 000000000000..18d96785ad2e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.test.ts @@ -0,0 +1,152 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license 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 } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getFoundExceptionListSchemaMock } from './index.mock'; +import { FoundExceptionListSchema, foundExceptionListSchema } from '.'; +import { getExceptionListSchemaMock } from '../exception_list_schema/index.mock'; +import { ExceptionListSchema } from '../exception_list_schema'; + +describe('exception_list_schema', () => { + test('it should validate a typical exception list response', () => { + const payload = getFoundExceptionListSchemaMock(); + const decoded = foundExceptionListSchema.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 NOT accept a malformed exception list item within "data"', () => { + const item: Omit & { + entries?: string[]; + } = { ...getExceptionListSchemaMock(), entries: ['I should not be here'] }; + const payload: Omit & { + data?: Array< + Omit & { + entries?: string[]; + } + >; + } = { ...getFoundExceptionListSchemaMock(), data: [item] }; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'invalid keys "entries,["I should not be here"]"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "page"', () => { + const payload: Omit & { + page?: string; + } = { ...getFoundExceptionListSchemaMock(), page: '1' }; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "page"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "per_page"', () => { + const payload: Omit & { + per_page?: string; + } = { ...getFoundExceptionListSchemaMock(), per_page: '20' }; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "20" supplied to "per_page"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept a string for "total"', () => { + const payload: Omit & { + total?: string; + } = { ...getFoundExceptionListSchemaMock(), total: '1' }; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "total"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "page"', () => { + const payload = getFoundExceptionListSchemaMock(); + // @ts-expect-error + delete payload.page; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "page"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "per_page"', () => { + const payload = getFoundExceptionListSchemaMock(); + // @ts-expect-error + delete payload.per_page; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "per_page"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "total"', () => { + const payload = getFoundExceptionListSchemaMock(); + // @ts-expect-error + delete payload.total; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "total"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "data"', () => { + const payload = getFoundExceptionListSchemaMock(); + // @ts-expect-error + delete payload.data; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "data"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: FoundExceptionListSchema & { + extraKey?: string; + } = getFoundExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = foundExceptionListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts new file mode 100644 index 000000000000..cb7867db7f29 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_exception_list_schema/index.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { page } from '../../common/page'; +import { per_page } from '../../common/per_page'; +import { pitId } from '../../common/pit'; +import { total } from '../../common/total'; + +import { exceptionListSchema } from '../exception_list_schema'; + +export const foundExceptionListSchema = t.intersection([ + t.exact( + t.type({ + data: t.array(exceptionListSchema), + page, + per_page, + total, + }) + ), + t.exact(t.partial({ pit: pitId })), +]); + +export type FoundExceptionListSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..bc6c6b63dbea --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundListItemSchema } from '.'; +import { getListItemResponseMock } from '../list_item_schema/index.mock'; + +export const getFoundListItemSchemaMock = (): FoundListItemSchema => ({ + cursor: 'WzI1LFsiNmE3NmI2OWQtODBkZi00YWIyLThjM2UtODVmNDY2YjA2YTBlIl1d', + data: [getListItemResponseMock()], + page: 1, + per_page: 25, + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.ts new file mode 100644 index 000000000000..86801ed60bca --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_item_schema/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { listItemSchema } from '../list_item_schema'; +import { cursor } from '../../common/cursor'; +import { page } from '../../common/page'; +import { per_page } from '../../common/per_page'; +import { total } from '../../common/total'; + +export const foundListItemSchema = t.exact( + t.type({ + cursor, + data: t.array(listItemSchema), + page, + per_page, + total, + }) +); + +export type FoundListItemSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts new file mode 100644 index 000000000000..07cbb1d03000 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.mock.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundListSchema } from '.'; +import { getListResponseMock } from '../list_schema/index.mock'; + +export const getFoundListSchemaMock = (): FoundListSchema => ({ + cursor: '123', + data: [getListResponseMock()], + page: 1, + per_page: 1, + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.ts new file mode 100644 index 000000000000..16922174e749 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_list_schema/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { listSchema } from '../list_schema'; +import { cursor } from '../../common/cursor'; +import { page } from '../../common/page'; +import { per_page } from '../../common/per_page'; +import { total } from '../../common/total'; + +export const foundListSchema = t.exact( + t.type({ + cursor, + data: t.array(listSchema), + page, + per_page, + total, + }) +); + +export type FoundListSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts new file mode 100644 index 000000000000..8d1a421acef2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.mock.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FoundListsBySizeSchema } from '.'; +import { getListResponseMock } from '../list_schema/index.mock'; + +export const getFoundListsBySizeSchemaMock = (): FoundListsBySizeSchema => ({ + smallLists: [getListResponseMock()], + largeLists: [getListResponseMock()], +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/index.ts new file mode 100644 index 000000000000..0271416b5f3c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/found_lists_by_size_schema/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { listSchema } from '../list_schema'; + +export const foundListsBySizeSchema = t.exact( + t.type({ + largeLists: t.array(listSchema), + smallLists: t.array(listSchema), + }) +); + +export type FoundListsBySizeSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.ts new file mode 100644 index 000000000000..9e8293b382cc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.mock.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ImportExceptionsResponseSchema } from '.'; + +export const getImportExceptionsResponseSchemaMock = ( + success = 0, + lists = 0, + items = 0 +): ImportExceptionsResponseSchema => ({ + errors: [], + success: true, + success_count: success, + success_exception_lists: true, + success_count_exception_lists: lists, + success_exception_list_items: true, + success_count_exception_list_items: items, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts new file mode 100644 index 000000000000..d5d481fe87be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.test.ts @@ -0,0 +1,128 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { importExceptionsResponseSchema, ImportExceptionsResponseSchema } from '.'; +import { getImportExceptionsResponseSchemaMock } from './index.mock'; + +describe('importExceptionsResponseSchema', () => { + test('it should validate a typical exceptions import response', () => { + const payload = getImportExceptionsResponseSchemaMock(); + const decoded = importExceptionsResponseSchema.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 NOT accept an undefined for "errors"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.errors; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "errors"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success_count"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success_count; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success_count"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success_exception_lists"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success_exception_lists; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success_exception_lists"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success_count_exception_lists"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success_count_exception_lists; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success_count_exception_lists"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success_exception_list_items"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success_exception_list_items; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success_exception_list_items"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "success_count_exception_list_items"', () => { + const payload: Partial> = + getImportExceptionsResponseSchemaMock(); + delete payload.success_count_exception_list_items; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "success_count_exception_list_items"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ImportExceptionsResponseSchema & { + extraKey?: string; + } = getImportExceptionsResponseSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = importExceptionsResponseSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts new file mode 100644 index 000000000000..4a172d2ec10a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/import_exceptions_schema/index.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; + +import { id } from '../../common/id'; +import { list_id } from '../../common/list_id'; +import { item_id } from '../../common/item_id'; + +export const bulkErrorErrorSchema = t.exact( + t.type({ + status_code: t.number, + message: t.string, + }) +); + +export const bulkErrorSchema = t.intersection([ + t.exact( + t.type({ + error: bulkErrorErrorSchema, + }) + ), + t.partial({ + id, + list_id, + item_id, + }), +]); + +export type BulkErrorSchema = t.TypeOf; + +export const importExceptionsResponseSchema = t.exact( + t.type({ + errors: t.array(bulkErrorSchema), + success: t.boolean, + success_count: PositiveInteger, + success_exception_lists: t.boolean, + success_count_exception_lists: PositiveInteger, + success_exception_list_items: t.boolean, + success_count_exception_list_items: PositiveInteger, + }) +); + +export type ImportExceptionsResponseSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/index.ts new file mode 100644 index 000000000000..04b00f43c702 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './acknowledge_schema'; +export * from './create_endpoint_list_schema'; +export * from './exception_list_schema'; +export * from './exception_list_item_schema'; +export * from './found_exception_list_item_schema'; +export * from './found_exception_list_schema'; +export * from './found_all_list_items_schema'; +export * from './found_lists_by_size_schema'; +export * from './found_list_item_schema'; +export * from './found_list_schema'; +export * from './import_exceptions_schema'; +export * from './list_item_schema'; +export * from './list_schema'; +export * from './exception_list_summary_schema'; +export * from './list_item_index_exist_schema'; +export * from './search_list_item_schema'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts new file mode 100644 index 000000000000..b3416ab76852 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.mock.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ListItemIndexExistSchema } from '.'; + +export const getListItemIndexExistSchemaResponseMock = (): ListItemIndexExistSchema => ({ + list_index: true, + list_item_index: true, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts new file mode 100644 index 000000000000..0c8812795935 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.test.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getListItemIndexExistSchemaResponseMock } from './index.mock'; +import { ListItemIndexExistSchema, listItemIndexExistSchema } from '.'; + +describe('list_item_index_exist_schema', () => { + test('it should validate a typical list item request', () => { + const payload = getListItemIndexExistSchemaResponseMock(); + const decoded = listItemIndexExistSchema.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 NOT accept an undefined for "list_index"', () => { + const payload = getListItemIndexExistSchemaResponseMock(); + // @ts-expect-error + delete payload.list_index; + const decoded = listItemIndexExistSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_index"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "list_item_index"', () => { + const payload = getListItemIndexExistSchemaResponseMock(); + // @ts-expect-error + delete payload.list_item_index; + const decoded = listItemIndexExistSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_item_index"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ListItemIndexExistSchema & { + extraKey?: string; + } = getListItemIndexExistSchemaResponseMock(); + payload.extraKey = 'some new value'; + const decoded = listItemIndexExistSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts new file mode 100644 index 000000000000..fb1070f72dae --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_index_exist_schema/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +export const listItemIndexExistSchema = t.exact( + t.type({ + list_index: t.boolean, + list_item_index: t.boolean, + }) +); + +export type ListItemIndexExistSchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.ts new file mode 100644 index 000000000000..10283965276d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.mock.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ListItemSchema } from '.'; +import { + DATE_NOW, + ELASTIC_USER, + LIST_ID, + LIST_ITEM_ID, + META, + TIE_BREAKER, + TYPE, + USER, + VALUE, +} from '../../constants/index.mock'; + +export const getListItemResponseMock = (): ListItemSchema => ({ + _version: undefined, + '@timestamp': DATE_NOW, + created_at: DATE_NOW, + created_by: USER, + deserializer: undefined, + id: LIST_ITEM_ID, + list_id: LIST_ID, + meta: META, + serializer: undefined, + tie_breaker_id: TIE_BREAKER, + type: TYPE, + updated_at: DATE_NOW, + updated_by: USER, + value: VALUE, +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getListItemResponseMockWithoutAutoGeneratedValues = (): Partial => ({ + created_by: ELASTIC_USER, + list_id: LIST_ID, + type: TYPE, + updated_by: ELASTIC_USER, + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts new file mode 100644 index 000000000000..f855448ff26e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.test.ts @@ -0,0 +1,192 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getListItemResponseMock } from './index.mock'; +import { ListItemSchema, listItemSchema } from '.'; + +describe('list_item_schema', () => { + test('it should validate a typical list item response', () => { + const payload = getListItemResponseMock(); + const decoded = listItemSchema.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 NOT accept an undefined for "id"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.id; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "list_id"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.list_id; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "list_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getListItemResponseMock(); + delete payload.meta; + const decoded = listItemSchema.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 accept an undefined for "serializer"', () => { + const payload = getListItemResponseMock(); + delete payload.serializer; + const decoded = listItemSchema.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 accept an undefined for "deserializer"', () => { + const payload = getListItemResponseMock(); + delete payload.deserializer; + const decoded = listItemSchema.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 NOT accept an undefined for "created_at"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.created_at; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "created_by"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.created_by; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "tie_breaker_id"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.tie_breaker_id; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tie_breaker_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.type; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_at"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.updated_at; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_by"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.updated_by; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "value"', () => { + const payload = getListItemResponseMock(); + // @ts-expect-error + delete payload.value; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "value"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ListItemSchema & { extraKey?: string } = getListItemResponseMock(); + payload.extraKey = 'some new value'; + const decoded = listItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.ts new file mode 100644 index 000000000000..0e7af6ab2726 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_item_schema/index.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; + +import { _versionOrUndefined } from '../../common/underscore_version'; +import { deserializerOrUndefined } from '../../common/deserializer'; +import { metaOrUndefined } from '../../common/meta'; +import { timestampOrUndefined } from '../../common/timestamp'; +import { serializerOrUndefined } from '../../common/serializer'; +import { created_at } from '../../common/created_at'; +import { created_by } from '../../common/created_by'; +import { id } from '../../common/id'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; +import { type } from '../../common/type'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; +import { list_id } from '../../common/list_id'; +import { value } from '../../common/value'; + +export const listItemSchema = t.exact( + t.type({ + _version: _versionOrUndefined, + '@timestamp': timestampOrUndefined, + created_at, + created_by, + deserializer: deserializerOrUndefined, + id, + list_id, + meta: metaOrUndefined, + serializer: serializerOrUndefined, + tie_breaker_id, + type, + updated_at, + updated_by, + value, + }) +); + +export type ListItemSchema = t.TypeOf; + +export const listItemArraySchema = t.array(listItemSchema); +export type ListItemArraySchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts new file mode 100644 index 000000000000..3b6ff22ceb15 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.mock.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ListSchema } from '.'; +import { + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + IMMUTABLE, + LIST_ID, + META, + NAME, + TIE_BREAKER, + TYPE, + USER, + VERSION, +} from '../../constants/index.mock'; + +export const getListResponseMock = (): ListSchema => ({ + _version: undefined, + '@timestamp': DATE_NOW, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + deserializer: undefined, + id: LIST_ID, + immutable: IMMUTABLE, + meta: META, + name: NAME, + serializer: undefined, + tie_breaker_id: TIE_BREAKER, + type: TYPE, + updated_at: DATE_NOW, + updated_by: USER, + version: VERSION, +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ + created_by: ELASTIC_USER, + description: DESCRIPTION, + immutable: IMMUTABLE, + name: NAME, + type: TYPE, + updated_by: ELASTIC_USER, + version: VERSION, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts new file mode 100644 index 000000000000..920941a2135a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.test.ts @@ -0,0 +1,192 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getListResponseMock } from './index.mock'; +import { ListSchema, listSchema } from '.'; + +describe('list_schema', () => { + test('it should validate a typical list response', () => { + const payload = getListResponseMock(); + const decoded = listSchema.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 NOT accept an undefined for "id"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.id; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should accept an undefined for "meta"', () => { + const payload = getListResponseMock(); + delete payload.meta; + const decoded = listSchema.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 accept an undefined for "serializer"', () => { + const payload = getListResponseMock(); + delete payload.serializer; + const decoded = listSchema.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 accept an undefined for "deserializer"', () => { + const payload = getListResponseMock(); + delete payload.deserializer; + const decoded = listSchema.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 NOT accept an undefined for "created_at"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.created_at; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "created_by"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.created_by; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "created_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "tie_breaker_id"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.tie_breaker_id; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tie_breaker_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "type"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.type; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_at"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.updated_at; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "updated_by"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.updated_by; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "updated_by"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "name"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.name; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "name"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT accept an undefined for "description"', () => { + const payload = getListResponseMock(); + // @ts-expect-error + delete payload.description; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: ListSchema & { extraKey?: string } = getListResponseMock(); + payload.extraKey = 'some new value'; + const decoded = listSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts new file mode 100644 index 000000000000..687c93ad6f6d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/list_schema/index.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { version } from '@kbn/securitysolution-io-ts-types'; +import { _versionOrUndefined } from '../../common/underscore_version'; +import { deserializerOrUndefined } from '../../common/deserializer'; +import { metaOrUndefined } from '../../common/meta'; +import { serializerOrUndefined } from '../../common/serializer'; +import { created_at } from '../../common/created_at'; +import { timestampOrUndefined } from '../../common/timestamp'; +import { created_by } from '../../common/created_by'; +import { description } from '../../common/description'; +import { id } from '../../common/id'; +import { immutable } from '../../common/immutable'; +import { name } from '../../common/name'; +import { tie_breaker_id } from '../../common/tie_breaker_id'; +import { type } from '../../common/type'; +import { updated_at } from '../../common/updated_at'; +import { updated_by } from '../../common/updated_by'; + +export const listSchema = t.exact( + t.type({ + _version: _versionOrUndefined, + '@timestamp': timestampOrUndefined, + created_at, + created_by, + description, + deserializer: deserializerOrUndefined, + id, + immutable, + meta: metaOrUndefined, + name, + serializer: serializerOrUndefined, + tie_breaker_id, + type, + updated_at, + updated_by, + version, + }) +); + +export type ListSchema = t.TypeOf; + +export const listArraySchema = t.array(listSchema); +export type ListArraySchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts new file mode 100644 index 000000000000..1ce8e23d4af5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.mock.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { SearchListItemSchema } from '.'; +import { VALUE } from '../../constants/index.mock'; +import { getListItemResponseMock } from '../list_item_schema/index.mock'; + +export const getSearchListItemResponseMock = (): SearchListItemSchema => ({ + items: [getListItemResponseMock()], + value: VALUE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.test.ts new file mode 100644 index 000000000000..6f89a58e0bc3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.test.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { getSearchListItemResponseMock } from './index.mock'; +import { SearchListItemSchema, searchListItemSchema } from '.'; + +describe('search_list_item_schema', () => { + test('it should validate a typical search list item response', () => { + const payload = getSearchListItemResponseMock(); + const decoded = searchListItemSchema.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 NOT validate with an "undefined" for "items"', () => { + const { items, ...noItems } = getSearchListItemResponseMock(); + const decoded = searchListItemSchema.decode(noItems); + const checked = exactCheck(noItems, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "items"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: SearchListItemSchema & { extraKey?: string } = getSearchListItemResponseMock(); + payload.extraKey = 'some new value'; + const decoded = searchListItemSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.ts new file mode 100644 index 000000000000..8c17db076500 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/response/search_list_item_schema/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { listItemArraySchema } from '../list_item_schema'; + +/** + * NOTE: Although this is defined within "response" this does not expose a REST API + * endpoint right now for this particular response. Instead this is only used internally + * for the plugins at this moment. If this changes, please remove this message. + */ +export const searchListItemSchema = t.exact( + t.type({ + items: listItemArraySchema, + value: t.unknown, + }) +); + +export type SearchListItemSchema = t.TypeOf; + +export const searchListItemArraySchema = t.array(searchListItemSchema); +export type SearchListItemArraySchema = t.TypeOf; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts new file mode 100644 index 000000000000..8b172753bbc5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/src/typescript_types/index.ts @@ -0,0 +1,242 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { HttpStart } from '@kbn/core-http-browser'; +import type { NotificationsStart } from '@kbn/core-notifications-browser'; +import type { Filter } from '@kbn/es-query'; +import { NamespaceType } from '../common/default_namespace'; +import { ExceptionListType, ExceptionListTypeEnum } from '../common/exception_list'; +import { Page } from '../common/page'; +import { PerPage } from '../common/per_page'; +import { TotalOrUndefined } from '../common/total'; +import { CreateExceptionListItemSchema } from '../request/create_exception_list_item_schema'; +import { CreateExceptionListSchema } from '../request/create_exception_list_schema'; +import { ExceptionListId } from '../request/get_exception_filter_schema'; +import { UpdateExceptionListItemSchema } from '../request/update_exception_list_item_schema'; +import { UpdateExceptionListSchema } from '../request/update_exception_list_schema'; +import { ExceptionListItemSchema } from '../response/exception_list_item_schema'; +import { ExceptionListSchema } from '../response/exception_list_schema'; + +interface BaseParams { + http: HttpStart; + signal: AbortSignal; +} + +export interface DuplicateExceptionListProps extends BaseParams { + listId: string; + namespaceType: NamespaceType; + includeExpiredExceptions: boolean; +} + +export interface ApiListDuplicateProps + extends Omit { + onError: (err: Error) => void; + onSuccess: (newList: ExceptionListSchema) => void; +} + +export interface ExceptionListFilter { + name?: string | null; + list_id?: string | null; + created_by?: string | null; + types?: ExceptionListTypeEnum[] | null; + tags?: string | null; +} + +export interface UseExceptionListsProps { + errorMessage: string; + filterOptions?: ExceptionListFilter; + http: HttpStart; + namespaceTypes: NamespaceType[]; + notifications: NotificationsStart; + initialPagination?: Pagination; + hideLists?: readonly string[]; + initialSort?: Sort; +} + +export interface UseExceptionListProps { + http: HttpStart; + lists: ExceptionListIdentifiers[]; + onError?: (arg: string[]) => void; + filterOptions: FilterExceptionsOptions[]; + pagination?: Pagination; + showDetectionsListsOnly: boolean; + showEndpointListsOnly: boolean; + matchFilters: boolean; + onSuccess?: (arg: UseExceptionListItemsSuccess) => void; + sort?: Sort; +} + +export interface FilterExceptionsOptions { + filter: string; + tags: string[]; +} + +export interface ApiCallMemoProps { + id: string; + namespaceType: NamespaceType; + onError: (arg: Error) => void; + onSuccess: () => void; +} + +// TODO: Switch to use ApiCallMemoProps +// after cleaning up exceptions/api file to +// remove unnecessary validation checks +export interface ApiListExportProps { + id: string; + includeExpiredExceptions: boolean; + listId: string; + namespaceType: NamespaceType; + onError: (err: Error) => void; + onSuccess: (blob: Blob) => void; +} + +export interface Sort { + field: string; + order: string; +} +export interface Pagination { + page: Page; + perPage: PerPage; + total: TotalOrUndefined; +} + +export interface UseExceptionListItemsSuccess { + exceptions: ExceptionListItemSchema[]; + pagination: Pagination; +} + +export interface ExceptionListIdentifiers { + id: string; + listId: string; + namespaceType: NamespaceType; + type: ExceptionListType; +} + +export interface ApiCallFindListsItemsMemoProps { + lists: ExceptionListIdentifiers[]; + pagination: Partial; + showDetectionsListsOnly: boolean; + showEndpointListsOnly: boolean; + filter?: string; + onError: (arg: string[]) => void; + onSuccess: (arg: UseExceptionListItemsSuccess) => void; +} + +export interface ApiCallGetExceptionFilterFromIdsMemoProps extends GetExceptionFilterOptionalProps { + exceptionListIds: ExceptionListId[]; + onError: (arg: string[]) => void; + onSuccess: (arg: Filter) => void; +} + +export interface ApiCallGetExceptionFilterFromExceptionsMemoProps + extends GetExceptionFilterOptionalProps { + exceptions: Array; + onError: (arg: string[]) => void; + onSuccess: (arg: Filter) => void; +} + +export interface ExportExceptionListProps { + http: HttpStart; + id: string; + listId: string; + namespaceType: NamespaceType; + includeExpiredExceptions: boolean; + signal: AbortSignal; +} + +export interface AddEndpointExceptionListProps { + http: HttpStart; + signal: AbortSignal; +} + +export interface UpdateExceptionListItemProps { + http: HttpStart; + listItem: UpdateExceptionListItemSchema; + signal: AbortSignal; +} + +export interface UpdateExceptionListProps { + http: HttpStart; + list: UpdateExceptionListSchema; + signal: AbortSignal; +} + +export interface AddExceptionListItemProps { + http: HttpStart; + listItem: CreateExceptionListItemSchema; + signal: AbortSignal; +} + +export interface AddExceptionListProps { + http: HttpStart; + list: CreateExceptionListSchema; + signal: AbortSignal; +} + +export interface UseExceptionListsSuccess { + exceptions: ExceptionListSchema[]; + pagination: Pagination; +} + +export interface ApiCallFetchExceptionListsProps { + http: HttpStart; + namespaceTypes: string; + pagination: Partial; + sort?: Sort; + filters: string; + signal: AbortSignal; +} + +export interface ApiCallByIdProps { + http: HttpStart; + id: string; + namespaceType: NamespaceType; + signal: AbortSignal; +} + +export interface ApiCallByListIdProps { + http: HttpStart; + listIds: string[]; + namespaceTypes: NamespaceType[]; + pagination: Partial; + search?: string; + filter?: string; + signal: AbortSignal; +} + +export type AddExceptionList = UpdateExceptionListSchema | CreateExceptionListSchema; + +export interface PersistHookProps { + http: HttpStart; + onError: (arg: Error) => void; +} + +export interface ExceptionList extends ExceptionListSchema { + totalItems: number; +} + +export interface GetExceptionFilterOptionalProps { + signal?: AbortSignal; + chunkSize?: number; + alias?: string; + excludeExceptions?: boolean; +} + +export interface GetExceptionFilterFromExceptionListIdsProps + extends GetExceptionFilterOptionalProps { + http: HttpStart; + exceptionListIds: ExceptionListId[]; +} + +export interface GetExceptionFilterFromExceptionsProps extends GetExceptionFilterOptionalProps { + http: HttpStart; + exceptions: Array; +} + +export interface ExceptionFilterResponse { + filter: Filter; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json new file mode 100644 index 000000000000..b8097b0b7b12 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/securitysolution-io-ts-types", + "@kbn/securitysolution-io-ts-utils", + "@kbn/securitysolution-list-constants", + "@kbn/es-query", + "@kbn/core-http-browser", + "@kbn/core-notifications-browser", + "@kbn/securitysolution-exceptions-common" + ], + "exclude": ["target/**/*"] +} diff --git a/packages/kbn-securitysolution-list-api/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/README.md similarity index 100% rename from packages/kbn-securitysolution-list-api/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-list-api/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/index.ts new file mode 100644 index 000000000000..afe1280b9b85 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/api'; +export * from './src/fp_utils'; +export * from './src/list_api'; +export * from './src/list_item_api'; +export * from './src/types'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/jest.config.js new file mode 100644 index 000000000000..9e9844e5cbd0 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-list-api'], +}; diff --git a/packages/kbn-securitysolution-list-api/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-list-api/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-list-api/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/package.json new file mode 100644 index 000000000000..5159b04f6204 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/package.json @@ -0,0 +1,7 @@ +{ + "name": "@kbn/securitysolution-list-api", + "version": "1.0.0", + "description": "security solution list REST API", + "license": "Elastic License 2.0", + "private": true +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/api/index.ts new file mode 100644 index 000000000000..c8fe4143d1bd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/api/index.ts @@ -0,0 +1,664 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { chain, fromEither, tryCatch } from 'fp-ts/lib/TaskEither'; +import { flow } from 'fp-ts/lib/function'; +import { validateEither } from '@kbn/securitysolution-io-ts-utils'; +import { + CreateEndpointListSchema, + ExceptionListItemSchema, + ExceptionListSchema, + FoundExceptionListItemSchema, + FoundExceptionListSchema, + createEndpointListSchema, + exceptionListItemSchema, + exceptionListSchema, + foundExceptionListItemSchema, + foundExceptionListSchema, + AddEndpointExceptionListProps, + AddExceptionListItemProps, + AddExceptionListProps, + ApiCallByIdProps, + ApiCallByListIdProps, + ApiCallFetchExceptionListsProps, + ExportExceptionListProps, + UpdateExceptionListItemProps, + UpdateExceptionListProps, + GetExceptionFilterFromExceptionListIdsProps, + GetExceptionFilterFromExceptionsProps, + ExceptionFilterResponse, + DuplicateExceptionListProps, +} from '@kbn/securitysolution-io-ts-list-types'; + +import { + ENDPOINT_LIST_URL, + INTERNAL_EXCEPTION_FILTER, + EXCEPTION_LIST_ITEM_URL, + EXCEPTION_LIST_URL, +} from '@kbn/securitysolution-list-constants'; +import { toError, toPromise } from '../fp_utils'; + +const version = '2023-10-31'; + +/** + * Add new ExceptionList + * + * @param http Kibana http service + * @param list exception list to add + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +const addExceptionList = async ({ + http, + list, + signal, +}: AddExceptionListProps): Promise => + http.fetch(EXCEPTION_LIST_URL, { + body: JSON.stringify(list), + method: 'POST', + signal, + version, + }); + +const addExceptionListWithValidation = async ({ + http, + list, + signal, +}: AddExceptionListProps): Promise => + flow( + () => + tryCatch( + () => + addExceptionList({ + http, + list, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(exceptionListSchema, response))), + flow(toPromise) + )(); + +export { addExceptionListWithValidation as addExceptionList }; + +/** + * Add new ExceptionListItem + * + * @param http Kibana http service + * @param listItem exception list item to add + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +const addExceptionListItem = async ({ + http, + listItem, + signal, +}: AddExceptionListItemProps): Promise => + http.fetch(EXCEPTION_LIST_ITEM_URL, { + body: JSON.stringify(listItem), + method: 'POST', + signal, + version, + }); + +const addExceptionListItemWithValidation = async ({ + http, + listItem, + signal, +}: AddExceptionListItemProps): Promise => + flow( + () => + tryCatch( + () => + addExceptionListItem({ + http, + listItem, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), + flow(toPromise) + )(); + +export { addExceptionListItemWithValidation as addExceptionListItem }; + +/** + * Update existing ExceptionList + * + * @param http Kibana http service + * @param list exception list to add + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +const updateExceptionList = async ({ + http, + list, + signal, +}: UpdateExceptionListProps): Promise => + http.fetch(EXCEPTION_LIST_URL, { + body: JSON.stringify(list), + method: 'PUT', + signal, + version, + }); + +const updateExceptionListWithValidation = async ({ + http, + list, + signal, +}: UpdateExceptionListProps): Promise => + flow( + () => + tryCatch( + () => + updateExceptionList({ + http, + list, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(exceptionListSchema, response))), + flow(toPromise) + )(); + +export { updateExceptionListWithValidation as updateExceptionList }; + +/** + * Update existing ExceptionListItem + * + * @param http Kibana http service + * @param listItem exception list item to add + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +const updateExceptionListItem = async ({ + http, + listItem, + signal, +}: UpdateExceptionListItemProps): Promise => + http.fetch(EXCEPTION_LIST_ITEM_URL, { + body: JSON.stringify(listItem), + method: 'PUT', + signal, + version, + }); + +const updateExceptionListItemWithValidation = async ({ + http, + listItem, + signal, +}: UpdateExceptionListItemProps): Promise => + flow( + () => + tryCatch( + () => + updateExceptionListItem({ + http, + listItem, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), + flow(toPromise) + )(); + +export { updateExceptionListItemWithValidation as updateExceptionListItem }; + +/** + * Fetch all ExceptionLists (optionally by namespaceType) + * + * @param http Kibana http service + * @param namespaceTypes ExceptionList namespace_types of lists to find + * @param filters search bar filters + * @param pagination optional + * @param signal to cancel request + * + * @throws An error if request params or response is not OK + */ +const fetchExceptionLists = async ({ + http, + filters, + namespaceTypes, + pagination, + signal, + sort, +}: ApiCallFetchExceptionListsProps): Promise => { + const query = { + filter: filters || undefined, + namespace_type: namespaceTypes, + page: pagination.page ? `${pagination.page}` : '1', + per_page: pagination.perPage ? `${pagination.perPage}` : '20', + sort_field: sort?.field ? sort?.field : 'exception-list.created_at', + sort_order: sort?.order ? sort?.order : 'desc', + }; + + return http.fetch(`${EXCEPTION_LIST_URL}/_find`, { + method: 'GET', + query, + signal, + version, + }); +}; + +const fetchExceptionListsWithValidation = async ({ + filters, + http, + namespaceTypes, + pagination, + signal, + sort, +}: ApiCallFetchExceptionListsProps): Promise => + flow( + () => + tryCatch( + () => + fetchExceptionLists({ + filters, + http, + namespaceTypes, + pagination, + signal, + sort, + }), + toError + ), + chain((response) => fromEither(validateEither(foundExceptionListSchema, response))), + flow(toPromise) + )(); + +export { fetchExceptionListsWithValidation as fetchExceptionLists }; + +/** + * Fetch an ExceptionList by providing a ExceptionList ID + * + * @param http Kibana http service + * @param id ExceptionList ID (not list_id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +const fetchExceptionListById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + http.fetch(EXCEPTION_LIST_URL, { + method: 'GET', + query: { id, namespace_type: namespaceType }, + signal, + version, + }); + +const fetchExceptionListByIdWithValidation = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + flow( + () => + tryCatch( + () => + fetchExceptionListById({ + http, + id, + namespaceType, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(exceptionListSchema, response))), + flow(toPromise) + )(); + +export { fetchExceptionListByIdWithValidation as fetchExceptionListById }; + +/** + * Fetch an ExceptionList's ExceptionItems by providing a ExceptionList list_id + * + * @param http Kibana http service + * @param listIds ExceptionList list_ids (not ID) + * @param namespaceTypes ExceptionList namespace_types + * @param search optional - simple search string + * @param filter optional + * @param pagination optional + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +const fetchExceptionListsItemsByListIds = async ({ + http, + listIds, + namespaceTypes, + filter, + pagination, + search, + signal, +}: ApiCallByListIdProps): Promise => { + const query = { + list_id: listIds.join(','), + namespace_type: namespaceTypes.join(','), + page: pagination.page ? `${pagination.page}` : '1', + per_page: pagination.perPage ? `${pagination.perPage}` : '20', + search, + sort_field: 'exception-list.created_at', + sort_order: 'desc', + filter, + }; + + return http.fetch(`${EXCEPTION_LIST_ITEM_URL}/_find`, { + method: 'GET', + query, + signal, + version, + }); +}; + +const fetchExceptionListsItemsByListIdsWithValidation = async ({ + filter, + http, + listIds, + namespaceTypes, + pagination, + search, + signal, +}: ApiCallByListIdProps): Promise => + flow( + () => + tryCatch( + () => + fetchExceptionListsItemsByListIds({ + filter, + http, + listIds, + namespaceTypes, + pagination, + search, + signal, + }), + toError + ), + chain((response) => fromEither(validateEither(foundExceptionListItemSchema, response))), + flow(toPromise) + )(); + +export { fetchExceptionListsItemsByListIdsWithValidation as fetchExceptionListsItemsByListIds }; + +/** + * Fetch an ExceptionListItem by providing a ExceptionListItem ID + * + * @param http Kibana http service + * @param id ExceptionListItem ID (not item_id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +const fetchExceptionListItemById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + http.fetch(EXCEPTION_LIST_ITEM_URL, { + method: 'GET', + query: { id, namespace_type: namespaceType }, + signal, + version, + }); + +const fetchExceptionListItemByIdWithValidation = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + flow( + () => tryCatch(() => fetchExceptionListItemById({ http, id, namespaceType, signal }), toError), + chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), + flow(toPromise) + )(); + +export { fetchExceptionListItemByIdWithValidation as fetchExceptionListItemById }; + +/** + * Delete an ExceptionList by providing a ExceptionList ID + * + * @param http Kibana http service + * @param id ExceptionList ID (not list_id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +const deleteExceptionListById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + http.fetch(EXCEPTION_LIST_URL, { + method: 'DELETE', + query: { id, namespace_type: namespaceType }, + signal, + version, + }); + +const deleteExceptionListByIdWithValidation = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + flow( + () => tryCatch(() => deleteExceptionListById({ http, id, namespaceType, signal }), toError), + chain((response) => fromEither(validateEither(exceptionListSchema, response))), + flow(toPromise) + )(); + +export { deleteExceptionListByIdWithValidation as deleteExceptionListById }; + +/** + * Delete an ExceptionListItem by providing a ExceptionListItem ID + * + * @param http Kibana http service + * @param id ExceptionListItem ID (not item_id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +const deleteExceptionListItemById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + http.fetch(EXCEPTION_LIST_ITEM_URL, { + method: 'DELETE', + query: { id, namespace_type: namespaceType }, + signal, + version, + }); + +const deleteExceptionListItemByIdWithValidation = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + flow( + () => tryCatch(() => deleteExceptionListItemById({ http, id, namespaceType, signal }), toError), + chain((response) => fromEither(validateEither(exceptionListItemSchema, response))), + flow(toPromise) + )(); + +export { deleteExceptionListItemByIdWithValidation as deleteExceptionListItemById }; + +/** + * Add new Endpoint ExceptionList + * + * @param http Kibana http service + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +const addEndpointExceptionList = async ({ + http, + signal, +}: AddEndpointExceptionListProps): Promise => + http.fetch(ENDPOINT_LIST_URL, { + method: 'POST', + signal, + version, + }); + +const addEndpointExceptionListWithValidation = async ({ + http, + signal, +}: AddEndpointExceptionListProps): Promise => + flow( + () => tryCatch(() => addEndpointExceptionList({ http, signal }), toError), + chain((response) => fromEither(validateEither(createEndpointListSchema, response))), + flow(toPromise) + )(); + +export { addEndpointExceptionListWithValidation as addEndpointExceptionList }; + +/** + * Export an ExceptionList by providing a ExceptionList ID + * + * @param http Kibana http service + * @param id ExceptionList ID (not list_id) + * @param includeExpiredExceptions boolean for including expired exceptions + * @param listId ExceptionList LIST_ID (not id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +export const exportExceptionList = async ({ + http, + id, + includeExpiredExceptions, + listId, + namespaceType, + signal, +}: ExportExceptionListProps): Promise => + http.fetch(`${EXCEPTION_LIST_URL}/_export`, { + method: 'POST', + query: { + id, + list_id: listId, + namespace_type: namespaceType, + include_expired_exceptions: includeExpiredExceptions, + }, + signal, + version, + }); + +/** + * Create a Filter query from an exception list id + * + * @param exceptionListId The id of the exception list from which create a Filter query + * @param signal AbortSignal for cancelling request + * + * @throws An error if response is not OK + */ +export const getExceptionFilterFromExceptionListIds = async ({ + alias, + chunkSize, + exceptionListIds, + excludeExceptions, + http, + signal, +}: GetExceptionFilterFromExceptionListIdsProps): Promise => + http.fetch(INTERNAL_EXCEPTION_FILTER, { + method: 'POST', + version: '1', + body: JSON.stringify({ + exception_list_ids: exceptionListIds, + type: 'exception_list_ids', + alias, + exclude_exceptions: excludeExceptions, + chunk_size: chunkSize, + }), + signal, + }); + +/** + * Create a Filter query from a list of exceptions + * + * @param exceptions Exception items to be made into a `Filter` query + * @param signal AbortSignal for cancelling request + * + * @throws An error if response is not OK + */ +export const getExceptionFilterFromExceptions = async ({ + exceptions, + alias, + excludeExceptions, + http, + chunkSize, + signal, +}: GetExceptionFilterFromExceptionsProps): Promise => + http.fetch(INTERNAL_EXCEPTION_FILTER, { + method: 'POST', + version: '1', + body: JSON.stringify({ + exceptions, + type: 'exception_items', + alias, + exclude_exceptions: excludeExceptions, + chunk_size: chunkSize, + }), + signal, + }); + +/** + * Duplicate an ExceptionList and its items by providing a ExceptionList list_id + * + * @param http Kibana http service + * @param includeExpiredExceptions boolean for including exception items with expired TTL + * @param listId ExceptionList LIST_ID (not id) + * @param namespaceType ExceptionList namespace_type + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +export const duplicateExceptionList = async ({ + http, + includeExpiredExceptions, + listId, + namespaceType, + signal, +}: DuplicateExceptionListProps): Promise => + http.fetch(`${EXCEPTION_LIST_URL}/_duplicate`, { + method: 'POST', + query: { + list_id: listId, + namespace_type: namespaceType, + include_expired_exceptions: includeExpiredExceptions, + }, + signal, + version, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.ts new file mode 100644 index 000000000000..574c0f97292e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.test.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { tryCatch } from 'fp-ts/lib/TaskEither'; + +import { toPromise } from '.'; + +describe('toPromise', () => { + it('rejects with left if TaskEither is left', async () => { + const task = tryCatch(() => Promise.reject(new Error('whoops')), String); + + await expect(toPromise(task)).rejects.toEqual('Error: whoops'); + }); + + it('resolves with right if TaskEither is right', async () => { + const task = tryCatch(() => Promise.resolve('success'), String); + + await expect(toPromise(task)).resolves.toEqual('success'); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.ts new file mode 100644 index 000000000000..1360c78db59e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/fp_utils/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 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 { TaskEither } from 'fp-ts/lib/TaskEither'; +import { fold } from 'fp-ts/lib/Either'; + +// TODO: This is copied in a few other spots and probably should live within its own kbn package +// rather than living here. A package such as kbn-security-solution-fp-utils +export const toPromise = async (taskEither: TaskEither): Promise => + pipe( + await taskEither(), + fold( + (e) => Promise.reject(e), + (a) => Promise.resolve(a) + ) + ); + +export const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e))); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts new file mode 100644 index 000000000000..1168b4e49195 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.test.ts @@ -0,0 +1,443 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { createListIndex, deleteList, exportList, findLists, importList, readListIndex } from '.'; +import { + ApiPayload, + DeleteListParams, + ExportListParams, + FindListsParams, + ImportListParams, +} from '../types'; + +import { HttpFetchOptions } from '@kbn/core-http-browser'; +import { httpServiceMock } from '@kbn/core-http-browser-mocks'; + +import { getFoundListSchemaMock } from './mocks/response/found_list_schema.mock'; +import { getListResponseMock } from './mocks/response/list_schema.mock'; +import { getListItemIndexExistSchemaResponseMock } from './mocks/response/list_item_index_exist_schema.mock'; +import { getAcknowledgeSchemaResponseMock } from './mocks/response/acknowledge_schema.mock'; + +describe('Value Lists API', () => { + let httpMock: ReturnType; + + beforeEach(() => { + httpMock = httpServiceMock.createStartContract(); + }); + describe('deleteList', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getListResponseMock()); + }); + + it('DELETEs specifying the id as a query parameter', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { + deleteReferences: false, + id: 'list-id', + ignoreReferences: true, + }; + await deleteList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists', + expect.objectContaining({ + method: 'DELETE', + query: { deleteReferences: false, id: 'list-id', ignoreReferences: true }, + }) + ); + }); + + it('rejects with an error if request payload is invalid (and does not make API call)', async () => { + const abortCtrl = new AbortController(); + const payload: Omit, 'id'> & { + id: number; + } = { id: 23 }; + + await expect( + deleteList({ + http: httpMock, + ...(payload as unknown as ApiPayload), + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "23" supplied to "id"')); + expect(httpMock.fetch).not.toHaveBeenCalled(); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { id: 'list-id' }; + const badResponse = { ...getListResponseMock(), id: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + deleteList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); + }); + }); + describe('findLists', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getFoundListSchemaMock()); + }); + + it('GETs from the lists endpoint', async () => { + const abortCtrl = new AbortController(); + await findLists({ + http: httpMock, + pageIndex: 1, + pageSize: 10, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/_find', + expect.objectContaining({ + method: 'GET', + }) + ); + }); + + it('sends pagination as query parameters', async () => { + const abortCtrl = new AbortController(); + await findLists({ + cursor: 'cursor', + http: httpMock, + pageIndex: 1, + pageSize: 10, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/_find', + expect.objectContaining({ + query: { + cursor: 'cursor', + page: 1, + per_page: 10, + }, + }) + ); + }); + + it('sends sort_field and sort_order as query parameters', async () => { + const abortCtrl = new AbortController(); + await findLists({ + cursor: 'cursor', + http: httpMock, + pageIndex: 1, + pageSize: 10, + signal: abortCtrl.signal, + sortField: 'created_at', + sortOrder: 'desc', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/_find', + expect.objectContaining({ + query: { + cursor: 'cursor', + page: 1, + per_page: 10, + sort_field: 'created_at', + sort_order: 'desc', + }, + }) + ); + }); + + it('rejects with an error if request payload is invalid (and does not make API call)', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { + pageIndex: 10, + pageSize: 0, + }; + + await expect( + findLists({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "0" supplied to "per_page"')); + expect(httpMock.fetch).not.toHaveBeenCalled(); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { + pageIndex: 1, + pageSize: 10, + }; + const badResponse = { ...getFoundListSchemaMock(), cursor: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + findLists({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "cursor"')); + }); + }); + describe('importList', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getListResponseMock()); + }); + + it('POSTs the file', async () => { + const abortCtrl = new AbortController(); + const file = new File([], 'name'); + + await importList({ + file, + http: httpMock, + listId: 'my_list', + signal: abortCtrl.signal, + type: 'keyword', + }); + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items/_import', + expect.objectContaining({ + method: 'POST', + }) + ); + + // httpmock's fetch signature is inferred incorrectly + const [[, { body }]] = httpMock.fetch.mock.calls as unknown as Array< + [unknown, HttpFetchOptions] + >; + const actualFile = (body as FormData).get('file'); + expect(actualFile).toEqual(file); + }); + + it('sends type and id as query parameters', async () => { + const abortCtrl = new AbortController(); + const file = new File([], 'name'); + + await importList({ + file, + http: httpMock, + listId: 'my_list', + signal: abortCtrl.signal, + type: 'keyword', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items/_import', + expect.objectContaining({ + query: { list_id: 'my_list', type: 'keyword' }, + }) + ); + }); + + it('rejects with an error if request body is invalid (and does not make API call)', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { + file: undefined as unknown as File, + listId: 'list-id', + type: 'ip', + }; + + await expect( + importList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "file"')); + expect(httpMock.fetch).not.toHaveBeenCalled(); + }); + + it('rejects with an error if request params are invalid (and does not make API call)', async () => { + const abortCtrl = new AbortController(); + const file = new File([], 'name'); + const payload: ApiPayload = { + file, + listId: 'list-id', + type: 'other' as 'ip', + }; + + await expect( + importList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "other" supplied to "type"')); + expect(httpMock.fetch).not.toHaveBeenCalled(); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const file = new File([], 'name'); + const payload: ApiPayload = { + file, + listId: 'list-id', + type: 'ip', + }; + const badResponse = { ...getListResponseMock(), id: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + importList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); + }); + }); + describe('exportList', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue({}); + }); + + it('POSTs to the export endpoint', async () => { + const abortCtrl = new AbortController(); + + await exportList({ + http: httpMock, + listId: 'my_list', + signal: abortCtrl.signal, + }); + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items/_export', + expect.objectContaining({ + method: 'POST', + }) + ); + }); + + it('sends type and id as query parameters', async () => { + const abortCtrl = new AbortController(); + + await exportList({ + http: httpMock, + listId: 'my_list', + signal: abortCtrl.signal, + }); + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items/_export', + expect.objectContaining({ + query: { list_id: 'my_list' }, + }) + ); + }); + + it('rejects with an error if request params are invalid (and does not make API call)', async () => { + const abortCtrl = new AbortController(); + const payload: ApiPayload = { + listId: 23 as unknown as string, + }; + + await expect( + exportList({ + http: httpMock, + ...payload, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "23" supplied to "list_id"')); + expect(httpMock.fetch).not.toHaveBeenCalled(); + }); + }); + + describe('readListIndex', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getListItemIndexExistSchemaResponseMock()); + }); + + it('GETs the list index', async () => { + const abortCtrl = new AbortController(); + await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/index', + expect.objectContaining({ + method: 'GET', + }) + ); + }); + + it('returns the response when valid', async () => { + const abortCtrl = new AbortController(); + const result = await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(result).toEqual(getListItemIndexExistSchemaResponseMock()); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const badResponse = { ...getListItemIndexExistSchemaResponseMock(), list_index: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "list_index"')); + }); + }); + + describe('createListIndex', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getAcknowledgeSchemaResponseMock()); + }); + + it('GETs the list index', async () => { + const abortCtrl = new AbortController(); + await createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/index', + expect.objectContaining({ + method: 'POST', + }) + ); + }); + + it('returns the response when valid', async () => { + const abortCtrl = new AbortController(); + const result = await createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(result).toEqual(getAcknowledgeSchemaResponseMock()); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const badResponse = { acknowledged: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "acknowledged"')); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.ts new file mode 100644 index 000000000000..93160ca739e2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/index.ts @@ -0,0 +1,342 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { chain, fromEither, map, tryCatch } from 'fp-ts/lib/TaskEither'; +import { flow } from 'fp-ts/lib/function'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { validateEither } from '@kbn/securitysolution-io-ts-utils'; +import { + AcknowledgeSchema, + DeleteListSchemaEncoded, + ExportListItemQuerySchemaEncoded, + FindListSchemaEncoded, + FoundListSchema, + ImportListItemQuerySchemaEncoded, + ImportListItemSchemaEncoded, + ListItemIndexExistSchema, + ListSchema, + ReadListSchema, + acknowledgeSchema, + deleteListSchema, + readListSchema, + exportListItemQuerySchema, + findListSchema, + foundListSchema, + importListItemQuerySchema, + importListItemSchema, + listItemIndexExistSchema, + listSchema, + foundListsBySizeSchema, + FoundListsBySizeSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { + LIST_INDEX, + LIST_ITEM_URL, + LIST_PRIVILEGES_URL, + LIST_URL, + INTERNAL_FIND_LISTS_BY_SIZE, +} from '@kbn/securitysolution-list-constants'; +import { toError, toPromise } from '../fp_utils'; + +import { + ApiParams, + DeleteListParams, + ExportListParams, + FindListsParams, + ImportListParams, + GetListByIdParams, +} from '../types'; + +export type { + ApiParams, + DeleteListParams, + ExportListParams, + FindListsParams, + ImportListParams, +} from '../types'; + +const version = '2023-10-31'; + +const findLists = async ({ + http, + cursor, + page, + // eslint-disable-next-line @typescript-eslint/naming-convention + per_page, + signal, + // eslint-disable-next-line @typescript-eslint/naming-convention + sort_field, + // eslint-disable-next-line @typescript-eslint/naming-convention + sort_order, +}: ApiParams & FindListSchemaEncoded): Promise => { + return http.fetch(`${LIST_URL}/_find`, { + method: 'GET', + query: { + cursor, + page, + per_page, + sort_field, + sort_order, + }, + signal, + version, + }); +}; + +const findListsWithValidation = async ({ + cursor, + http, + pageIndex, + pageSize, + signal, + sortField, + sortOrder, +}: FindListsParams): Promise => + pipe( + { + cursor: cursor != null ? cursor.toString() : undefined, + page: pageIndex != null ? pageIndex.toString() : undefined, + per_page: pageSize != null ? pageSize.toString() : undefined, + sort_field: sortField != null ? sortField.toString() : undefined, + sort_order: sortOrder, + }, + (payload) => fromEither(validateEither(findListSchema, payload)), + chain((payload) => tryCatch(() => findLists({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(foundListSchema, response))), + flow(toPromise) + ); + +export { findListsWithValidation as findLists }; + +const findListsBySize = async ({ + http, + cursor, + page, + // eslint-disable-next-line @typescript-eslint/naming-convention + per_page, + signal, +}: ApiParams & FindListSchemaEncoded): Promise => { + return http.fetch(`${INTERNAL_FIND_LISTS_BY_SIZE}`, { + method: 'GET', + version: '1', + query: { + cursor, + page, + per_page, + }, + signal, + }); +}; + +const findListsBySizeWithValidation = async ({ + cursor, + http, + pageIndex, + pageSize, + signal, +}: FindListsParams): Promise => + pipe( + { + cursor: cursor != null ? cursor.toString() : undefined, + page: pageIndex != null ? pageIndex.toString() : undefined, + per_page: pageSize != null ? pageSize.toString() : undefined, + }, + (payload) => fromEither(validateEither(findListSchema, payload)), + chain((payload) => tryCatch(() => findListsBySize({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(foundListsBySizeSchema, response))), + flow(toPromise) + ); + +export { findListsBySizeWithValidation as findListsBySize }; + +const importList = async ({ + file, + http, + // eslint-disable-next-line @typescript-eslint/naming-convention + list_id, + type, + signal, + refresh, +}: ApiParams & + ImportListItemSchemaEncoded & + ImportListItemQuerySchemaEncoded): Promise => { + const formData = new FormData(); + formData.append('file', file as Blob); + + return http.fetch(`${LIST_ITEM_URL}/_import`, { + body: formData, + headers: { 'Content-Type': undefined }, + method: 'POST', + query: { list_id, type, refresh }, + signal, + version, + }); +}; + +const importListWithValidation = async ({ + file, + http, + listId, + type, + signal, + refresh, +}: ImportListParams): Promise => + pipe( + { + list_id: listId, + type, + refresh, + }, + (query) => fromEither(validateEither(importListItemQuerySchema, query)), + chain((query) => + pipe( + fromEither(validateEither(importListItemSchema, { file })), + map((body) => ({ ...body, ...query })) + ) + ), + chain((payload) => tryCatch(() => importList({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(listSchema, response))), + toPromise + ); + +export { importListWithValidation as importList }; + +const deleteList = async ({ + deleteReferences = false, + http, + id, + ignoreReferences = false, + signal, +}: ApiParams & DeleteListSchemaEncoded): Promise => + http.fetch(LIST_URL, { + method: 'DELETE', + query: { deleteReferences, id, ignoreReferences }, + signal, + version, + }); + +const deleteListWithValidation = async ({ + deleteReferences, + http, + id, + ignoreReferences, + signal, +}: DeleteListParams): Promise => + pipe( + { deleteReferences, id, ignoreReferences }, + (payload) => fromEither(validateEither(deleteListSchema, payload)), + chain((payload) => tryCatch(() => deleteList({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(listSchema, response))), + flow(toPromise) + ); + +export { deleteListWithValidation as deleteList }; + +const exportList = async ({ + http, + // eslint-disable-next-line @typescript-eslint/naming-convention + list_id, + signal, +}: ApiParams & ExportListItemQuerySchemaEncoded): Promise => + http.fetch(`${LIST_ITEM_URL}/_export`, { + method: 'POST', + query: { list_id }, + signal, + version, + }); + +const exportListWithValidation = async ({ + http, + listId, + signal, +}: ExportListParams): Promise => + pipe( + { list_id: listId }, + (payload) => fromEither(validateEither(exportListItemQuerySchema, payload)), + chain((payload) => tryCatch(() => exportList({ http, signal, ...payload }), toError)), + flow(toPromise) + ); + +export { exportListWithValidation as exportList }; + +const readListIndex = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_INDEX, { + method: 'GET', + signal, + version, + }); + +const readListIndexWithValidation = async ({ + http, + signal, +}: ApiParams): Promise => + flow( + () => tryCatch(() => readListIndex({ http, signal }), toError), + chain((response) => fromEither(validateEither(listItemIndexExistSchema, response))), + flow(toPromise) + )(); + +export { readListIndexWithValidation as readListIndex }; + +// TODO add types and validation +export const readListPrivileges = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_PRIVILEGES_URL, { + method: 'GET', + signal, + version, + }); + +const createListIndex = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_INDEX, { + method: 'POST', + signal, + version, + }); + +const createListIndexWithValidation = async ({ + http, + signal, +}: ApiParams): Promise => + flow( + () => tryCatch(() => createListIndex({ http, signal }), toError), + chain((response) => fromEither(validateEither(acknowledgeSchema, response))), + flow(toPromise) + )(); + +export { createListIndexWithValidation as createListIndex }; + +const getListById = async ({ + http, + signal, + id, +}: ApiParams & ReadListSchema): Promise => { + return http.fetch(`${LIST_URL}`, { + method: 'GET', + query: { + id, + }, + signal, + version, + }); +}; + +const getListByIdWithValidation = async ({ + http, + signal, + id, +}: GetListByIdParams): Promise => + pipe( + { + id, + }, + (payload) => fromEither(validateEither(readListSchema, payload)), + chain((payload) => tryCatch(() => getListById({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(listSchema, response))), + flow(toPromise) + ); + +export { getListByIdWithValidation as getListById }; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.ts new file mode 100644 index 000000000000..b3ce62d03f48 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/constants.mock.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const DATE_NOW = '2020-04-20T15:25:31.830Z'; +export const USER = 'some user'; +export const ELASTIC_USER = 'elastic'; +export const NAME = 'some name'; +export const DESCRIPTION = 'some description'; +export const LIST_ID = 'some-list-id'; +export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; + +export const META = {}; +export const TYPE = 'ip'; + +export const VERSION = 1; +export const IMMUTABLE = false; diff --git a/x-pack/plugins/lists/common/schemas/response/acknowledge_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/acknowledge_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/acknowledge_schema.mock.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/acknowledge_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/found_list_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/found_list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_list_schema.mock.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/found_list_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/list_item_index_exist_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_item_index_exist_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/list_item_index_exist_schema.mock.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_item_index_exist_schema.mock.ts diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.ts new file mode 100644 index 000000000000..b2b66ad4636c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_api/mocks/response/list_schema.mock.ts @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + IMMUTABLE, + LIST_ID, + META, + NAME, + TIE_BREAKER, + TYPE, + USER, + VERSION, +} from '../constants.mock'; + +export const getListResponseMock = (): ListSchema => ({ + '@timestamp': DATE_NOW, + _version: undefined, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + deserializer: undefined, + id: LIST_ID, + immutable: IMMUTABLE, + meta: META, + name: NAME, + serializer: undefined, + tie_breaker_id: TIE_BREAKER, + type: TYPE, + updated_at: DATE_NOW, + updated_by: USER, + version: VERSION, +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ + created_by: ELASTIC_USER, + description: DESCRIPTION, + immutable: IMMUTABLE, + name: NAME, + type: TYPE, + updated_by: ELASTIC_USER, + version: VERSION, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts new file mode 100644 index 000000000000..651edfe25cb1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.test.ts @@ -0,0 +1,171 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { createListItem, deleteListItem, findListItems, patchListItem } from '.'; +import { httpServiceMock } from '@kbn/core-http-browser-mocks'; +import { + getFoundListSchemaMock, + getCreateListItemResponseMock, + getUpdatedListItemResponseMock, + getDeletedListItemResponseMock, +} from './mocks/response'; + +describe('Value list item API', () => { + let httpMock: ReturnType; + beforeEach(() => { + httpMock = httpServiceMock.createStartContract(); + }); + + describe('findListItems', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getFoundListSchemaMock()); + }); + + it('GETs from the lists endpoint with query params', async () => { + const abortCtrl = new AbortController(); + await findListItems({ + http: httpMock, + pageIndex: 1, + pageSize: 10, + signal: abortCtrl.signal, + filter: '*:*', + listId: 'list_id', + sortField: 'updated_at', + sortOrder: 'asc', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items/_find', + expect.objectContaining({ + method: 'GET', + query: { + cursor: undefined, + filter: '*:*', + list_id: 'list_id', + page: 1, + per_page: 10, + sort_field: 'updated_at', + sort_order: 'asc', + }, + }) + ); + }); + }); + + describe('createListItem', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getCreateListItemResponseMock()); + }); + + it('POSTs to the lists endpoint with the list item', async () => { + const abortCtrl = new AbortController(); + await createListItem({ + http: httpMock, + signal: abortCtrl.signal, + value: '123', + listId: 'list_id', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items', + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ + value: '123', + list_id: 'list_id', + }), + }) + ); + }); + + it('returns the created list item', async () => { + const abortCtrl = new AbortController(); + const result = await createListItem({ + http: httpMock, + signal: abortCtrl.signal, + value: '123', + listId: 'list_id', + }); + + expect(result).toEqual(getCreateListItemResponseMock()); + }); + }); + + describe('patchListItem', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getUpdatedListItemResponseMock()); + }); + + it('PATCH to the lists endpoint with the list item', async () => { + const abortCtrl = new AbortController(); + await patchListItem({ + http: httpMock, + signal: abortCtrl.signal, + id: 'item_id', + value: '123', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items', + expect.objectContaining({ + method: 'PATCH', + body: JSON.stringify({ + id: 'item_id', + value: '123', + }), + }) + ); + }); + + it('returns the updated list item', async () => { + const abortCtrl = new AbortController(); + const result = await patchListItem({ + http: httpMock, + signal: abortCtrl.signal, + id: 'item_id', + value: '123', + }); + + expect(result).toEqual(getUpdatedListItemResponseMock()); + }); + }); + + describe('deleteListItem', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getCreateListItemResponseMock()); + }); + + it('DELETE to the lists endpoint with the list item', async () => { + const abortCtrl = new AbortController(); + await deleteListItem({ + http: httpMock, + signal: abortCtrl.signal, + id: 'item_id', + refresh: 'true', + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/items', + expect.objectContaining({ + method: 'DELETE', + query: { id: 'item_id', refresh: 'true' }, + }) + ); + }); + + it('returns the deleted list item', async () => { + const abortCtrl = new AbortController(); + const result = await deleteListItem({ + http: httpMock, + signal: abortCtrl.signal, + id: 'item_id', + }); + + expect(result).toEqual(getDeletedListItemResponseMock()); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts new file mode 100644 index 000000000000..1605b68ee04c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/index.ts @@ -0,0 +1,225 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + FindListItemSchema, + ListItemSchema, + deleteListItemSchema, + patchListItemSchema, + createListItemSchema, + findListItemSchema, + foundListItemSchema, + listItemSchema, + FoundListItemSchema, + DeleteListItemSchema, + PatchListItemSchema, + CreateListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { chain, fromEither, tryCatch } from 'fp-ts/lib/TaskEither'; +import { flow } from 'fp-ts/lib/function'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { validateEither } from '@kbn/securitysolution-io-ts-utils'; + +import { LIST_ITEM_URL } from '@kbn/securitysolution-list-constants'; +import { + ApiParams, + FindListItemsParams, + DeleteListItemParams, + PatchListItemParams, + CreateListItemParams, +} from '../types'; +import { toError, toPromise } from '../fp_utils'; + +const version = '2023-10-31'; + +/** + * Fetch list items + */ +const findListItems = async ({ + http, + cursor, + page, + // eslint-disable-next-line @typescript-eslint/naming-convention + list_id, + // eslint-disable-next-line @typescript-eslint/naming-convention + per_page, + signal, + // eslint-disable-next-line @typescript-eslint/naming-convention + sort_field, + // eslint-disable-next-line @typescript-eslint/naming-convention + sort_order, + filter, +}: ApiParams & FindListItemSchema): Promise => { + return http.fetch(`${LIST_ITEM_URL}/_find`, { + method: 'GET', + query: { + cursor, + page, + per_page, + sort_field, + sort_order, + list_id, + filter, + }, + signal, + version, + }); +}; + +const findListItemsWithValidation = async ({ + cursor, + http, + pageIndex, + pageSize, + signal, + sortField, + sortOrder, + filter, + listId, +}: FindListItemsParams): Promise => + pipe( + { + cursor: cursor != null ? cursor.toString() : undefined, + page: pageIndex != null ? pageIndex.toString() : undefined, + per_page: pageSize != null ? pageSize.toString() : undefined, + sort_field: sortField != null ? sortField.toString() : undefined, + filter: filter != null ? filter.toString() : undefined, + sort_order: sortOrder, + list_id: listId, + }, + (payload) => fromEither(validateEither(findListItemSchema, payload)), + chain((payload) => tryCatch(() => findListItems({ http, signal, ...payload }), toError)), + chain((response) => fromEither(validateEither(foundListItemSchema, response))), + flow(toPromise) + ); + +export { findListItemsWithValidation as findListItems }; + +const deleteListItem = async ({ + http, + id, + signal, + refresh, +}: ApiParams & DeleteListItemSchema): Promise => + http.fetch(LIST_ITEM_URL, { + method: 'DELETE', + query: { id, refresh }, + signal, + version, + }); + +const deleteListItemWithValidation = async ({ + http, + id, + signal, + refresh, +}: DeleteListItemParams): Promise => + pipe( + { id, refresh }, + (payload) => fromEither(validateEither(deleteListItemSchema, payload)), + chain((payload) => + tryCatch( + () => + deleteListItem({ + http, + signal, + ...payload, + value: undefined, + list_id: undefined, + }), + toError + ) + ), + chain((response) => fromEither(validateEither(listItemSchema, response))), + flow(toPromise) + ); + +export { deleteListItemWithValidation as deleteListItem }; + +const patchListItem = async ({ + http, + id, + signal, + value, + _version, +}: ApiParams & PatchListItemSchema): Promise => + http.fetch(LIST_ITEM_URL, { + method: 'PATCH', + body: JSON.stringify({ id, value, _version }), + signal, + version, + }); + +const patchListItemWithValidation = async ({ + http, + id, + signal, + value, + refresh, + _version, +}: PatchListItemParams): Promise => + pipe( + { id, value, _version, refresh }, + (payload) => fromEither(validateEither(patchListItemSchema, payload)), + chain((payload) => + tryCatch( + () => + patchListItem({ + http, + signal, + ...payload, + }), + toError + ) + ), + chain((response) => fromEither(validateEither(listItemSchema, response))), + flow(toPromise) + ); + +export { patchListItemWithValidation as patchListItem }; + +const createListItem = async ({ + http, + signal, + value, + // eslint-disable-next-line @typescript-eslint/naming-convention + list_id, + refresh, +}: ApiParams & CreateListItemSchema): Promise => + http.fetch(LIST_ITEM_URL, { + method: 'POST', + body: JSON.stringify({ value, list_id, refresh }), + signal, + version, + }); + +const createListItemWithValidation = async ({ + http, + signal, + value, + refresh, + listId, +}: CreateListItemParams): Promise => + pipe( + { list_id: listId, value, refresh }, + (payload) => fromEither(validateEither(createListItemSchema, payload)), + chain((payload) => + tryCatch( + () => + createListItem({ + http, + signal, + ...payload, + }), + toError + ) + ), + chain((response) => fromEither(validateEither(listItemSchema, response))), + flow(toPromise) + ); + +export { createListItemWithValidation as createListItem }; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/index.ts new file mode 100644 index 000000000000..2dddd844c5f2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { FoundListItemSchema, ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { getListItemResponseMock } from './list_item_schema.mock'; + +export const getFoundListSchemaMock = (): FoundListItemSchema => ({ + cursor: '123', + data: [getListItemResponseMock()], + page: 1, + per_page: 1, + total: 1, +}); + +export const getCreateListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); +export const getUpdatedListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); +export const getDeletedListItemResponseMock = (): ListItemSchema => getListItemResponseMock(); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.ts new file mode 100644 index 000000000000..726f49e9d0d3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/list_item_api/mocks/response/list_item_schema.mock.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +export const getListItemResponseMock = (): ListItemSchema => ({ + _version: '1', + '@timestamp': '2020-08-11T11:22:13.670Z', + created_at: '2020-08-11T11:22:13.670Z', + created_by: 'elastic', + deserializer: 'some deserializer', + id: 'bpdB3XMBx7pemMHopQ6M', + list_id: 'list_id', + meta: {}, + serializer: 'some serializer', + tie_breaker_id: '17d3befb-dc22-4b3c-a286-b5504c4fbeeb', + type: 'keyword', + updated_at: '2020-08-11T11:22:13.670Z', + updated_by: 'elastic', + value: 'some keyword', +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/types.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/types.ts new file mode 100644 index 000000000000..54aa89936d73 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/src/types.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { + SortFieldOrUndefined, + SortOrderOrUndefined, + Type, + Refresh, + RefreshWithWaitFor, +} from '@kbn/securitysolution-io-ts-list-types'; + +// TODO: Replace these with kbn packaged versions once we have those available to us +// These originally came from this location below before moving them to this hacked "any" types: +// import { HttpStart, NotificationsStart } from '../../../../../../../../src/core/public'; +interface HttpStart { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + fetch: (...args: any) => any; +} + +export interface ApiParams { + http: HttpStart; + signal: AbortSignal; +} +export type ApiPayload = Omit; + +export interface FindListsParams extends ApiParams { + cursor?: string | undefined; + pageSize: number | undefined; + pageIndex: number | undefined; + sortOrder?: SortOrderOrUndefined; + sortField?: SortFieldOrUndefined; +} + +export interface FindListItemsParams extends ApiParams { + cursor?: string | undefined; + pageSize: number | undefined; + pageIndex: number | undefined; + sortOrder?: SortOrderOrUndefined; + sortField?: SortFieldOrUndefined; + filter: string | undefined; + listId: string; +} + +export interface ImportListParams extends ApiParams { + file: File; + listId: string | undefined; + type: Type | undefined; + refresh?: RefreshWithWaitFor; +} + +export interface DeleteListParams extends ApiParams { + deleteReferences?: boolean; + id: string; + ignoreReferences?: boolean; +} + +export interface DeleteListItemParams extends ApiParams { + refresh?: Refresh; + id: string; +} + +export interface PatchListItemParams extends ApiParams { + refresh?: Refresh; + id: string; + value: string; + _version?: string; +} + +export interface CreateListItemParams extends ApiParams { + refresh?: RefreshWithWaitFor; + value: string; + listId: string; +} + +export interface ExportListParams extends ApiParams { + listId: string; +} + +export interface GetListByIdParams extends ApiParams { + id: string; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-api/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/tsconfig.json new file mode 100644 index 000000000000..10dbca803000 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-api/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-io-ts-utils", + "@kbn/securitysolution-list-constants", + "@kbn/core-http-browser", + "@kbn/core-http-browser-mocks", + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-list-constants/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/README.md similarity index 100% rename from packages/kbn-securitysolution-list-constants/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-list-constants/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/index.ts new file mode 100644 index 000000000000..746294c8908f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/index.ts @@ -0,0 +1,146 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { deepFreeze } from '@kbn/std'; + +/** + * Value list routes + */ +export const LIST_URL = '/api/lists'; +export const LIST_INDEX = `${LIST_URL}/index`; +export const LIST_ITEM_URL = `${LIST_URL}/items`; +export const LIST_PRIVILEGES_URL = `${LIST_URL}/privileges`; + +/** + * Internal value list routes + */ +export const INTERNAL_LIST_URL = '/internal/lists'; +export const INTERNAL_FIND_LISTS_BY_SIZE = `${INTERNAL_LIST_URL}/_find_lists_by_size` as const; +export const INTERNAL_EXCEPTION_FILTER = `${INTERNAL_LIST_URL}/_create_filter` as const; + +/** + * Exception list routes + */ +export const EXCEPTION_LIST_URL = '/api/exception_lists'; +export const EXCEPTION_LIST_ITEM_URL = '/api/exception_lists/items'; + +/** + * Internal exception list routes + */ +export const INTERNAL_EXCEPTION_LIST_URL = `/internal${EXCEPTION_LIST_URL}`; +export const INTERNAL_EXCEPTIONS_LIST_ENSURE_CREATED_URL = `${INTERNAL_EXCEPTION_LIST_URL}/_create`; + +/** + * Exception list spaces + */ +export const EXCEPTION_LIST_NAMESPACE_AGNOSTIC = 'exception-list-agnostic'; +export const EXCEPTION_LIST_NAMESPACE = 'exception-list'; + +/** + * Specific routes for the single global space agnostic endpoint list + */ +export const ENDPOINT_LIST_URL = '/api/endpoint_list'; + +/** + * Specific routes for the single global space agnostic endpoint list. These are convenience + * routes where they are going to try and create the global space agnostic endpoint list if it + * does not exist yet or if it was deleted at some point and re-create it before adding items to + * the list + */ +export const ENDPOINT_LIST_ITEM_URL = '/api/endpoint_list/items'; + +/** + * This ID is used for _both_ the Saved Object ID and for the list_id + * for the single global space agnostic endpoint list + */ +export const ENDPOINT_LIST_ID = 'endpoint_list'; + +/** The name of the single global space agnostic endpoint list */ +export const ENDPOINT_LIST_NAME = 'Endpoint Security Exception List'; + +/** The description of the single global space agnostic endpoint list */ +export const ENDPOINT_LIST_DESCRIPTION = 'Endpoint Security Exception List'; + +export const MAX_EXCEPTION_LIST_SIZE = 10000; + +export const MAXIMUM_SMALL_VALUE_LIST_SIZE = 65536; + +export const MAXIMUM_SMALL_IP_RANGE_VALUE_LIST_DASH_SIZE = 200; + +/** + * List definitions for Endpoint Artifact + */ +export const ENDPOINT_ARTIFACT_LISTS = deepFreeze({ + trustedApps: { + id: 'endpoint_trusted_apps', + name: 'Endpoint Security Trusted Apps List', + description: 'Endpoint Security Trusted Apps List', + }, + eventFilters: { + id: 'endpoint_event_filters', + name: 'Endpoint Security Event Filters List', + description: 'Endpoint Security Event Filters List', + }, + hostIsolationExceptions: { + id: 'endpoint_host_isolation_exceptions', + name: 'Endpoint Security Host isolation exceptions List', + description: 'Endpoint Security Host isolation exceptions List', + }, + blocklists: { + id: 'endpoint_blocklists', + name: 'Endpoint Security Blocklists List', + description: 'Endpoint Security Blocklists List', + }, +}); + +/** + * The IDs of all Endpoint artifact lists + */ +export const ENDPOINT_ARTIFACT_LIST_IDS = Object.freeze( + Object.values(ENDPOINT_ARTIFACT_LISTS).map(({ id }) => id) +); + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_TRUSTED_APPS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.trustedApps.id; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_TRUSTED_APPS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.trustedApps.name; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION = + ENDPOINT_ARTIFACT_LISTS.trustedApps.description; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_EVENT_FILTERS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.eventFilters.id; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_EVENT_FILTERS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.eventFilters.name; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_EVENT_FILTERS_LIST_DESCRIPTION = + ENDPOINT_ARTIFACT_LISTS.eventFilters.description; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID = + ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.id; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_NAME = + ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.name; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_DESCRIPTION = + ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.description; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_BLOCKLISTS_LIST_ID = ENDPOINT_ARTIFACT_LISTS.blocklists.id; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_BLOCKLISTS_LIST_NAME = ENDPOINT_ARTIFACT_LISTS.blocklists.name; + +/** @deprecated Use `ENDPOINT_ARTIFACT_LISTS` instead */ +export const ENDPOINT_BLOCKLISTS_LIST_DESCRIPTION = ENDPOINT_ARTIFACT_LISTS.blocklists.description; diff --git a/packages/kbn-securitysolution-list-constants/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-list-constants/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-list-constants/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/package.json new file mode 100644 index 000000000000..f57bdd68a2cc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/package.json @@ -0,0 +1,7 @@ +{ + "name": "@kbn/securitysolution-list-constants", + "version": "1.0.0", + "description": "security solution list constants to use across plugins such lists, security_solution, cases, etc...", + "license": "Elastic License 2.0", + "private": true +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/tsconfig.json new file mode 100644 index 000000000000..0d3f96d6a17b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-constants/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/std" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-list-hooks/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/README.md similarity index 100% rename from packages/kbn-securitysolution-list-hooks/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/index.ts new file mode 100644 index 000000000000..8e5fdecab186 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/transforms'; +export * from './src/use_api'; +export * from './src/use_create_list_index'; +export * from './src/use_cursor'; +export * from './src/use_delete_list'; +export * from './src/use_exception_lists'; +export * from './src/use_export_list'; +export * from './src/use_find_lists'; +export * from './src/use_find_lists_by_size'; +export * from './src/use_import_list'; +export * from './src/use_persist_exception_item'; +export * from './src/use_persist_exception_list'; +export * from './src/use_read_list_index'; +export * from './src/use_read_list_privileges'; +export * from './src/use_find_list_items'; +export * from './src/use_create_list_item'; +export * from './src/use_delete_list_item'; +export * from './src/use_patch_list_item'; +export * from './src/use_get_list_by_id'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/jest.config.js new file mode 100644 index 000000000000..7b0430c9bf09 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks'], +}; diff --git a/packages/kbn-securitysolution-list-hooks/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-list-hooks/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/package.json new file mode 100644 index 000000000000..8a2ead4291bd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-list-hooks", + "version": "1.0.0", + "description": "Security solution list ReactJS hooks", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/constants.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/constants.ts new file mode 100644 index 000000000000..377c980531a4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/constants.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const READ_INDEX_QUERY_KEY = ['detectionEngine', 'listIndex']; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/index.ts new file mode 100644 index 000000000000..dd0e180eba26 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './transforms'; +export * from './use_api'; +export * from './use_create_list_index'; +export * from './use_cursor'; +export * from './use_delete_list'; +export * from './use_exception_lists'; +export * from './use_export_list'; +export * from './use_find_lists'; +export * from './use_import_list'; +export * from './use_persist_exception_item'; +export * from './use_persist_exception_list'; +export * from './use_read_list_index'; +export * from './use_read_list_privileges'; +export * from './use_find_list_items'; +export * from './use_create_list_item'; +export * from './use_delete_list_item'; +export * from './use_patch_list_item'; +export * from './use_get_list_by_id'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts new file mode 100644 index 000000000000..762d1eb243cf --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/constants.mock.ts @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + CommentsArray, + EntriesArray, + Entry, + EntryMatch, + EntryNested, + OsTypeArray, +} from '@kbn/securitysolution-io-ts-list-types'; + +export const DATE_NOW = '2020-04-20T15:25:31.830Z'; +export const USER = 'some user'; +export const ELASTIC_USER = 'elastic'; +export const NAME = 'some name'; +export const DESCRIPTION = 'some description'; +export const LIST_ID = 'some-list-id'; +export const TIE_BREAKER = '6a76b69d-80df-4ab2-8c3e-85f466b06a0e'; + +export const META = {}; +export const TYPE = 'ip'; + +export const VERSION = 1; +export const IMMUTABLE = false; +// Exception List specific +export const ID = 'uuid_here'; +export const NAMESPACE_TYPE = 'single'; +export const OS_TYPES: OsTypeArray = ['windows']; +export const TAGS = []; +export const UPDATED_COMMENTS = [ + { + comment: 'old comment', + id: 'old_created_id', + }, + { + comment: 'new comment', + id: 'new_id', + }, +]; +export const COMMENTS = []; +export const ENTRIES: EntriesArray = [ + { + entries: [{ field: 'nested.field', operator: 'included', type: 'match', value: 'some value' }], + field: 'some.parentField', + type: 'nested', + }, + { field: 'some.not.nested.field', operator: 'included', type: 'match', value: 'some value' }, +]; +export const ITEM_ID = 'some-list-item-id'; +export const ITEM_TYPE = 'simple'; +export const LIST_ITEM_ID = 'some-list-item-id'; +// ENTRIES_WITH_IDS should only be used to mock out functionality of a collection of transforms +// that are UI specific and useful for UI concerns that are inserted between the +// API and the actual user interface. In some ways these might be viewed as +// technical debt or to compensate for the differences and preferences +// of how ReactJS might prefer data vs. how we want to model data. +export const ENTRIES_WITH_IDS: EntriesArray = [ + { + entries: [ + { + field: 'nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as EntryMatch & { id: string }, + ], + field: 'some.parentField', + id: '123', + type: 'nested', + } as EntryNested & { id: string }, + { + field: 'some.not.nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as Entry & { id: string }, +]; + +export const COMMENTS_WITH_CREATEDAT_CREATEDBY: CommentsArray = [ + { + comment: 'old comment', + id: 'old_created_id', + created_at: '2022-01-08T15:25:31.830Z', + created_by: 'elastic', + }, + { + comment: 'new comment', + id: 'new_id', + created_at: '2022-05-14T15:25:31.830Z', + created_by: 'elastic', + }, +]; diff --git a/packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts similarity index 76% rename from packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts index 5727a271a9bf..ff9789a7995b 100644 --- a/packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/create_exception_list_item_schema.mock.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import type { CreateExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.ts new file mode 100644 index 000000000000..47b0030c316a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/request/update_exception_list_item_schema.mock.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { UpdateExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { + DESCRIPTION, + ENTRIES, + ID, + ITEM_ID, + ITEM_TYPE, + LIST_ITEM_ID, + META, + NAME, + NAMESPACE_TYPE, + OS_TYPES, + TAGS, + UPDATED_COMMENTS, +} from '../constants.mock'; + +export const getUpdateExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ + _version: undefined, + comments: UPDATED_COMMENTS, + description: DESCRIPTION, + entries: ENTRIES, + id: ID, + item_id: LIST_ITEM_ID, + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: ['linux'], + tags: TAGS, + type: ITEM_TYPE, +}); + +/** + * Useful for end to end tests and other mechanisms which want to fill in the values + * after doing a get of the structure. + */ +export const getUpdateMinimalExceptionListItemSchemaMock = (): UpdateExceptionListItemSchema => ({ + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + name: NAME, + os_types: OS_TYPES, + type: ITEM_TYPE, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts new file mode 100644 index 000000000000..acb7204da9b7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/exception_list_item_schema.mock.ts @@ -0,0 +1,70 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { + COMMENTS, + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + ENTRIES, + ITEM_ID, + ITEM_TYPE, + LIST_ID, + META, + NAME, + NAMESPACE_TYPE, + OS_TYPES, + TIE_BREAKER, + USER, +} from '../constants.mock'; + +export const getExceptionListItemSchemaMock = ( + overrides?: Partial +): ExceptionListItemSchema => ({ + _version: undefined, + comments: COMMENTS, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + entries: ENTRIES, + expire_time: undefined, + id: '1', + item_id: 'endpoint_list_item', + list_id: 'endpoint_list_id', + meta: META, + name: NAME, + namespace_type: NAMESPACE_TYPE, + os_types: [], + tags: ['user added string for a tag', 'malware'], + tie_breaker_id: TIE_BREAKER, + type: ITEM_TYPE, + updated_at: DATE_NOW, + updated_by: USER, + ...(overrides || {}), +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = + (): Partial => ({ + comments: [], + created_by: ELASTIC_USER, + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + list_id: LIST_ID, + name: NAME, + namespace_type: 'single', + os_types: OS_TYPES, + tags: [], + type: ITEM_TYPE, + updated_by: ELASTIC_USER, + }); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.ts new file mode 100644 index 000000000000..1691221842d3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/found_list_schema.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { FoundListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { getListResponseMock } from './list_schema.mock'; + +export const getFoundListSchemaMock = (): FoundListSchema => ({ + cursor: '123', + data: [getListResponseMock()], + page: 1, + per_page: 1, + total: 1, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.ts new file mode 100644 index 000000000000..b2b66ad4636c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/mocks/response/list_schema.mock.ts @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { + DATE_NOW, + DESCRIPTION, + ELASTIC_USER, + IMMUTABLE, + LIST_ID, + META, + NAME, + TIE_BREAKER, + TYPE, + USER, + VERSION, +} from '../constants.mock'; + +export const getListResponseMock = (): ListSchema => ({ + '@timestamp': DATE_NOW, + _version: undefined, + created_at: DATE_NOW, + created_by: USER, + description: DESCRIPTION, + deserializer: undefined, + id: LIST_ID, + immutable: IMMUTABLE, + meta: META, + name: NAME, + serializer: undefined, + tie_breaker_id: TIE_BREAKER, + type: TYPE, + updated_at: DATE_NOW, + updated_by: USER, + version: VERSION, +}); + +/** + * This is useful for end to end tests where we remove the auto generated parts for comparisons + * such as created_at, updated_at, and id. + */ +export const getListResponseMockWithoutAutoGeneratedValues = (): Partial => ({ + created_by: ELASTIC_USER, + description: DESCRIPTION, + immutable: IMMUTABLE, + name: NAME, + type: TYPE, + updated_by: ELASTIC_USER, + version: VERSION, +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts new file mode 100644 index 000000000000..dc94fcddd849 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.test.ts @@ -0,0 +1,297 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { + CreateExceptionListItemSchema, + Entry, + EntryMatch, + EntryNested, + ExceptionListItemSchema, + UpdateExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { + addIdToExceptionItemEntries, + removeIdFromExceptionItemsEntries, + transformInput, + transformOutput, +} from '../..'; + +import { getCreateExceptionListItemSchemaMock } from '../mocks/request/create_exception_list_item_schema.mock'; +import { getUpdateExceptionListItemSchemaMock } from '../mocks/request/update_exception_list_item_schema.mock'; +import { getExceptionListItemSchemaMock } from '../mocks/response/exception_list_item_schema.mock'; +import { COMMENTS_WITH_CREATEDAT_CREATEDBY, ENTRIES_WITH_IDS } from '../mocks/constants.mock'; + +jest.mock('uuid', () => ({ + v4: jest.fn().mockReturnValue('123'), +})); + +describe('Exceptions transforms', () => { + describe('transformOutput', () => { + it('should return same output as input with stripped ids per entry - CreateExceptionListItemSchema', () => { + const mockCreateExceptionItem = { + ...getCreateExceptionListItemSchemaMock(), + entries: ENTRIES_WITH_IDS, + }; + const output = transformOutput(mockCreateExceptionItem); + const expectedOutput: CreateExceptionListItemSchema = getCreateExceptionListItemSchemaMock(); + + expect(output).toEqual(expectedOutput); + }); + + it('should return same output as input with stripped ids per entry - UpdateExceptionListItemSchema', () => { + const mockUpdateExceptionItem = { + ...getUpdateExceptionListItemSchemaMock(), + entries: ENTRIES_WITH_IDS, + }; + const output = transformOutput(mockUpdateExceptionItem); + const expectedOutput: UpdateExceptionListItemSchema = getUpdateExceptionListItemSchemaMock(); + + expect(output).toEqual(expectedOutput); + }); + it('should return output as input with stripped createdAt and createdBy per entry - UpdateExceptionListItemSchema', () => { + const mockUpdateExceptionItem = { + ...getUpdateExceptionListItemSchemaMock(), + entries: ENTRIES_WITH_IDS, + comments: COMMENTS_WITH_CREATEDAT_CREATEDBY, + }; + const output = transformOutput(mockUpdateExceptionItem); + const expectedOutput: UpdateExceptionListItemSchema = getUpdateExceptionListItemSchemaMock(); + + expect(output).toEqual(expectedOutput); + }); + }); + + describe('transformInput', () => { + it('should return same output as input with added ids per entry', () => { + const mockExceptionItem = getExceptionListItemSchemaMock(); + const output = transformInput(mockExceptionItem); + const expectedOutput: ExceptionListItemSchema = { + ...getExceptionListItemSchemaMock(), + entries: ENTRIES_WITH_IDS, + }; + + expect(output).toEqual(expectedOutput); + }); + }); + + describe('addIdToExceptionItemEntries', () => { + it('should return same output as input with added ids per entry', () => { + const mockExceptionItem: ExceptionListItemSchema = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + }; + const output = addIdToExceptionItemEntries(mockExceptionItem); + const expectedOutput: ExceptionListItemSchema = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as Entry & { id: string }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + + it('should return same output as input with added ids per nested entry', () => { + const mockExceptionItem: ExceptionListItemSchema = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + field: 'some.parentField', + type: 'nested', + }, + ], + }; + const output = addIdToExceptionItemEntries(mockExceptionItem); + const expectedOutput: ExceptionListItemSchema = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as EntryMatch & { id: string }, + ], + field: 'some.parentField', + id: '123', + type: 'nested', + } as EntryNested & { id: string }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + }); + + describe('removeIdFromExceptionItemsEntries', () => { + it('should return same output as input with stripped ids per entry - CreateExceptionListItemSchema', () => { + const mockCreateExceptionItem = { + ...getCreateExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as Entry & { id: string }, + ], + }; + const output = removeIdFromExceptionItemsEntries(mockCreateExceptionItem); + const expectedOutput: CreateExceptionListItemSchema = { + ...getCreateExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + + it('should return same output as input with stripped ids per nested entry - CreateExceptionListItemSchema', () => { + const mockCreateExceptionItem = { + ...getCreateExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as EntryMatch & { id: string }, + ], + field: 'some.parentField', + id: '123', + type: 'nested', + } as EntryNested & { id: string }, + ], + }; + const output = removeIdFromExceptionItemsEntries(mockCreateExceptionItem); + const expectedOutput: CreateExceptionListItemSchema = { + ...getCreateExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + field: 'some.parentField', + type: 'nested', + }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + + it('should return same output as input with stripped ids per entry - UpdateExceptionListItemSchema', () => { + const mockUpdateExceptionItem = { + ...getUpdateExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as Entry & { id: string }, + ], + }; + const output = removeIdFromExceptionItemsEntries(mockUpdateExceptionItem); + const expectedOutput: UpdateExceptionListItemSchema = { + ...getUpdateExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + + it('should return same output as input with stripped ids per nested entry - UpdateExceptionListItemSchema', () => { + const mockUpdateExceptionItem = { + ...getUpdateExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + id: '123', + operator: 'included', + type: 'match', + value: 'some value', + } as EntryMatch & { id: string }, + ], + field: 'some.parentField', + id: '123', + type: 'nested', + } as EntryNested & { id: string }, + ], + }; + const output = removeIdFromExceptionItemsEntries(mockUpdateExceptionItem); + const expectedOutput: UpdateExceptionListItemSchema = { + ...getUpdateExceptionListItemSchemaMock(), + entries: [ + { + entries: [ + { + field: 'nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + field: 'some.parentField', + type: 'nested', + }, + ], + }; + + expect(output).toEqual(expectedOutput); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts new file mode 100644 index 000000000000..276c52b000af --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/transforms/index.ts @@ -0,0 +1,136 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { flow } from 'fp-ts/lib/function'; +import { addIdToItem, removeIdFromItem } from '@kbn/securitysolution-utils'; +import type { + CreateExceptionListItemSchema, + EntriesArray, + Entry, + ExceptionListItemSchema, + UpdateExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; + +// These are a collection of transforms that are UI specific and useful for UI concerns +// that are inserted between the API and the actual user interface. In some ways these +// might be viewed as technical debt or to compensate for the differences and preferences +// of how ReactJS might prefer data vs. how we want to model data. Each function should have +// a description giving context around the transform. + +/** + * Transforms the output of exception items to compensate for technical debt or UI concerns such as + * ReactJS preferences for having ids within arrays if the data is not modeled that way. + * + * If you add a new transform of the output called "myNewTransform" do it + * in the form of: + * flow(removeIdFromExceptionItemsEntries, myNewTransform)(exceptionItem) + * + * @param exceptionItem The exceptionItem to transform the output of + * @returns The exceptionItem transformed from the output + */ +export const transformOutput = ( + exceptionItem: UpdateExceptionListItemSchema | ExceptionListItemSchema +): UpdateExceptionListItemSchema | ExceptionListItemSchema => + flow( + removeCreatedAtCreatedByFromCommentsOnUpdate, + removeIdFromExceptionItemsEntries + )(exceptionItem); + +export const transformNewItemOutput = ( + exceptionItem: CreateExceptionListItemSchema +): CreateExceptionListItemSchema => flow(removeIdFromExceptionItemsEntries)(exceptionItem); + +/** + * Transforms the output of rules to compensate for technical debt or UI concerns such as + * ReactJS preferences for having ids within arrays if the data is not modeled that way. + * + * If you add a new transform of the input called "myNewTransform" do it + * in the form of: + * flow(addIdToExceptionItemEntries, myNewTransform)(exceptionItem) + * + * @param exceptionItem The exceptionItem to transform the output of + * @returns The exceptionItem transformed from the output + */ +export const transformInput = (exceptionItem: ExceptionListItemSchema): ExceptionListItemSchema => + flow(addIdToExceptionItemEntries)(exceptionItem); + +/** + * This adds an id to the incoming exception item entries as ReactJS prefers to have + * an id added to them for use as a stable id. Later if we decide to change the data + * model to have id's within the array then this code should be removed. If not, then + * this code should stay as an adapter for ReactJS. + * + * This does break the type system slightly as we are lying a bit to the type system as we return + * the same exceptionItem as we have previously but are augmenting the arrays with an id which TypeScript + * doesn't mind us doing here. However, downstream you will notice that you have an id when the type + * does not indicate it. In that case use (ExceptionItem & { id: string }) temporarily if you're using the id. If you're not, + * you can ignore the id and just use the normal TypeScript with ReactJS. + * + * @param exceptionItem The exceptionItem to add an id to the threat matches. + * @returns exceptionItem The exceptionItem but with id added to the exception item entries + */ +export const addIdToExceptionItemEntries = ( + exceptionItem: ExceptionListItemSchema +): ExceptionListItemSchema => { + const entries = exceptionItem.entries.map((entry) => { + if (entry.type === 'nested') { + return addIdToItem({ + ...entry, + entries: entry.entries.map((nestedEntry) => addIdToItem(nestedEntry)), + }); + } else { + return addIdToItem(entry); + } + }); + return { ...exceptionItem, entries }; +}; + +/** + * This removes an id from the exceptionItem entries as ReactJS prefers to have + * an id added to them for use as a stable id. Later if we decide to change the data + * model to have id's within the array then this code should be removed. If not, then + * this code should stay as an adapter for ReactJS. + * + * @param exceptionItem The exceptionItem to remove an id from the entries. + * @returns exceptionItem The exceptionItem but with id removed from the entries + */ +export const removeIdFromExceptionItemsEntries = ( + exceptionItem: T +): T => { + const { entries } = exceptionItem; + const entriesNoId = entries.map((entry) => { + if (entry.type === 'nested') { + return removeIdFromItem({ + ...entry, + entries: entry.entries.map((nestedEntry) => removeIdFromItem(nestedEntry)), + }); + } else { + return removeIdFromItem(entry); + } + }); + return { ...exceptionItem, entries: entriesNoId }; +}; + +/** + * This removes createdAt, createdBy from the exceptionItem if a comment was added to + * the Exception item, and return the comment message with id to prevent creating the commet + * twice + * @param exceptionItem The exceptionItem to remove createdAt, createdBy from the comments array. + * @returns exceptionItem The exceptionItem with comments do not have createdAt, createdBy. + */ +export const removeCreatedAtCreatedByFromCommentsOnUpdate = ( + exceptionItem: UpdateExceptionListItemSchema | ExceptionListItemSchema +) => { + const { comments } = exceptionItem; + if (!comments || !comments.length) return exceptionItem; + + const entriesNoCreatedAtAndBy = comments.map(({ comment, id }) => ({ + comment, + id, + })); + return { ...exceptionItem, comments: entriesNoCreatedAtAndBy }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts new file mode 100644 index 000000000000..673eaff90b1a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_api/index.ts @@ -0,0 +1,315 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useMemo } from 'react'; +import type { + CreateExceptionListItemSchema, + ExceptionListItemSchema, + ExceptionListSchema, + UpdateExceptionListItemSchema, + ApiCallFindListsItemsMemoProps, + ApiCallMemoProps, + ApiListExportProps, + ApiCallGetExceptionFilterFromIdsMemoProps, + ApiCallGetExceptionFilterFromExceptionsMemoProps, + ApiListDuplicateProps, +} from '@kbn/securitysolution-io-ts-list-types'; +import * as Api from '@kbn/securitysolution-list-api'; +import { getIdsAndNamespaces } from '@kbn/securitysolution-list-utils'; +import type { HttpStart } from '@kbn/core-http-browser'; + +import { transformInput, transformNewItemOutput, transformOutput } from '../transforms'; + +export interface ExceptionsApi { + addExceptionListItem: (arg: { + listItem: CreateExceptionListItemSchema; + }) => Promise; + updateExceptionListItem: (arg: { + listItem: UpdateExceptionListItemSchema; + }) => Promise; + deleteExceptionItem: (arg: ApiCallMemoProps) => Promise; + deleteExceptionList: (arg: ApiCallMemoProps) => Promise; + duplicateExceptionList: (arg: ApiListDuplicateProps) => Promise; + getExceptionItem: ( + arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void } + ) => Promise; + getExceptionList: ( + arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void } + ) => Promise; + getExceptionListsItems: (arg: ApiCallFindListsItemsMemoProps) => Promise; + getExceptionFilterFromIds: (arg: ApiCallGetExceptionFilterFromIdsMemoProps) => Promise; + getExceptionFilterFromExceptions: ( + arg: ApiCallGetExceptionFilterFromExceptionsMemoProps + ) => Promise; + exportExceptionList: (arg: ApiListExportProps) => Promise; +} + +export const useApi = (http: HttpStart): ExceptionsApi => { + return useMemo( + (): ExceptionsApi => ({ + async addExceptionListItem({ + listItem, + }: { + listItem: CreateExceptionListItemSchema; + }): Promise { + const abortCtrl = new AbortController(); + const sanitizedItem: CreateExceptionListItemSchema = transformNewItemOutput(listItem); + + return Api.addExceptionListItem({ + http, + listItem: sanitizedItem, + signal: abortCtrl.signal, + }); + }, + async deleteExceptionItem({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps): Promise { + const abortCtrl = new AbortController(); + + try { + await Api.deleteExceptionListItemById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(); + } catch (error) { + onError(error); + } + }, + async deleteExceptionList({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps): Promise { + const abortCtrl = new AbortController(); + + try { + await Api.deleteExceptionListById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(); + } catch (error) { + onError(error); + } + }, + async duplicateExceptionList({ + includeExpiredExceptions, + listId, + namespaceType, + onError, + onSuccess, + }: ApiListDuplicateProps): Promise { + const abortCtrl = new AbortController(); + + try { + const newList = await Api.duplicateExceptionList({ + http, + includeExpiredExceptions, + listId, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(newList); + } catch (error) { + onError(error); + } + }, + async exportExceptionList({ + id, + includeExpiredExceptions, + listId, + namespaceType, + onError, + onSuccess, + }: ApiListExportProps): Promise { + const abortCtrl = new AbortController(); + + try { + const blob = await Api.exportExceptionList({ + http, + id, + includeExpiredExceptions, + listId, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(blob); + } catch (error) { + onError(error); + } + }, + async getExceptionItem({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void }): Promise { + const abortCtrl = new AbortController(); + + try { + const item = transformInput( + await Api.fetchExceptionListItemById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }) + ); + onSuccess(item); + } catch (error) { + onError(error); + } + }, + async getExceptionList({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void }): Promise { + const abortCtrl = new AbortController(); + + try { + const list = await Api.fetchExceptionListById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(list); + } catch (error) { + onError(error); + } + }, + async getExceptionListsItems({ + lists, + filter, + pagination, + showDetectionsListsOnly, + showEndpointListsOnly, + onSuccess, + onError, + }: ApiCallFindListsItemsMemoProps): Promise { + const abortCtrl = new AbortController(); + const { ids, namespaces } = getIdsAndNamespaces({ + lists, + showDetection: showDetectionsListsOnly, + showEndpoint: showEndpointListsOnly, + }); + + try { + if (ids.length > 0 && namespaces.length > 0) { + const { + data, + page, + per_page: perPage, + total, + } = await Api.fetchExceptionListsItemsByListIds({ + filter, + http, + listIds: ids, + namespaceTypes: namespaces, + pagination, + signal: abortCtrl.signal, + }); + onSuccess({ + // This data transform is UI specific and useful for UI concerns + // to compensate for the differences and preferences of how ReactJS might prefer + // data vs. how we want to model data. View `transformInput` for more details + exceptions: data.map((item) => transformInput(item)), + pagination: { + page, + perPage, + total, + }, + }); + } else { + onSuccess({ + exceptions: [], + pagination: { + page: 0, + perPage: pagination.perPage != null ? pagination.perPage : 0, + total: 0, + }, + }); + } + } catch (error) { + onError(error); + } + }, + async getExceptionFilterFromIds({ + exceptionListIds, + chunkSize, + alias, + excludeExceptions, + onSuccess, + onError, + }: ApiCallGetExceptionFilterFromIdsMemoProps): Promise { + const abortCtrl = new AbortController(); + try { + const { filter } = await Api.getExceptionFilterFromExceptionListIds({ + http, + exceptionListIds, + signal: abortCtrl.signal, + chunkSize, + alias, + excludeExceptions, + }); + onSuccess(filter); + } catch (error) { + onError(error); + } + }, + async getExceptionFilterFromExceptions({ + exceptions, + chunkSize, + alias, + excludeExceptions, + onSuccess, + onError, + }: ApiCallGetExceptionFilterFromExceptionsMemoProps): Promise { + const abortCtrl = new AbortController(); + try { + const { filter } = await Api.getExceptionFilterFromExceptions({ + http, + exceptions, + signal: abortCtrl.signal, + chunkSize, + alias, + excludeExceptions, + }); + onSuccess(filter); + } catch (error) { + onError(error); + } + }, + async updateExceptionListItem({ + listItem, + }: { + listItem: UpdateExceptionListItemSchema; + }): Promise { + const abortCtrl = new AbortController(); + const sanitizedItem: UpdateExceptionListItemSchema = transformOutput(listItem); + + return Api.updateExceptionListItem({ + http, + listItem: sanitizedItem, + signal: abortCtrl.signal, + }); + }, + }), + [http] + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.ts new file mode 100644 index 000000000000..9cfaf30a9e2a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useMutation, useQueryClient } from '@tanstack/react-query'; + +import { createListIndex, ApiParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +import { READ_INDEX_QUERY_KEY } from '../constants'; + +const createListIndexWithOptionalSignal = withOptionalSignal(createListIndex); + +export const useCreateListIndex = ({ + http, + onError, +}: { + http: ApiParams['http']; + onError?: (err: unknown) => void; +}) => { + const queryClient = useQueryClient(); + + const { mutate, isLoading, error } = useMutation( + () => createListIndexWithOptionalSignal({ http }), + { + onSuccess: () => { + queryClient.invalidateQueries(READ_INDEX_QUERY_KEY); + }, + onError, + } + ); + + return { + start: mutate, + loading: isLoading, + error, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.ts new file mode 100644 index 000000000000..eaafc36d8733 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_item/index.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { UseMutationOptions } from '@tanstack/react-query'; +import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { useMutation } from '@tanstack/react-query'; +import { createListItem } from '@kbn/securitysolution-list-api'; +import type { CreateListItemParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +import { useInvalidateListItemQuery } from '../use_find_list_items'; + +const createListItemWithOptionalSignal = withOptionalSignal(createListItem); + +export const CREATE_LIST_ITEM_MUTATION_KEY = ['POST', 'LIST_ITEM_CREATE']; +type CreateListMutationParams = Omit; + +export const useCreateListItemMutation = ( + options?: UseMutationOptions, CreateListMutationParams> +) => { + const invalidateListItemQuery = useInvalidateListItemQuery(); + return useMutation, CreateListMutationParams>( + ({ listId, value, http }) => + createListItemWithOptionalSignal({ listId, value, http, refresh: 'wait_for' }), + { + ...options, + mutationKey: CREATE_LIST_ITEM_MUTATION_KEY, + onSettled: (...args) => { + invalidateListItemQuery(); + if (options?.onSettled) { + options.onSettled(...args); + } + }, + } + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts new file mode 100644 index 000000000000..714c310f6d5e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.test.ts @@ -0,0 +1,119 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { renderHook, act } from '@testing-library/react'; + +import { UseCursorProps, useCursor } from '.'; + +describe('useCursor', () => { + it('returns undefined cursor if no values have been set', () => { + const { result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + expect(result.current[0]).toBeUndefined(); + }); + + it('retrieves a cursor for the next page of a given page size', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + + expect(result.current[0]).toBeUndefined(); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + }); + + it('returns undefined cursor for an unknown search', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + act(() => { + result.current[1]('new_cursor'); + }); + + rerender({ pageIndex: 1, pageSize: 2 }); + expect(result.current[0]).toBeUndefined(); + }); + + it('remembers cursor through rerenders', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + + rerender({ pageIndex: 0, pageSize: 0 }); + expect(result.current[0]).toBeUndefined(); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + }); + + it('remembers multiple cursors', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + rerender({ pageIndex: 2, pageSize: 2 }); + act(() => { + result.current[1]('another_cursor'); + }); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + + rerender({ pageIndex: 3, pageSize: 2 }); + expect(result.current[0]).toEqual('another_cursor'); + }); + + it('returns the "nearest" cursor for the given page size', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 2 }); + act(() => { + result.current[1]('cursor1'); + }); + rerender({ pageIndex: 2, pageSize: 2 }); + act(() => { + result.current[1]('cursor2'); + }); + rerender({ pageIndex: 3, pageSize: 2 }); + act(() => { + result.current[1]('cursor3'); + }); + + rerender({ pageIndex: 2, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor1'); + + rerender({ pageIndex: 3, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor2'); + + rerender({ pageIndex: 4, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor3'); + + rerender({ pageIndex: 6, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor3'); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts new file mode 100644 index 000000000000..1bc85c63363c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_cursor/index.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useState } from 'react'; + +export interface UseCursorProps { + pageIndex: number; + pageSize: number; +} +type Cursor = string | undefined; +type SetCursor = (cursor: Cursor) => void; +type UseCursor = (props: UseCursorProps) => [Cursor, SetCursor]; + +const hash = (props: UseCursorProps): string => JSON.stringify(props); + +export const useCursor: UseCursor = ({ pageIndex, pageSize }) => { + const [cache, setCache] = useState>({}); + + const setCursor = useCallback( + (cursor) => { + setCache({ + ...cache, + [hash({ pageIndex: pageIndex + 1, pageSize })]: cursor, + }); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [pageIndex, pageSize] + ); + + let cursor: Cursor; + for (let i = pageIndex; i >= 0; i--) { + const currentProps = { pageIndex: i, pageSize }; + cursor = cache[hash(currentProps)]; + if (cursor) { + break; + } + } + + return [cursor, setCursor]; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts new file mode 100644 index 000000000000..ae427947ab66 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { deleteList } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const deleteListWithOptionalSignal = withOptionalSignal(deleteList); + +export const useDeleteList = () => useAsync(deleteListWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts new file mode 100644 index 000000000000..04c608f9c841 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list_item/index.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { UseMutationOptions } from '@tanstack/react-query'; +import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { useMutation } from '@tanstack/react-query'; +import { deleteListItem } from '@kbn/securitysolution-list-api'; +import type { IHttpFetchError } from '@kbn/core-http-browser'; +import type { DeleteListItemParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; +import { useInvalidateListItemQuery } from '../use_find_list_items'; + +const deleteListItemWithOptionalSignal = withOptionalSignal(deleteListItem); + +export const DELETE_LIST_ITEM_MUTATION_KEY = ['POST', ' DELETE_LIST_ITEM_MUTATION']; +type DeleteListMutationParams = Omit; + +export const useDeleteListItemMutation = ( + options?: UseMutationOptions, DeleteListMutationParams> +) => { + const invalidateListItemQuery = useInvalidateListItemQuery(); + return useMutation, DeleteListMutationParams>( + ({ id, http }) => deleteListItemWithOptionalSignal({ id, http }), + { + ...options, + mutationKey: DELETE_LIST_ITEM_MUTATION_KEY, + onSettled: (...args) => { + invalidateListItemQuery(); + if (options?.onSettled) { + options.onSettled(...args); + } + }, + } + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts new file mode 100644 index 000000000000..8a8e2aadf258 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts @@ -0,0 +1,140 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { + ExceptionListSchema, + UseExceptionListsProps, + Pagination, + Sort, +} from '@kbn/securitysolution-io-ts-list-types'; +import { fetchExceptionLists } from '@kbn/securitysolution-list-api'; + +import { getFilters } from '@kbn/securitysolution-list-utils'; + +export type Func = () => void; +export type ReturnExceptionLists = [ + loading: boolean, + exceptionLists: ExceptionListSchema[], + pagination: Pagination, + setPagination: React.Dispatch>, + fetchLists: Func | null, + sort: Sort, + setSort: React.Dispatch> +]; + +const DEFAULT_PAGINATION = { + page: 1, + perPage: 20, + total: 0, +}; + +const DEFAULT_SORT = { + field: 'created_at', + order: 'desc', +}; + +/** + * Hook for fetching ExceptionLists + * + * @param http Kibana http service + * @param errorMessage message shown to user if error occurs + * @param filterOptions filter by certain fields + * @param namespaceTypes spaces to be searched + * @param notifications kibana service for displaying toasters + * @param hideLists a list of listIds we don't want to query + * @param initialPagination + * + */ +export const useExceptionLists = ({ + errorMessage, + http, + initialPagination = DEFAULT_PAGINATION, + filterOptions = {}, + namespaceTypes, + notifications, + hideLists = [], + initialSort = DEFAULT_SORT, +}: UseExceptionListsProps): ReturnExceptionLists => { + const [exceptionLists, setExceptionLists] = useState([]); + const [pagination, setPagination] = useState(initialPagination); + const [sort, setSort] = useState(initialSort); + const [loading, setLoading] = useState(true); + const abortCtrlRef = useRef(); + + const namespaceTypesAsString = useMemo(() => namespaceTypes.join(','), [namespaceTypes]); + const filters = useMemo( + (): string => + getFilters({ + filters: filterOptions, + namespaceTypes, + hideLists, + }), + [namespaceTypes, filterOptions, hideLists] + ); + + const fetchData = useCallback(async (): Promise => { + try { + setLoading(true); + + abortCtrlRef.current = new AbortController(); + + const { + page, + per_page: perPage, + total, + data, + } = await fetchExceptionLists({ + filters, + http, + namespaceTypes: namespaceTypesAsString, + pagination: { + page: pagination.page, + perPage: pagination.perPage, + }, + sort, + signal: abortCtrlRef.current.signal, + }); + + setPagination({ + page, + perPage, + total, + }); + setExceptionLists(data); + setLoading(false); + } catch (error) { + if (error.name !== 'AbortError') { + notifications.toasts.addError(error, { + title: errorMessage, + }); + setExceptionLists([]); + setPagination(DEFAULT_PAGINATION); + setLoading(false); + } + } + }, [ + errorMessage, + filters, + http, + namespaceTypesAsString, + notifications.toasts, + pagination.page, + pagination.perPage, + sort, + ]); + + useEffect(() => { + fetchData(); + + return (): void => { + abortCtrlRef.current?.abort(); + }; + }, [fetchData]); + + return [loading, exceptionLists, pagination, setPagination, fetchData, sort, setSort]; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts new file mode 100644 index 000000000000..bdaec5e50361 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { exportList } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const exportListWithOptionalSignal = withOptionalSignal(exportList); + +export const useExportList = () => useAsync(exportListWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts new file mode 100644 index 000000000000..86ed9892fa95 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_list_items/index.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useCallback } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { findListItems, ApiParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; +import { useCursor } from '../use_cursor'; + +const findListItemsWithOptionalSignal = withOptionalSignal(findListItems); + +const FIND_LIST_ITEMS_QUERY_KEY = 'FIND_LIST_ITEMS'; + +export const useInvalidateListItemQuery = () => { + const queryClient = useQueryClient(); + + return useCallback(() => { + queryClient.invalidateQueries([FIND_LIST_ITEMS_QUERY_KEY], { + refetchType: 'active', + }); + }, [queryClient]); +}; + +export const useFindListItems = ({ + pageIndex, + pageSize, + sortField, + sortOrder, + listId, + filter, + http, +}: { + pageIndex: number; + pageSize: number; + sortField: string; + sortOrder: 'asc' | 'desc'; + listId: string; + filter: string; + http: ApiParams['http']; +}) => { + const [cursor, setCursor] = useCursor({ pageIndex, pageSize }); + return useQuery( + [FIND_LIST_ITEMS_QUERY_KEY, pageIndex, pageSize, sortField, sortOrder, listId, filter], + async ({ signal }) => { + const response = await findListItemsWithOptionalSignal({ + http, + signal, + pageIndex, + pageSize, + sortField, + sortOrder, + listId, + cursor, + filter, + }); + return response; + }, + { + keepPreviousData: true, + refetchOnWindowFocus: false, + retry: false, + onSuccess: (data) => { + if (data?.cursor) { + setCursor(data?.cursor); + } + }, + } + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts new file mode 100644 index 000000000000..0c60b3ebebb3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.test.ts @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { waitFor, renderHook, act } from '@testing-library/react'; + +import { useFindLists } from '.'; +import { httpServiceMock } from '@kbn/core-http-browser-mocks'; +import * as Api from '@kbn/securitysolution-list-api'; + +import { getFoundListSchemaMock } from '../mocks/response/found_list_schema.mock'; + +jest.mock('@kbn/securitysolution-list-api'); + +describe('useFindLists', () => { + let httpMock: ReturnType; + + beforeEach(() => { + httpMock = httpServiceMock.createStartContract(); + (Api.findLists as jest.Mock).mockResolvedValue(getFoundListSchemaMock()); + }); + + it('invokes Api.findLists', async () => { + const { result } = renderHook(() => useFindLists()); + act(() => { + result.current.start({ http: httpMock, pageIndex: 1, pageSize: 10 }); + }); + await waitFor(() => + expect(Api.findLists).toHaveBeenCalledWith( + expect.objectContaining({ http: httpMock, pageIndex: 1, pageSize: 10 }) + ) + ); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts new file mode 100644 index 000000000000..0ad30728be4a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { findLists } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const findListsWithOptionalSignal = withOptionalSignal(findLists); + +export const useFindLists = () => useAsync(findListsWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts new file mode 100644 index 000000000000..e1132bdaab29 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_find_lists_by_size/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { findListsBySize } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const findListsBySizeWithOptionalSignal = withOptionalSignal(findListsBySize); + +export const useFindListsBySize = () => useAsync(findListsBySizeWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.ts new file mode 100644 index 000000000000..394b48352a32 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_get_list_by_id/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useQuery } from '@tanstack/react-query'; +import { getListById, ApiParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const getListByIdWithOptionalSignal = withOptionalSignal(getListById); + +const GET_LIST_BY_ID_QUERY_KEY = 'GET_LIST_BY_ID'; +export const useGetListById = ({ http, id }: { http: ApiParams['http']; id: string }) => { + return useQuery( + [GET_LIST_BY_ID_QUERY_KEY, id], + async ({ signal }) => { + const respone = await getListByIdWithOptionalSignal({ http, signal, id }); + return respone; + }, + { + refetchOnWindowFocus: false, + } + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts new file mode 100644 index 000000000000..4499b7220128 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { importList } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const importListWithOptionalSignal = withOptionalSignal(importList); + +export const useImportList = () => useAsync(importListWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.ts new file mode 100644 index 000000000000..e321006a0b68 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_patch_list_item/index.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { UseMutationOptions } from '@tanstack/react-query'; +import type { ListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; +import { useMutation } from '@tanstack/react-query'; +import type { PatchListItemParams } from '@kbn/securitysolution-list-api'; +import { patchListItem } from '@kbn/securitysolution-list-api'; +import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; +import { useInvalidateListItemQuery } from '../use_find_list_items'; + +const patchListItemWithOptionalSignal = withOptionalSignal(patchListItem); + +export const PATCH_LIST_ITEM_MUTATION_KEY = ['PATCH', 'LIST_ITEM_MUTATION']; +type PatchListMutationParams = Omit; + +export const usePatchListItemMutation = ( + options?: UseMutationOptions, PatchListMutationParams> +) => { + const invalidateListItemQuery = useInvalidateListItemQuery(); + return useMutation, PatchListMutationParams>( + ({ id, value, _version, http }: PatchListMutationParams) => + patchListItemWithOptionalSignal({ id, value, http, refresh: 'true', _version }), + { + ...options, + mutationKey: PATCH_LIST_ITEM_MUTATION_KEY, + onSettled: (...args) => { + invalidateListItemQuery(); + if (options?.onSettled) { + options.onSettled(...args); + } + }, + } + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts new file mode 100644 index 000000000000..ad239016ed05 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.ts @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Dispatch, useEffect, useRef, useState } from 'react'; +import type { + CreateExceptionListItemSchema, + PersistHookProps, + UpdateExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { addExceptionListItem, updateExceptionListItem } from '@kbn/securitysolution-list-api'; + +import { transformNewItemOutput, transformOutput } from '../transforms'; + +interface PersistReturnExceptionItem { + isLoading: boolean; + isSaved: boolean; +} + +export type ReturnPersistExceptionItem = [ + PersistReturnExceptionItem, + Dispatch +]; + +// TODO: Add this to @kbn/securitysolution-list-hooks + +/** + * Hook for creating or updating ExceptionListItem + * + * @param http Kibana http service + * @param onError error callback + * + */ +export const usePersistExceptionItem = ({ + http, + onError, +}: PersistHookProps): ReturnPersistExceptionItem => { + const [exceptionListItem, setExceptionItem] = useState< + CreateExceptionListItemSchema | UpdateExceptionListItemSchema | null + >(null); + const [isSaved, setIsSaved] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const isUpdateExceptionItem = (item: unknown): item is UpdateExceptionListItemSchema => + Boolean(item && (item as UpdateExceptionListItemSchema).id != null); + const isSubscribed = useRef(false); + + useEffect(() => { + let abortCtrl: AbortController | null = null; + isSubscribed.current = true; + setIsSaved(false); + + const saveExceptionItem = async (): Promise => { + if (exceptionListItem === null) { + return; + } + + try { + abortCtrl = new AbortController(); + setIsLoading(true); + + if (isUpdateExceptionItem(exceptionListItem)) { + // Please see `x-pack/solutions/security/plugins/lists/public/exceptions/transforms.ts` doc notes + // for context around the temporary `id` + const transformedList = transformOutput(exceptionListItem); + + await updateExceptionListItem({ + http, + listItem: transformedList, + signal: abortCtrl.signal, + }); + } else { + // Please see `x-pack/solutions/security/plugins/lists/public/exceptions/transforms.ts` doc notes + // for context around the temporary `id` + const transformedList = transformNewItemOutput(exceptionListItem); + + await addExceptionListItem({ + http, + listItem: transformedList, + signal: abortCtrl.signal, + }); + } + + if (isSubscribed.current) { + setIsSaved(true); + } + } catch (error) { + if (isSubscribed.current) { + onError(error); + } + } finally { + if (isSubscribed.current) { + setIsLoading(false); + } + } + }; + + saveExceptionItem(); + + return (): void => { + isSubscribed.current = false; + abortCtrl?.abort(); + }; + }, [http, exceptionListItem, onError]); + + return [{ isLoading, isSaved }, setExceptionItem]; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.ts new file mode 100644 index 000000000000..6814a19679c5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.ts @@ -0,0 +1,79 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Dispatch, useEffect, useState } from 'react'; +import type { + AddExceptionList, + PersistHookProps, + UpdateExceptionListSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { addExceptionList, updateExceptionList } from '@kbn/securitysolution-list-api'; + +interface PersistReturnExceptionList { + isLoading: boolean; + isSaved: boolean; +} + +export type ReturnPersistExceptionList = [ + PersistReturnExceptionList, + Dispatch +]; + +/** + * Hook for creating or updating ExceptionList + * + * @param http Kibana http service + * @param onError error callback + * + */ +export const usePersistExceptionList = ({ + http, + onError, +}: PersistHookProps): ReturnPersistExceptionList => { + const [exceptionList, setExceptionList] = useState(null); + const [isSaved, setIsSaved] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const isUpdateExceptionList = (item: unknown): item is UpdateExceptionListSchema => + Boolean(item && (item as UpdateExceptionListSchema).id != null); + + useEffect(() => { + let isSubscribed = true; + const abortCtrl = new AbortController(); + setIsSaved(false); + + const saveExceptionList = async (): Promise => { + if (exceptionList != null) { + try { + setIsLoading(true); + if (isUpdateExceptionList(exceptionList)) { + await updateExceptionList({ http, list: exceptionList, signal: abortCtrl.signal }); + } else { + await addExceptionList({ http, list: exceptionList, signal: abortCtrl.signal }); + } + if (isSubscribed) { + setIsSaved(true); + } + } catch (error) { + if (isSubscribed) { + onError(error); + } + } + if (isSubscribed) { + setIsLoading(false); + } + } + }; + + saveExceptionList(); + return (): void => { + isSubscribed = false; + abortCtrl.abort(); + }; + }, [http, exceptionList, onError]); + + return [{ isLoading, isSaved }, setExceptionList]; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.ts new file mode 100644 index 000000000000..2bb2a7018857 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.ts @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useQuery } from '@tanstack/react-query'; + +import { readListIndex, ApiParams } from '@kbn/securitysolution-list-api'; +import { withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +import { READ_INDEX_QUERY_KEY } from '../constants'; + +const readListIndexWithOptionalSignal = withOptionalSignal(readListIndex); + +export const useReadListIndex = ({ + http, + isEnabled, + onError, +}: { + isEnabled: boolean; + http: ApiParams['http']; + onError?: (err: unknown) => void; +}) => { + const query = useQuery( + READ_INDEX_QUERY_KEY, + async ({ signal }) => { + if (!isEnabled) { + return null; + } + + return readListIndexWithOptionalSignal({ http, signal }); + }, + { + onError, + retry: false, + refetchOnWindowFocus: false, + enabled: isEnabled, + staleTime: Infinity, + } + ); + + return { + result: query.data, + loading: query.isFetching, + error: query.error, + }; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts new file mode 100644 index 000000000000..1e96118228b5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_privileges/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { readListPrivileges } from '@kbn/securitysolution-list-api'; +import { useAsync, withOptionalSignal } from '@kbn/securitysolution-hook-utils'; + +const readListPrivilegesWithOptionalSignal = withOptionalSignal(readListPrivileges); + +export const useReadListPrivileges = () => useAsync(readListPrivilegesWithOptionalSignal); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/tsconfig.json new file mode 100644 index 000000000000..f2583861bced --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts", + ], + "kbn_references": [ + "@kbn/securitysolution-hook-utils", + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-list-api", + "@kbn/securitysolution-list-utils", + "@kbn/securitysolution-utils", + "@kbn/core-http-browser-mocks", + "@kbn/core-http-browser", + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-list-utils/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/README.md similarity index 100% rename from packages/kbn-securitysolution-list-utils/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-list-utils/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/index.ts new file mode 100644 index 000000000000..cd6928dd89e3 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/autocomplete_operators'; +export * from './src/get_exception_list_type'; +export * from './src/get_filters'; +export * from './src/get_general_filters'; +export * from './src/get_ids_and_namespaces'; +export * from './src/get_saved_object_type'; +export * from './src/get_saved_object_types'; +export * from './src/has_large_value_list'; +export * from './src/helpers'; +export * from './src/types'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/jest.config.js new file mode 100644 index 000000000000..e3fc2abb342a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-list-utils'], +}; diff --git a/packages/kbn-securitysolution-list-utils/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-list-utils/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-list-utils/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/package.json new file mode 100644 index 000000000000..585acd8e3d70 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-list-utils", + "version": "1.0.0", + "description": "security solution list utilities", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts new file mode 100644 index 000000000000..430a0dbc3a1d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/autocomplete_operators/index.ts @@ -0,0 +1,158 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; +import { + ListOperatorEnum as OperatorEnum, + ListOperatorTypeEnum as OperatorTypeEnum, +} from '@kbn/securitysolution-io-ts-list-types'; +import { OperatorOption } from '../types'; + +export const isOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isOperatorLabel', { + defaultMessage: 'is', + }), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.MATCH, + value: 'is', +}; + +export const isNotOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isNotOperatorLabel', { + defaultMessage: 'is not', + }), + operator: OperatorEnum.EXCLUDED, + type: OperatorTypeEnum.MATCH, + value: 'is_not', +}; + +export const isOneOfOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isOneOfOperatorLabel', { + defaultMessage: 'is one of', + }), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.MATCH_ANY, + value: 'is_one_of', +}; + +export const isNotOneOfOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isNotOneOfOperatorLabel', { + defaultMessage: 'is not one of', + }), + operator: OperatorEnum.EXCLUDED, + type: OperatorTypeEnum.MATCH_ANY, + value: 'is_not_one_of', +}; + +export const existsOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.existsOperatorLabel', { + defaultMessage: 'exists', + }), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.EXISTS, + value: 'exists', +}; + +export const doesNotExistOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.doesNotExistOperatorLabel', { + defaultMessage: 'does not exist', + }), + operator: OperatorEnum.EXCLUDED, + type: OperatorTypeEnum.EXISTS, + value: 'does_not_exist', +}; + +export const isInListOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isInListOperatorLabel', { + defaultMessage: 'is in list', + }), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.LIST, + value: 'is_in_list', +}; + +export const isNotInListOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.isNotInListOperatorLabel', { + defaultMessage: 'is not in list', + }), + operator: OperatorEnum.EXCLUDED, + type: OperatorTypeEnum.LIST, + value: 'is_not_in_list', +}; + +export const matchesOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.matchesOperatorLabel', { + defaultMessage: 'matches', + }), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.WILDCARD, + value: 'matches', +}; + +export const doesNotMatchOperator: OperatorOption = { + message: i18n.translate('lists.exceptions.doesNotMatchOperatorLabel', { + defaultMessage: 'does not match', + }), + operator: OperatorEnum.EXCLUDED, + type: OperatorTypeEnum.WILDCARD, + value: 'does_not_match', +}; + +export const EVENT_FILTERS_OPERATORS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + matchesOperator, + doesNotMatchOperator, +]; + +/* + * !IMPORTANT! - Please only add to this list if it is an operator + * supported by the detection engine. + */ +export const DETECTION_ENGINE_EXCEPTION_OPERATORS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + isInListOperator, + isNotInListOperator, + matchesOperator, + doesNotMatchOperator, +]; + +export const ALL_OPERATORS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + isInListOperator, + isNotInListOperator, + matchesOperator, + doesNotMatchOperator, +]; + +export const EXCEPTION_OPERATORS_SANS_LISTS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + matchesOperator, + doesNotMatchOperator, +]; + +export const EXCEPTION_OPERATORS_ONLY_LISTS: OperatorOption[] = [ + isInListOperator, + isNotInListOperator, +]; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_exception_list_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_exception_list_type/index.ts new file mode 100644 index 000000000000..29dba94f7676 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_exception_list_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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; + +import { exceptionListAgnosticSavedObjectType } from '../types'; + +export const getExceptionListType = ({ + savedObjectType, +}: { + savedObjectType: string; +}): NamespaceType => { + if (savedObjectType === exceptionListAgnosticSavedObjectType) { + return 'agnostic'; + } else { + return 'single'; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts new file mode 100644 index 000000000000..a88a78479cf5 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.test.ts @@ -0,0 +1,207 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getFilters } from '.'; + +describe('getFilters', () => { + describe('single', () => { + test('it properly formats when no filters and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(not exception-list.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when no filters and hide lists contains one list id', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual('(not exception-list.attributes.list_id: listId-1*)'); + }); + test('it properly formats when no filters and no hide lists', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single'], + hideLists: [], + }); + + expect(filter).toEqual(''); + }); + test('it properly formats when filters passed and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when filters passed and hide lists contains one list id', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1*)' + ); + }); + test('it properly formats when filters passed and no hide lists', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single'], + hideLists: [], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample)' + ); + }); + }); + + describe('agnostic', () => { + test('it properly formats when no filters and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['agnostic'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list-agnostic.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when no filters and hide lists contains one list id', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['agnostic'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual('(not exception-list-agnostic.attributes.list_id: listId-1*)'); + }); + test('it properly formats when no filters and no hide lists', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['agnostic'], + hideLists: [], + }); + + expect(filter).toEqual(''); + }); + test('it properly formats when filters passed and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['agnostic'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list-agnostic.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when filters passed and hide lists contains one list id', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['agnostic'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual( + '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list-agnostic.attributes.list_id: listId-1*)' + ); + }); + test('it properly formats when filters passed and no hide lists', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['agnostic'], + hideLists: [], + }); + + expect(filter).toEqual( + '(exception-list-agnostic.attributes.created_by:moi) AND (exception-list-agnostic.attributes.name.text:Sample)' + ); + }); + }); + + describe('single, agnostic', () => { + test('it properly formats when no filters and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single', 'agnostic'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2* AND not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3* AND not exception-list-agnostic.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when no filters and hide lists contains one list id', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single', 'agnostic'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual( + '(not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*)' + ); + }); + test('it properly formats when no filters and no hide lists', () => { + const filter = getFilters({ + filters: {}, + namespaceTypes: ['single', 'agnostic'], + hideLists: [], + }); + + expect(filter).toEqual(''); + }); + test('it properly formats when filters passed and hide lists contains few list ids', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single', 'agnostic'], + hideLists: ['listId-1', 'listId-2', 'listId-3'], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*) AND (not exception-list.attributes.list_id: listId-2* AND not exception-list-agnostic.attributes.list_id: listId-2*) AND (not exception-list.attributes.list_id: listId-3* AND not exception-list-agnostic.attributes.list_id: listId-3*)' + ); + }); + test('it properly formats when filters passed and hide lists contains one list id', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single', 'agnostic'], + hideLists: ['listId-1'], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (not exception-list.attributes.list_id: listId-1* AND not exception-list-agnostic.attributes.list_id: listId-1*)' + ); + }); + test('it properly formats when filters passed and no hide lists', () => { + const filter = getFilters({ + filters: { created_by: 'moi', name: 'Sample' }, + namespaceTypes: ['single', 'agnostic'], + hideLists: [], + }); + + expect(filter).toEqual( + '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample)' + ); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.ts new file mode 100644 index 000000000000..2bc7960de792 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_filters/index.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExceptionListFilter, NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; +import { getGeneralFilters } from '../get_general_filters'; +import { getSavedObjectTypes } from '../get_saved_object_types'; +export interface GetFiltersParams { + filters: ExceptionListFilter; + namespaceTypes: NamespaceType[]; + hideLists: readonly string[]; +} + +export const getFilters = ({ filters, namespaceTypes, hideLists }: GetFiltersParams): string => { + const namespaces = getSavedObjectTypes({ namespaceType: namespaceTypes }); + const generalFilters = getGeneralFilters(filters, namespaces); + const hideListsFilters = hideLists.map((listId) => { + const filtersByNamespace = namespaces.map((namespace) => { + return `not ${namespace}.attributes.list_id: ${listId}*`; + }); + return `(${filtersByNamespace.join(' AND ')})`; + }); + + return [generalFilters, ...hideListsFilters] + .filter((filter) => filter.trim() !== '') + .join(' AND '); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.test.ts new file mode 100644 index 000000000000..026202349763 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.test.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; +import { getGeneralFilters } from '.'; + +describe('getGeneralFilters', () => { + test('it returns empty string if no filters', () => { + const filters = getGeneralFilters({}, ['exception-list']); + + expect(filters).toEqual(''); + }); + + test('it properly formats filters when one namespace type passed in', () => { + const filters = getGeneralFilters({ created_by: 'moi', name: 'Sample' }, ['exception-list']); + + expect(filters).toEqual( + '(exception-list.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample)' + ); + }); + + test('it properly formats filters when two namespace types passed in', () => { + const filters = getGeneralFilters({ created_by: 'moi', name: 'Sample' }, [ + 'exception-list', + 'exception-list-agnostic', + ]); + + expect(filters).toEqual( + '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample)' + ); + }); + + test('it properly formats filters when two types are passed in', () => { + const filters = getGeneralFilters( + { + created_by: 'moi', + name: 'Sample', + types: [ExceptionListTypeEnum.DETECTION, ExceptionListTypeEnum.RULE_DEFAULT], + }, + ['exception-list', 'exception-list-agnostic'] + ); + + expect(filters).toEqual( + '(exception-list.attributes.created_by:moi OR exception-list-agnostic.attributes.created_by:moi) AND (exception-list.attributes.name.text:Sample OR exception-list-agnostic.attributes.name.text:Sample) AND (exception-list.attributes.type:detection OR exception-list.attributes.type:rule_default OR exception-list-agnostic.attributes.type:detection OR exception-list-agnostic.attributes.type:rule_default)' + ); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts new file mode 100644 index 000000000000..7960617fad48 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_general_filters/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExceptionListFilter } from '@kbn/securitysolution-io-ts-list-types'; +import { isArray } from 'lodash'; +import { get } from 'lodash/fp'; +import { SavedObjectType } from '../types'; + +export const getGeneralFilters = ( + filters: ExceptionListFilter, + namespaceTypes: SavedObjectType[] +): string => { + return Object.keys(filters) + .map((filterKey) => { + const value = get(filterKey, filters); + if (isArray(value) || (value != null && value.trim() !== '')) { + const filtersByNamespace = namespaceTypes + .map((namespace) => { + const fieldToSearch = + filterKey === 'name' ? 'name.text' : filterKey === 'types' ? 'type' : filterKey; + return isArray(value) + ? value.map((val) => `${namespace}.attributes.${fieldToSearch}:${val}`).join(' OR ') + : `${namespace}.attributes.${fieldToSearch}:${value}`; + }) + .join(' OR '); + return `(${filtersByNamespace})`; + } else return null; + }) + .filter((item) => item != null) + .join(' AND '); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts new file mode 100644 index 000000000000..b76bc2df94ff --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getIdsAndNamespaces } from '.'; + +describe('getIdsAndNamespaces', () => { + test('it returns empty arrays if no lists found', async () => { + const output = getIdsAndNamespaces({ + lists: [], + showDetection: false, + showEndpoint: false, + }); + + expect(output).toEqual({ ids: [], namespaces: [] }); + }); + + test('it returns all lists if "showDetection" and "showEndpoint" are "false"', async () => { + const output = getIdsAndNamespaces({ + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + { + id: 'myListIdEndpoint', + listId: 'list_id_endpoint', + namespaceType: 'agnostic', + type: 'endpoint', + }, + ], + showDetection: false, + showEndpoint: false, + }); + + expect(output).toEqual({ + ids: ['list_id', 'list_id_endpoint'], + namespaces: ['single', 'agnostic'], + }); + }); + + test('it returns only detections lists if "showDetection" is "true"', async () => { + const output = getIdsAndNamespaces({ + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + { + id: 'myListIdEndpoint', + listId: 'list_id_endpoint', + namespaceType: 'agnostic', + type: 'endpoint', + }, + ], + showDetection: true, + showEndpoint: false, + }); + + expect(output).toEqual({ + ids: ['list_id'], + namespaces: ['single'], + }); + }); + + test('it returns only endpoint lists if "showEndpoint" is "true"', async () => { + const output = getIdsAndNamespaces({ + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + { + id: 'myListIdEndpoint', + listId: 'list_id_endpoint', + namespaceType: 'agnostic', + type: 'endpoint', + }, + ], + showDetection: false, + showEndpoint: true, + }); + + expect(output).toEqual({ + ids: ['list_id_endpoint'], + namespaces: ['agnostic'], + }); + }); + + test('it returns only detection lists if both "showEndpoint" and "showDetection" are "true"', async () => { + const output = getIdsAndNamespaces({ + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + { + id: 'myListIdEndpoint', + listId: 'list_id_endpoint', + namespaceType: 'agnostic', + type: 'endpoint', + }, + ], + showDetection: true, + showEndpoint: true, + }); + + expect(output).toEqual({ + ids: ['list_id'], + namespaces: ['single'], + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts new file mode 100644 index 000000000000..25a7ae1931e1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExceptionListIdentifiers, NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; + +export const getIdsAndNamespaces = ({ + lists, + showDetection, + showEndpoint, +}: { + lists: ExceptionListIdentifiers[]; + showDetection: boolean; + showEndpoint: boolean; +}): { ids: string[]; namespaces: NamespaceType[] } => + lists + .filter((list) => { + if (showDetection) { + return list.type === 'detection'; + } else if (showEndpoint) { + return list.type === 'endpoint'; + } else { + return true; + } + }) + .reduce<{ ids: string[]; namespaces: NamespaceType[] }>( + (acc, { listId, namespaceType }) => ({ + ids: [...acc.ids, listId], + namespaces: [...acc.namespaces, namespaceType], + }), + { ids: [], namespaces: [] } + ); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.ts new file mode 100644 index 000000000000..0ee1b134333c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_type/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; + +import { + exceptionListAgnosticSavedObjectType, + exceptionListSavedObjectType, + SavedObjectType, +} from '../types'; + +export const getSavedObjectType = ({ + namespaceType, +}: { + namespaceType: NamespaceType; +}): SavedObjectType => { + if (namespaceType === 'agnostic') { + return exceptionListAgnosticSavedObjectType; + } else { + return exceptionListSavedObjectType; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts new file mode 100644 index 000000000000..92b6ff4a9263 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/get_saved_object_types/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { NamespaceTypeArray } from '@kbn/securitysolution-io-ts-list-types'; + +import { SavedObjectType } from '../types'; +import { getSavedObjectType } from '../get_saved_object_type'; + +export const getSavedObjectTypes = ({ + namespaceType, +}: { + namespaceType: NamespaceTypeArray; +}): SavedObjectType[] => { + return namespaceType.map((singleNamespaceType) => + getSavedObjectType({ namespaceType: singleNamespaceType }) + ); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts new file mode 100644 index 000000000000..350cb581153b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/has_large_value_list/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { EntriesArray } from '@kbn/securitysolution-io-ts-list-types'; + +export const hasLargeValueList = (entries: EntriesArray): boolean => { + const found = entries.filter(({ type }) => type === 'list'); + return found.length > 0; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts new file mode 100644 index 000000000000..fe75ad88e012 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.test.ts @@ -0,0 +1,375 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + getMappingConflictsInfo, + fieldSupportsMatches, + hasWrongOperatorWithWildcard, + hasPartialCodeSignatureEntry, +} from '.'; + +describe('Helpers', () => { + describe('getMappingConflictsInfo', () => { + test('it return null if there are not conflicts', () => { + const field = { + name: 'field1', + type: 'string', + }; + const conflictsInfo = getMappingConflictsInfo(field); + + expect(conflictsInfo).toBeNull(); + }); + test('it groups ".ds-" data stream indices', () => { + const field = { + name: 'field1', + type: 'conflict', + conflictDescriptions: { + text: [ + '.ds-logs-default-2023.01.18-000001', + '.ds-logs-default-2023.01.18-000002', + '.ds-logs-tortilla.process-default-2022.11.20-000011', + '.ds-logs-tortilla.process-default-2022.11.20-000012', + '.ds-logs-tortilla.process-default-2022.11.20-000016', + ], + long: [ + '.ds-logs-default-2023.01.18-000004', + '.ds-logs-default-2023.01.18-000005', + 'partial-.ds-logs-gcp.audit-2021.12.22-000240', + 'partial-.ds-logs-gcp.audit-2021.12.22-000242', + ], + }, + }; + const conflictsInfo = getMappingConflictsInfo(field); + + expect(conflictsInfo).toEqual([ + { + type: 'text', + totalIndexCount: 5, + groupedIndices: [ + { name: 'logs-tortilla.process-default', count: 3 }, + { name: 'logs-default', count: 2 }, + ], + }, + { + type: 'long', + totalIndexCount: 4, + groupedIndices: [ + { name: 'logs-default', count: 2 }, + { name: 'logs-gcp.audit', count: 2 }, + ], + }, + ]); + }); + test('it groups old ".siem-" indices', () => { + const field = { + name: 'field1', + type: 'conflict', + conflictDescriptions: { + text: [ + '.siem-signals-default-000001', + '.siem-signals-default-000002', + '.siem-signals-default-000011', + '.siem-signals-default-000012', + ], + unmapped: [ + '.siem-signals-default-000004', + '.siem-signals-default-000005', + '.siem-signals-default-000240', + ], + }, + }; + const conflictsInfo = getMappingConflictsInfo(field); + + expect(conflictsInfo).toEqual([ + { + type: 'text', + totalIndexCount: 4, + groupedIndices: [{ name: '.siem-signals-default', count: 4 }], + }, + { + type: 'unmapped', + totalIndexCount: 3, + groupedIndices: [{ name: '.siem-signals-default', count: 3 }], + }, + ]); + }); + test('it groups mixed indices', () => { + const field = { + name: 'field1', + type: 'conflict', + conflictDescriptions: { + boolean: [ + '.ds-logs-default-2023.01.18-000001', + '.ds-logs-tortilla.process-default-2022.11.20-000011', + '.ds-logs-tortilla.process-default-2022.11.20-000012', + '.ds-logs-tortilla.process-default-2022.11.20-000016', + '.siem-signals-default-000001', + '.siem-signals-default-000002', + '.siem-signals-default-000012', + 'my-own-index-1', + 'my-own-index-2', + ], + unmapped: [ + '.siem-signals-default-000004', + 'partial-.ds-logs-gcp.audit-2021.12.22-000240', + 'partial-.ds-logs-gcp.audit-2021.12.22-000242', + 'my-own-index-3', + ], + }, + }; + const conflictsInfo = getMappingConflictsInfo(field); + + expect(conflictsInfo).toEqual([ + { + type: 'boolean', + totalIndexCount: 9, + groupedIndices: [ + { name: 'logs-tortilla.process-default', count: 3 }, + { name: '.siem-signals-default', count: 3 }, + { name: 'logs-default', count: 1 }, + { name: 'my-own-index-1', count: 1 }, + { name: 'my-own-index-2', count: 1 }, + ], + }, + { + type: 'unmapped', + totalIndexCount: 4, + groupedIndices: [ + { name: 'logs-gcp.audit', count: 2 }, + { name: '.siem-signals-default', count: 1 }, + { name: 'my-own-index-3', count: 1 }, + ], + }, + ]); + }); + }); + + describe('fieldSupportsMatches', () => { + test('it returns true if esTypes is keyword', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword'] }) + ).toBeTruthy(); + }); + + test('it returns true if one of the esTypes is kibana type string and another is not', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword', 'object'] }) + ).toBeTruthy(); + }); + + test('it returns true if one of the esTypes is keyword', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['keyword', 'unmapped'] }) + ).toBeTruthy(); + }); + + test('it returns true if one of the esTypes is text', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['text', 'unmapped'] }) + ).toBeTruthy(); + }); + + test('it returns true if all of the esTypes is map to kibana type string', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['text', 'keyword'] }) + ).toBeTruthy(); + }); + + test('it returns false if none of the esTypes map to kibana type string', () => { + expect( + fieldSupportsMatches({ name: 'field', type: 'conflict', esTypes: ['bool', 'unmapped'] }) + ).toBeFalsy(); + }); + }); + describe('hasWrongOperatorWithWildcard', () => { + test('it returns true if there is at least one exception entry with a wildcard and the wrong operator', () => { + expect( + hasWrongOperatorWithWildcard([ + { + description: '', + name: '', + type: 'simple', + entries: [{ type: 'match', value: 'withwildcard*', field: '', operator: 'included' }], + }, + ]) + ).toBeTruthy(); + expect( + hasWrongOperatorWithWildcard([ + { + description: '', + name: '', + type: 'simple', + entries: [{ type: 'match', value: 'withwildcard?', field: '', operator: 'included' }], + }, + ]) + ).toBeTruthy(); + }); + + test('it returns true if there are entries joined with an OR that have a wildcard and the wrong operator', () => { + expect( + hasWrongOperatorWithWildcard([ + { + description: '', + name: '', + type: 'simple', + entries: [{ type: 'match', value: 'withwildcard?', field: '', operator: 'included' }], + }, + { + description: '', + name: '', + type: 'simple', + entries: [{ type: 'match', value: 'withwildcard?*', field: '', operator: 'included' }], + }, + ]) + ).toBeTruthy(); + }); + + test('it returns false if there are no exception entries with a wildcard and the wrong operator', () => { + expect( + hasWrongOperatorWithWildcard([ + { + description: '', + name: '', + type: 'simple', + entries: [ + { type: 'match', value: 'nowildcard', field: '', operator: 'excluded' }, + { type: 'wildcard', value: 'withwildcard*?', field: '', operator: 'included' }, + ], + }, + ]) + ).toBeFalsy(); + }); + + test('it returns true if there are nested entries with a wildcard and the wrong operator', () => { + expect( + hasWrongOperatorWithWildcard([ + { + description: '', + name: '', + type: 'simple', + entries: [ + { type: 'match', value: 'nowildcard', field: '', operator: 'excluded' }, + { + field: '', + type: 'nested', + entries: [{ type: 'match', value: 'wildcard?', field: '', operator: 'excluded' }], + }, + ], + }, + ]) + ).toBeTruthy(); + }); + }); + + describe('hasPartialCodeSignatureEntry', () => { + it('returns false if the entry has neither code signature subject name nor trusted field', () => { + expect( + hasPartialCodeSignatureEntry([ + { + description: '', + name: '', + type: 'simple', + os_types: ['windows'], + entries: [{ type: 'match', value: 'asdf', field: 'someField', operator: 'excluded' }], + }, + ]) + ).toBeFalsy(); + }); + it('returns true if the entry has code signature subject name but not trusted field', () => { + expect( + hasPartialCodeSignatureEntry([ + { + description: '', + name: '', + type: 'simple', + os_types: ['windows'], + entries: [ + { + type: 'match', + value: 'asdf', + field: 'process.code_signature.subject_name', + operator: 'excluded', + }, + ], + }, + ]) + ).toBeTruthy(); + }); + it('returns true if the entry has code signature trusted but not the subject name field', () => { + expect( + hasPartialCodeSignatureEntry([ + { + description: '', + name: '', + type: 'simple', + os_types: ['windows'], + entries: [ + { + type: 'match', + value: 'asdf', + field: 'process.code_signature.trusted', + operator: 'excluded', + }, + ], + }, + ]) + ).toBeTruthy(); + }); + it('returns false if the entry has both code signature subject name and trusted field', () => { + expect( + hasPartialCodeSignatureEntry([ + { + description: '', + name: '', + type: 'simple', + os_types: ['windows'], + entries: [ + { + type: 'match', + value: 'asdf', + field: 'process.code_signature.subject_name', + operator: 'excluded', + }, + { + type: 'match', + value: 'true', + field: 'process.code_signature.trusted', + operator: 'excluded', + }, + ], + }, + ]) + ).toBeFalsy(); + }); + it('returns false if the entry has both code signature team_id and trusted fields for mac os', () => { + expect( + hasPartialCodeSignatureEntry([ + { + description: '', + name: '', + type: 'simple', + os_types: ['macos'], + entries: [ + { + type: 'match', + value: 'asdf', + field: 'process.code_signature.team_id', + operator: 'excluded', + }, + { + type: 'match', + value: 'true', + field: 'process.code_signature.trusted', + operator: 'excluded', + }, + ], + }, + ]) + ).toBeFalsy(); + }); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.ts new file mode 100644 index 000000000000..6cbdbe55cfeb --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/helpers/index.ts @@ -0,0 +1,1088 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { v4 as uuidv4 } from 'uuid'; +import { + addIdToItem, + removeIdFromItem, + validateHasWildcardWithWrongOperator, +} from '@kbn/securitysolution-utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; +import { + CreateExceptionListItemSchema, + EntriesArray, + Entry, + EntryNested, + ExceptionListType, + ListSchema, + NamespaceType, + ListOperatorEnum as OperatorEnum, + ListOperatorTypeEnum as OperatorTypeEnum, + createExceptionListItemSchema, + entriesList, + entriesNested, + entry, + exceptionListItemSchema, + nestedEntryItem, + CreateRuleExceptionListItemSchema, + createRuleExceptionListItemSchema, +} from '@kbn/securitysolution-io-ts-list-types'; +import { + DataViewBase, + DataViewFieldBase, + getDataViewFieldSubtypeNested, + isDataViewFieldSubtypeNested, +} from '@kbn/es-query'; +import { castEsToKbnFieldTypeName, KBN_FIELD_TYPES } from '@kbn/field-types'; + +import { + ALL_OPERATORS, + EXCEPTION_OPERATORS_SANS_LISTS, + doesNotExistOperator, + existsOperator, + isNotOperator, + isOneOfOperator, + isOperator, + DETECTION_ENGINE_EXCEPTION_OPERATORS, + isNotOneOfOperator, + isInListOperator, + isNotInListOperator, + matchesOperator, + doesNotMatchOperator, +} from '../autocomplete_operators'; + +import { + BuilderEntry, + CreateExceptionListItemBuilderSchema, + DataViewField, + EmptyEntry, + EmptyNestedEntry, + ExceptionsBuilderExceptionItem, + ExceptionsBuilderReturnExceptionItem, + FormattedBuilderEntry, + OperatorOption, + SavedObjectType, +} from '../types'; + +export const isEntryNested = (item: BuilderEntry): item is EntryNested => { + return (item as EntryNested).entries != null; +}; + +export const filterExceptionItems = ( + exceptions: ExceptionsBuilderExceptionItem[] +): ExceptionsBuilderReturnExceptionItem[] => { + return exceptions.reduce((acc, exception) => { + const entries = exception.entries.reduce((nestedAcc, singleEntry) => { + const strippedSingleEntry = removeIdFromItem(singleEntry); + if (entriesNested.is(strippedSingleEntry)) { + const nestedEntriesArray = strippedSingleEntry.entries.filter((singleNestedEntry) => { + const noIdSingleNestedEntry = removeIdFromItem(singleNestedEntry); + const [validatedNestedEntry] = validate(noIdSingleNestedEntry, nestedEntryItem); + return validatedNestedEntry != null; + }); + const noIdNestedEntries = nestedEntriesArray.map((singleNestedEntry) => + removeIdFromItem(singleNestedEntry) + ); + + const [validatedNestedEntry] = validate( + { ...strippedSingleEntry, entries: noIdNestedEntries }, + entriesNested + ); + + if (validatedNestedEntry != null) { + return [...nestedAcc, { ...singleEntry, entries: nestedEntriesArray }]; + } + return nestedAcc; + } else { + const [validatedEntry] = validate(strippedSingleEntry, entry); + if (validatedEntry != null) { + return [...nestedAcc, singleEntry]; + } + return nestedAcc; + } + }, []); + + if (entries.length === 0) { + return acc; + } + + const item = { ...exception, entries }; + + if (exceptionListItemSchema.is(item)) { + return [...acc, item]; + } else if ( + createExceptionListItemSchema.is(item) || + createRuleExceptionListItemSchema.is(item) + ) { + const { meta, ...rest } = item; + const itemSansMetaId: CreateExceptionListItemSchema | CreateRuleExceptionListItemSchema = { + ...rest, + meta: undefined, + }; + return [...acc, itemSansMetaId]; + } else { + return acc; + } + }, []); +}; + +export const addIdToEntries = (entries: EntriesArray): EntriesArray => { + return entries.map((singleEntry) => { + if (singleEntry.type === 'nested') { + return addIdToItem({ + ...singleEntry, + entries: singleEntry.entries.map((nestedEntry) => addIdToItem(nestedEntry)), + }); + } else { + return addIdToItem(singleEntry); + } + }); +}; + +export const getNewExceptionItem = ({ + listId, + namespaceType, + name, +}: { + listId: string | undefined; + namespaceType: NamespaceType | undefined; + name: string; +}): CreateExceptionListItemBuilderSchema => { + return { + comments: [], + description: `Exception list item`, + entries: addIdToEntries([ + { + field: '', + operator: 'included', + type: 'match', + value: '', + }, + ]), + item_id: undefined, + list_id: listId, + meta: { + temporaryUuid: uuidv4(), + }, + name, + namespace_type: namespaceType, + tags: [], + type: 'simple', + }; +}; + +/** + * Returns the operator type, may not need this if using io-ts types + * + * @param item a single ExceptionItem entry + */ +export const getOperatorType = (item: BuilderEntry): OperatorTypeEnum => { + switch (item.type) { + case 'match': + return OperatorTypeEnum.MATCH; + case 'match_any': + return OperatorTypeEnum.MATCH_ANY; + case 'wildcard': + return OperatorTypeEnum.WILDCARD; + case 'list': + return OperatorTypeEnum.LIST; + default: + return OperatorTypeEnum.EXISTS; + } +}; + +/** + * Determines operator selection (is/is not/is one of, etc.) + * Default operator is "is" + * + * @param item a single ExceptionItem entry + */ +export const getExceptionOperatorSelect = (item: BuilderEntry): OperatorOption => { + if (item.type === 'nested') { + return isOperator; + } else { + const operatorType = getOperatorType(item); + const foundOperator = ALL_OPERATORS.find((operatorOption) => { + return item.operator === operatorOption.operator && operatorType === operatorOption.type; + }); + + return foundOperator != null ? foundOperator : isOperator; + } +}; + +/** + * Returns the fields corresponding value for an entry + * + * @param item a single ExceptionItem entry + */ +export const getEntryValue = (item: BuilderEntry): string | string[] | undefined => { + switch (item.type) { + case OperatorTypeEnum.MATCH: + case OperatorTypeEnum.MATCH_ANY: + case OperatorTypeEnum.WILDCARD: + return item.value; + case OperatorTypeEnum.EXISTS: + return undefined; + case OperatorTypeEnum.LIST: + return item.list.id; + default: + return undefined; + } +}; + +/** + * Determines whether an entire entry, exception item, or entry within a nested + * entry needs to be removed + * + * @param exceptionItem + * @param entryIndex index of given entry, for nested entries, this will correspond + * to their parent index + * @param nestedEntryIndex index of nested entry + * + */ +export const getUpdatedEntriesOnDelete = ( + exceptionItem: ExceptionsBuilderExceptionItem, + entryIndex: number, + nestedParentIndex: number | null +): ExceptionsBuilderExceptionItem => { + const itemOfInterest: BuilderEntry = + exceptionItem.entries[nestedParentIndex != null ? nestedParentIndex : entryIndex]; + + if (nestedParentIndex != null && itemOfInterest.type === OperatorTypeEnum.NESTED) { + const updatedEntryEntries = [ + ...itemOfInterest.entries.slice(0, entryIndex), + ...itemOfInterest.entries.slice(entryIndex + 1), + ]; + + if (updatedEntryEntries.length === 0) { + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, nestedParentIndex), + ...exceptionItem.entries.slice(nestedParentIndex + 1), + ], + }; + } else { + const { field } = itemOfInterest; + const updatedItemOfInterest: EntryNested | EmptyNestedEntry = { + entries: updatedEntryEntries, + field, + id: itemOfInterest.id != null ? itemOfInterest.id : `${entryIndex}`, + type: OperatorTypeEnum.NESTED, + }; + + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, nestedParentIndex), + updatedItemOfInterest, + ...exceptionItem.entries.slice(nestedParentIndex + 1), + ], + }; + } + } else { + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, entryIndex), + ...exceptionItem.entries.slice(entryIndex + 1), + ], + }; + } +}; + +/** + * Returns filtered index patterns based on the field - if a user selects to + * add nested entry, should only show nested fields, if item is the parent + * field of a nested entry, we only display the parent field + * + * @param patterns DataViewBase containing available fields on rule index + * @param item exception item entry + * set to add a nested field + */ +export const getFilteredIndexPatterns = ( + patterns: DataViewBase, + item: FormattedBuilderEntry +): DataViewBase => { + if (item.nested === 'child' && item.parent != null) { + // when user has selected a nested entry, only fields with the common parent are shown + return { + ...patterns, + fields: patterns.fields + .filter((indexField) => { + const subTypeNested = getDataViewFieldSubtypeNested(indexField); + const fieldHasCommonParentPath = + subTypeNested && + item.parent != null && + subTypeNested.nested.path === item.parent.parent.field; + + return fieldHasCommonParentPath; + }) + .map((f) => { + const [fieldNameWithoutParentPath] = f.name.split('.').slice(-1); + return { ...f, name: fieldNameWithoutParentPath }; + }), + }; + } else if (item.nested === 'parent' && item.field != null) { + // when user has selected a nested entry, right above it we show the common parent + return { ...patterns, fields: [item.field] }; + } else if (item.nested === 'parent' && item.field == null) { + // when user selects to add a nested entry, only nested fields are shown as options + return { + ...patterns, + fields: patterns.fields.filter((field) => isDataViewFieldSubtypeNested(field)), + }; + } else { + return patterns; + } +}; + +/** + * Determines proper entry update when user selects new field + * + * @param item - current exception item entry values + * @param newField - newly selected field + * + */ +export const getEntryOnFieldChange = ( + item: FormattedBuilderEntry, + newField: DataViewFieldBase +): { index: number; updatedEntry: BuilderEntry } => { + const { parent, entryIndex, nested } = item; + const newChildFieldValue = newField != null ? newField.name.split('.').slice(-1)[0] : ''; + + if (nested === 'parent') { + // For nested entries, when user first selects to add a nested + // entry, they first see a row similar to what is shown for when + // a user selects "exists", as soon as they make a selection + // we can now identify the 'parent' and 'child' this is where + // we first convert the entry into type "nested" + const subTypeNested = getDataViewFieldSubtypeNested(newField); + const newParentFieldValue = subTypeNested?.nested.path || ''; + + return { + index: entryIndex, + updatedEntry: { + entries: [ + addIdToItem({ + field: newChildFieldValue != null ? newChildFieldValue : '', + operator: isOperator.operator, + type: OperatorTypeEnum.MATCH, + value: '', + }), + ], + field: newParentFieldValue, + id: item.id, + type: OperatorTypeEnum.NESTED, + }, + }; + } else if (nested === 'child' && parent != null) { + return { + index: parent.parentIndex, + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: newChildFieldValue != null ? newChildFieldValue : '', + id: item.id, + operator: isOperator.operator, + type: OperatorTypeEnum.MATCH, + value: '', + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + }; + } else { + return { + index: entryIndex, + updatedEntry: { + field: newField != null ? newField.name : '', + id: item.id, + operator: isOperator.operator, + type: OperatorTypeEnum.MATCH, + value: '', + }, + }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "list" + * + * @param item - current exception item entry values + * @param newField - newly selected list + * + */ +export const getEntryOnListChange = ( + item: FormattedBuilderEntry, + newField: ListSchema +): { index: number; updatedEntry: BuilderEntry } => { + const { entryIndex, field, operator } = item; + const { id, type } = newField; + + return { + index: entryIndex, + updatedEntry: { + field: field != null ? field.name : '', + id: item.id, + list: { id, type }, + operator: operator.operator, + type: OperatorTypeEnum.LIST, + }, + }; +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "match_any" + * + * @param item - current exception item entry values + * @param newField - newly entered value + * + */ +export const getEntryOnMatchAnyChange = ( + item: FormattedBuilderEntry, + newField: string[] +): { index: number; updatedEntry: BuilderEntry } => { + const { nested, parent, entryIndex, field, operator } = item; + + if (nested != null && parent != null) { + const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; + + return { + index: parent.parentIndex, + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: fieldName, + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.MATCH_ANY, + value: newField, + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + }; + } else { + return { + index: entryIndex, + updatedEntry: { + field: field != null ? field.name : '', + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.MATCH_ANY, + value: newField, + }, + }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "match" + * + * @param item - current exception item entry values + * @param newField - newly entered value + * + */ +export const getEntryOnMatchChange = ( + item: FormattedBuilderEntry, + newField: string +): { index: number; updatedEntry: BuilderEntry } => { + const { nested, parent, entryIndex, field, operator } = item; + + if (nested != null && parent != null) { + const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; + + return { + index: parent.parentIndex, + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: fieldName, + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.MATCH, + value: newField, + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + }; + } else { + return { + index: entryIndex, + updatedEntry: { + field: field != null ? field.name : '', + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.MATCH, + value: newField, + }, + }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "wildcard" + * + * @param item - current exception item entry values + * @param newField - newly entered value + * + */ +export const getEntryOnWildcardChange = ( + item: FormattedBuilderEntry, + newField: string +): { index: number; updatedEntry: BuilderEntry } => { + const { nested, parent, entryIndex, field, operator } = item; + + if (nested != null && parent != null) { + const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; + + return { + index: parent.parentIndex, + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: fieldName, + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.WILDCARD, + value: newField, + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + }; + } else { + return { + index: entryIndex, + updatedEntry: { + field: field != null ? field.name : '', + id: item.id, + operator: operator.operator, + type: OperatorTypeEnum.WILDCARD, + value: newField, + }, + }; + } +}; + +/** + * On operator change, determines whether value needs to be cleared or not + * + * @param field + * @param selectedOperator + * @param currentEntry + * + */ +export const getEntryFromOperator = ( + selectedOperator: OperatorOption, + currentEntry: FormattedBuilderEntry +): Entry & { id?: string } => { + const isSameOperatorType = currentEntry.operator.type === selectedOperator.type; + const fieldValue = currentEntry.field != null ? currentEntry.field.name : ''; + switch (selectedOperator.type) { + case 'match': + return { + field: fieldValue, + id: currentEntry.id, + operator: selectedOperator.operator, + type: OperatorTypeEnum.MATCH, + value: + isSameOperatorType && typeof currentEntry.value === 'string' ? currentEntry.value : '', + }; + case 'match_any': + return { + field: fieldValue, + id: currentEntry.id, + operator: selectedOperator.operator, + type: OperatorTypeEnum.MATCH_ANY, + value: isSameOperatorType && Array.isArray(currentEntry.value) ? currentEntry.value : [], + }; + case 'list': + return { + field: fieldValue, + id: currentEntry.id, + list: { id: '', type: 'ip' }, + operator: selectedOperator.operator, + type: OperatorTypeEnum.LIST, + }; + case 'wildcard': + return { + field: fieldValue, + id: currentEntry.id, + operator: selectedOperator.operator, + type: OperatorTypeEnum.WILDCARD, + value: + isSameOperatorType && typeof currentEntry.value === 'string' ? currentEntry.value : '', + }; + default: + return { + field: fieldValue, + id: currentEntry.id, + operator: selectedOperator.operator, + type: OperatorTypeEnum.EXISTS, + }; + } +}; + +/** + * Determines proper entry update when user selects new operator + * + * @param item - current exception item entry values + * @param newOperator - newly selected operator + * + */ +export const getEntryOnOperatorChange = ( + item: FormattedBuilderEntry, + newOperator: OperatorOption +): { updatedEntry: BuilderEntry; index: number } => { + const { parent, entryIndex, field, nested } = item; + const newEntry = getEntryFromOperator(newOperator, item); + + if (!entriesList.is(newEntry) && nested != null && parent != null) { + return { + index: parent.parentIndex, + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + ...newEntry, + field: field != null ? field.name.split('.').slice(-1)[0] : '', + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + }; + } else { + return { index: entryIndex, updatedEntry: newEntry }; + } +}; + +export const isKibanaStringType = (type: string) => { + const kbnFieldType = castEsToKbnFieldTypeName(type); + return kbnFieldType === KBN_FIELD_TYPES.STRING; +}; + +export const fieldSupportsMatches = (field: DataViewFieldBase) => { + return field.esTypes?.some(isKibanaStringType); +}; + +/** + * Determines which operators to make available + * + * @param item + * @param listType + * @param isBoolean + * @param includeValueListOperators whether or not to include the 'is in list' and 'is not in list' operators + */ +export const getOperatorOptions = ( + item: FormattedBuilderEntry, + listType: ExceptionListType, + isBoolean: boolean, + includeValueListOperators = true +): OperatorOption[] => { + if (item.nested === 'parent' || item.field == null) { + return [isOperator]; + } else if (listType === 'endpoint') { + if (isBoolean) { + return [isOperator]; + } else { + return fieldSupportsMatches(item.field) + ? [isOperator, isOneOfOperator, matchesOperator, doesNotMatchOperator] + : [isOperator, isOneOfOperator]; + } + } else if (item.nested != null && listType === 'detection') { + return isBoolean ? [isOperator, existsOperator] : [isOperator, isOneOfOperator, existsOperator]; + } else if (isBoolean) { + return [isOperator, isNotOperator, existsOperator, doesNotExistOperator]; + } else if (!includeValueListOperators) { + return fieldSupportsMatches(item.field) + ? EXCEPTION_OPERATORS_SANS_LISTS + : [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + ]; + } else { + return listType === 'detection' + ? fieldSupportsMatches(item.field) + ? DETECTION_ENGINE_EXCEPTION_OPERATORS + : [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + isInListOperator, + isNotInListOperator, + ] + : ALL_OPERATORS; + } +}; + +/** + * Fields of type 'text' do not generate autocomplete values, we want + * to find it's corresponding keyword type (if available) which does + * generate autocomplete values + * + * @param fields DataViewFieldBase fields + * @param selectedField the field name that was selected + * @param isTextType we only want a corresponding keyword field if + * the selected field is of type 'text' + * + */ +export const getCorrespondingKeywordField = ({ + fields, + selectedField, +}: { + fields: DataViewFieldBase[]; + selectedField: string | undefined; +}): DataViewFieldBase | undefined => { + const selectedFieldBits = + selectedField != null && selectedField !== '' ? selectedField.split('.') : []; + const selectedFieldIsTextType = selectedFieldBits.slice(-1)[0] === 'text'; + + if (selectedFieldIsTextType && selectedFieldBits.length > 0) { + const keywordField = selectedFieldBits.slice(0, selectedFieldBits.length - 1).join('.'); + const [foundKeywordField] = fields.filter( + ({ name }) => keywordField !== '' && keywordField === name + ); + return foundKeywordField; + } + + return undefined; +}; + +/** + * Formats the entry into one that is easily usable for the UI, most of the + * complexity was introduced with nested fields + * + * @param patterns DataViewBase containing available fields on rule index + * @param item exception item entry + * @param itemIndex entry index + * @param parent nested entries hold copy of their parent for use in various logic + * @param parentIndex corresponds to the entry index, this might seem obvious, but + * was added to ensure that nested items could be identified with their parent entry + * @param allowCustomFieldOptions determines if field must be found to match in indexPattern or not + */ +export const getFormattedBuilderEntry = ( + indexPattern: DataViewBase, + item: BuilderEntry, + itemIndex: number, + parent: EntryNested | undefined, + parentIndex: number | undefined, + allowCustomFieldOptions: boolean +): FormattedBuilderEntry => { + const { fields } = indexPattern; + const field = parent != null ? `${parent.field}.${item.field}` : item.field; + const [foundField] = fields.filter(({ name }) => field != null && field === name); + const correspondingKeywordField = getCorrespondingKeywordField({ + fields, + selectedField: field, + }); + + if (parent != null && parentIndex != null) { + return { + correspondingKeywordField, + entryIndex: itemIndex, + field: + foundField != null + ? { ...foundField, name: foundField.name.split('.').slice(-1)[0] } + : foundField, + id: item.id != null ? item.id : `${itemIndex}`, + nested: 'child', + operator: getExceptionOperatorSelect(item), + parent: { parent, parentIndex }, + value: getEntryValue(item), + }; + } else { + const fieldToUse = allowCustomFieldOptions + ? foundField ?? { name: item.field, type: 'keyword' } + : foundField; + + return { + correspondingKeywordField, + entryIndex: itemIndex, + field: fieldToUse, + id: item.id != null ? item.id : `${itemIndex}`, + nested: undefined, + operator: getExceptionOperatorSelect(item), + parent: undefined, + value: getEntryValue(item), + }; + } +}; + +/** + * Formats the entries to be easily usable for the UI, most of the + * complexity was introduced with nested fields + * + * @param patterns DataViewBase containing available fields on rule index + * @param entries exception item entries + * @param allowCustomFieldOptions determines if field must be found to match in indexPattern or not + * @param parent nested entries hold copy of their parent for use in various logic + * @param parentIndex corresponds to the entry index, this might seem obvious, but + * was added to ensure that nested items could be identified with their parent entry + */ +export const getFormattedBuilderEntries = ( + indexPattern: DataViewBase, + entries: BuilderEntry[], + allowCustomFieldOptions: boolean, + parent?: EntryNested, + parentIndex?: number +): FormattedBuilderEntry[] => { + return entries.reduce((acc, item, index) => { + const isNewNestedEntry = item.type === 'nested' && item.entries.length === 0; + if (item.type !== 'nested' && !isNewNestedEntry) { + const newItemEntry: FormattedBuilderEntry = getFormattedBuilderEntry( + indexPattern, + item, + index, + parent, + parentIndex, + allowCustomFieldOptions + ); + return [...acc, newItemEntry]; + } else { + const parentEntry: FormattedBuilderEntry = { + correspondingKeywordField: undefined, + entryIndex: index, + field: isNewNestedEntry + ? undefined + : // This type below is really a FieldSpec type from "src/plugins/data/common/index_patterns/fields/types.ts", we cast it here to keep using the DataViewFieldBase interface + ({ + aggregatable: false, + esTypes: ['nested'], + name: item.field != null ? item.field : '', + searchable: false, + type: 'string', + } as DataViewFieldBase), + id: item.id != null ? item.id : `${index}`, + nested: 'parent', + operator: isOperator, + parent: undefined, + value: undefined, + }; + + // User has selected to add a nested field, but not yet selected the field + if (isNewNestedEntry) { + return [...acc, parentEntry]; + } + + if (isEntryNested(item)) { + const nestedItems = getFormattedBuilderEntries( + indexPattern, + item.entries, + allowCustomFieldOptions, + item, + index + ); + + return [...acc, parentEntry, ...nestedItems]; + } + + return [...acc]; + } + }, []); +}; + +export const getDefaultEmptyEntry = (): EmptyEntry => ({ + field: '', + id: uuidv4(), + operator: OperatorEnum.INCLUDED, + type: OperatorTypeEnum.MATCH, + value: '', +}); + +export const getDefaultNestedEmptyEntry = (): EmptyNestedEntry => ({ + entries: [], + field: '', + id: uuidv4(), + type: OperatorTypeEnum.NESTED, +}); + +export const containsValueListEntry = (items: ExceptionsBuilderExceptionItem[]): boolean => + items.some((item) => item.entries.some(({ type }) => type === OperatorTypeEnum.LIST)); + +export const buildShowActiveExceptionsFilter = (savedObjectPrefix: SavedObjectType[]): string => { + const now = new Date().toISOString(); + const filters = savedObjectPrefix.map( + (prefix) => + `${prefix}.attributes.expire_time > "${now}" OR NOT ${prefix}.attributes.expire_time: *` + ); + return filters.join(','); +}; + +export const buildShowExpiredExceptionsFilter = (savedObjectPrefix: SavedObjectType[]): string => { + const now = new Date().toISOString(); + const filters = savedObjectPrefix.map((prefix) => `${prefix}.attributes.expire_time <= "${now}"`); + return filters.join(','); +}; + +const getIndexGroupName = (indexName: string): string => { + // Check whether it is a Data Stream index + const dataStreamExp = /.ds-(.*?)-[0-9]{4}\.[0-9]{2}\.[0-9]{2}-[0-9]{6}/; + let result = indexName.match(dataStreamExp); + if (result && result.length === 2) { + return result[1]; + } + + // Check whether it is an old '.siem' index group + const siemSignalsExp = /.siem-(.*?)-[0-9]{6}/; + result = indexName.match(siemSignalsExp); + if (result && result.length === 2) { + return `.siem-${result[1]}`; + } + + // Otherwise return index name + return indexName; +}; + +export interface FieldConflictsInfo { + /** + * Kibana field type + */ + type: string; + /** + * Total count of the indices of this type + */ + totalIndexCount: number; + /** + * Grouped indices info + */ + groupedIndices: Array<{ + /** + * Index group name (like '.ds-...' or '.siem-signals-...') + */ + name: string; + /** + * Count of indices in the group + */ + count: number; + }>; +} + +export const getMappingConflictsInfo = (field: DataViewField): FieldConflictsInfo[] | null => { + if (!field.conflictDescriptions) { + return null; + } + const conflicts: FieldConflictsInfo[] = []; + for (const [key, value] of Object.entries(field.conflictDescriptions)) { + const groupedIndices: Array<{ + name: string; + count: number; + }> = []; + + // Group indices and calculate count of indices in each group + const groupedInfo: { [key: string]: number } = {}; + value.forEach((index) => { + const groupName = getIndexGroupName(index); + if (!groupedInfo[groupName]) { + groupedInfo[groupName] = 0; + } + groupedInfo[groupName]++; + }); + for (const [name, count] of Object.entries(groupedInfo)) { + groupedIndices.push({ + name, + count, + }); + } + + // Sort groups by the indices count + groupedIndices.sort((group1, group2) => { + return group2.count - group1.count; + }); + + conflicts.push({ + type: key, + totalIndexCount: value.length, + groupedIndices, + }); + } + return conflicts; +}; + +/** + * Given an exceptions list, determine if any entries have an "IS" operator with a wildcard value + */ +export const hasWrongOperatorWithWildcard = ( + items: ExceptionsBuilderReturnExceptionItem[] +): boolean => { + // flattens array of multiple entries added with OR + const multipleEntries = items.flatMap((item) => item.entries); + // flattens nested entries + const allEntries = multipleEntries.flatMap((item) => { + if (item.type === 'nested') { + return item.entries; + } + return item; + }); + + // eslint-disable-next-line array-callback-return + return allEntries.some((e) => { + if (e.type !== 'list' && 'value' in e) { + return validateHasWildcardWithWrongOperator({ + operator: e.type, + value: e.value, + }); + } + }); +}; + +/** + * Event filters helper where given an exceptions list, + * determine if both 'subject_name' and 'trusted' are + * included in an entry with 'code_signature' + */ +export const hasPartialCodeSignatureEntry = ( + items: ExceptionsBuilderReturnExceptionItem[] +): boolean => { + const { os_types: os = ['windows'], entries = [] } = items[0] || {}; + let name = false; + let trusted = false; + + for (const e of entries) { + if (e.type === 'nested' && e.field === 'process.Ext.code_signature') { + const includesNestedName = e.entries.some( + (nestedEntry) => nestedEntry.field === 'subject_name' + ); + const includesNestedTrusted = e.entries.some( + (nestedEntry) => nestedEntry.field === 'trusted' + ); + if (includesNestedName !== includesNestedTrusted) { + return true; + } + } else if ( + e.field === 'process.code_signature.subject_name' || + (os.includes('macos') && e.field === 'process.code_signature.team_id') + ) { + name = true; + } else if (e.field === 'process.code_signature.trusted') { + trusted = true; + } + } + return name !== trusted; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/types/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/types/index.ts new file mode 100644 index 000000000000..1730a0e9a829 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/src/types/index.ts @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { DataViewFieldBase } from '@kbn/es-query'; +import type { + CreateExceptionListItemSchema, + CreateRuleExceptionListItemSchema, + Entry, + EntryExists, + EntryMatch, + EntryMatchAny, + EntryMatchWildcard, + EntryNested, + ExceptionListItemSchema, + ListOperatorEnum as OperatorEnum, + ListOperatorTypeEnum as OperatorTypeEnum, + NamespaceType, +} from '@kbn/securitysolution-io-ts-list-types'; +import { + EXCEPTION_LIST_NAMESPACE, + EXCEPTION_LIST_NAMESPACE_AGNOSTIC, +} from '@kbn/securitysolution-list-constants'; + +export interface DataViewField extends DataViewFieldBase { + conflictDescriptions?: Record; +} + +export interface OperatorOption { + message: string; + value: string; + operator: OperatorEnum; + type: OperatorTypeEnum; +} + +export interface FormattedBuilderEntry { + id: string; + field: DataViewField | undefined; + operator: OperatorOption; + value: string | string[] | undefined; + nested: 'parent' | 'child' | undefined; + entryIndex: number; + parent: { parent: BuilderEntryNested; parentIndex: number } | undefined; + correspondingKeywordField: DataViewFieldBase | undefined; +} + +export interface EmptyEntry { + id: string; + field: string | undefined; + operator: OperatorEnum; + type: OperatorTypeEnum.MATCH | OperatorTypeEnum.MATCH_ANY | OperatorTypeEnum.WILDCARD; + value: string | string[] | undefined; +} + +export interface EmptyListEntry { + id: string; + field: string | undefined; + operator: OperatorEnum; + type: OperatorTypeEnum.LIST; + list: { id: string | undefined; type: string | undefined }; +} + +export interface EmptyNestedEntry { + id: string; + field: string | undefined; + type: OperatorTypeEnum.NESTED; + entries: Array< + | (EntryMatch & { id?: string }) + | (EntryMatchAny & { id?: string }) + | (EntryMatchWildcard & { id?: string }) + | (EntryExists & { id?: string }) + >; +} + +export type BuilderEntry = + | (Entry & { id?: string }) + | EmptyListEntry + | EmptyEntry + | BuilderEntryNested + | EmptyNestedEntry; + +export type BuilderEntryNested = Omit & { + id?: string; + entries: Array< + | (EntryMatch & { id?: string }) + | (EntryMatchAny & { id?: string }) + | (EntryMatchWildcard & { id?: string }) + | (EntryExists & { id?: string }) + >; +}; + +export type ExceptionListItemBuilderSchema = Omit & { + entries: BuilderEntry[]; +}; + +export type CreateExceptionListItemBuilderSchema = Omit< + CreateExceptionListItemSchema, + 'meta' | 'entries' | 'list_id' | 'namespace_type' +> & { + meta: { temporaryUuid: string }; + entries: BuilderEntry[]; + list_id: string | undefined; + namespace_type: NamespaceType | undefined; +}; + +export type ExceptionsBuilderExceptionItem = + | ExceptionListItemBuilderSchema + | CreateExceptionListItemBuilderSchema; + +export type ExceptionsBuilderReturnExceptionItem = + | ExceptionListItemSchema + | CreateExceptionListItemSchema + | CreateRuleExceptionListItemSchema; + +export const exceptionListSavedObjectType = EXCEPTION_LIST_NAMESPACE; +export const exceptionListAgnosticSavedObjectType = EXCEPTION_LIST_NAMESPACE_AGNOSTIC; +export type SavedObjectType = + | typeof EXCEPTION_LIST_NAMESPACE + | typeof EXCEPTION_LIST_NAMESPACE_AGNOSTIC; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/tsconfig.json new file mode 100644 index 000000000000..0b6eb353950d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-list-utils/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/es-query", + "@kbn/i18n", + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-io-ts-utils", + "@kbn/securitysolution-list-constants", + "@kbn/securitysolution-utils", + "@kbn/field-types" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-lists-common/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/README.md similarity index 100% rename from packages/kbn-securitysolution-lists-common/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts new file mode 100644 index 000000000000..cf603f3ac3bd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.gen.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Create list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { + ListId, + ListName, + ListDescription, + ListType, + ListMetadata, +} from '../model/list_common.gen'; +import { List } from '../model/list_schemas.gen'; + +export type CreateListRequestBody = z.infer; +export const CreateListRequestBody = z.object({ + id: ListId.optional(), + name: ListName, + description: ListDescription, + type: ListType, + serializer: z.string().optional(), + deserializer: z.string().optional(), + meta: ListMetadata.optional(), + version: z.number().int().min(1).optional().default(1), +}); +export type CreateListRequestBodyInput = z.input; + +export type CreateListResponse = z.infer; +export const CreateListResponse = List; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml new file mode 100644 index 000000000000..3c1d090687fe --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list/create_list.schema.yaml @@ -0,0 +1,81 @@ +openapi: 3.0.0 +info: + title: Create list API endpoint + version: '2023-10-31' +paths: + /api/lists: + post: + x-labels: [serverless, ess] + operationId: CreateList + x-codegen-enabled: true + summary: Create a list + description: Create a new list. + requestBody: + description: List's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + name: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' + description: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' + type: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListType' + serializer: + type: string + deserializer: + type: string + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' + version: + type: integer + minimum: 1 + default: 1 + required: + - name + - description + - type + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 409: + description: List already exists response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.ts new file mode 100644 index 000000000000..7eb20ada7f32 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.gen.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Create list DS API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +export type CreateListIndexResponse = z.infer; +export const CreateListIndexResponse = z.object({ + acknowledged: z.boolean(), +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml new file mode 100644 index 000000000000..8f7981114437 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_index/create_list_index.schema.yaml @@ -0,0 +1,55 @@ +openapi: 3.0.0 +info: + title: Create list DS API endpoint + version: '2023-10-31' +paths: + /api/lists/index: + post: + x-labels: [serverless, ess] + operationId: CreateListIndex + x-codegen-enabled: true + summary: Create list data streams + description: Create `.lists` and `.items` data streams in the relevant space. + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + acknowledged: + type: boolean + required: [acknowledged] + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 409: + description: List data stream exists response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.ts new file mode 100644 index 000000000000..ce4744f3c441 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.gen.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Create list item API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListItemId, ListId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; +import { ListItem } from '../model/list_schemas.gen'; + +export type CreateListItemRequestBody = z.infer; +export const CreateListItemRequestBody = z.object({ + id: ListItemId.optional(), + list_id: ListId, + value: ListItemValue, + meta: ListItemMetadata.optional(), + /** + * Determines when changes made by the request are made visible to search + */ + refresh: z.enum(['true', 'false', 'wait_for']).optional(), +}); +export type CreateListItemRequestBodyInput = z.input; + +export type CreateListItemResponse = z.infer; +export const CreateListItemResponse = ListItem; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml new file mode 100644 index 000000000000..bdf266c8926f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/create_list_item/create_list_item.schema.yaml @@ -0,0 +1,82 @@ +openapi: 3.0.0 +info: + title: Create list item API endpoint + version: '2023-10-31' +paths: + /api/lists/items: + post: + x-labels: [serverless, ess] + operationId: CreateListItem + x-codegen-enabled: true + summary: Create a list item + description: | + Create a list item and associate it with the specified list. + + All list items in the same list must be the same type. For example, each list item in an `ip` list must define a specific IP address. + > info + > Before creating a list item, you must create a list. + requestBody: + description: List item's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' + list_id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + value: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' + refresh: + type: string + enum: + - 'true' + - 'false' + - wait_for + description: Determines when changes made by the request are made visible to search + required: + - list_id + - value + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 409: + description: List item already exists response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts new file mode 100644 index 000000000000..3dd638be564e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.gen.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Delete list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; +import { BooleanFromString } from '@kbn/zod-helpers'; + +import { ListId } from '../model/list_common.gen'; +import { List } from '../model/list_schemas.gen'; + +export type DeleteListRequestQuery = z.infer; +export const DeleteListRequestQuery = z.object({ + /** + * List's `id` value + */ + id: ListId, + deleteReferences: BooleanFromString.optional().default(false), + ignoreReferences: BooleanFromString.optional().default(false), +}); +export type DeleteListRequestQueryInput = z.input; + +export type DeleteListResponse = z.infer; +export const DeleteListResponse = List; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml new file mode 100644 index 000000000000..d8440aa347cd --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list/delete_list.schema.yaml @@ -0,0 +1,73 @@ +openapi: 3.0.0 +info: + title: Delete list API endpoint + version: '2023-10-31' +paths: + /api/lists: + delete: + x-labels: [serverless, ess] + operationId: DeleteList + x-codegen-enabled: true + summary: Delete a list + description: | + Delete a list using the list ID. + > info + > When you delete a list, all of its list items are also deleted. + parameters: + - name: id + in: query + required: true + description: List's `id` value + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: deleteReferences + in: query + required: false + schema: + type: boolean + default: false + - name: ignoreReferences + in: query + required: false + schema: + type: boolean + default: false + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.ts new file mode 100644 index 000000000000..4ffd90f6fb8b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.gen.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Delete list DS API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +export type DeleteListIndexResponse = z.infer; +export const DeleteListIndexResponse = z.object({ + acknowledged: z.boolean(), +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml new file mode 100644 index 000000000000..8773925e358b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_index/delete_list_index.schema.yaml @@ -0,0 +1,55 @@ +openapi: 3.0.0 +info: + title: Delete list DS API endpoint + version: '2023-10-31' +paths: + /api/lists/index: + delete: + x-labels: [serverless, ess] + operationId: DeleteListIndex + x-codegen-enabled: true + summary: Delete list data streams + description: Delete the `.lists` and `.items` data streams. + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + acknowledged: + type: boolean + required: [acknowledged] + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List data stream not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts similarity index 76% rename from packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts index 178641cd8d6a..fe9f7bee0e68 100644 --- a/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml new file mode 100644 index 000000000000..752a246bdd9b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/delete_list_item/delete_list_item.schema.yaml @@ -0,0 +1,82 @@ +openapi: 3.0.0 +info: + title: Delete list item API endpoint + version: '2023-10-31' +paths: + /api/lists/items: + delete: + x-labels: [serverless, ess] + operationId: DeleteListItem + x-codegen-enabled: true + summary: Delete a list item + description: Delete a list item using its `id`, or its `list_id` and `value` fields. + parameters: + - name: id + in: query + required: false + description: Required if `list_id` and `value` are not specified + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: list_id + in: query + required: false + description: Required if `id` is not specified + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: value + in: query + required: false + description: Required if `id` is not specified + schema: + type: string + - name: refresh + in: query + required: false + description: Determines when changes made by the request are made visible to search + schema: + type: string + enum: ['true', 'false', 'wait_for'] + default: 'false' + responses: + 200: + description: Successful response + content: + application/json: + schema: + oneOf: + - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + - type: array + items: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.ts new file mode 100644 index 000000000000..87e05bd24e48 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.gen.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Export list items API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListId } from '../model/list_common.gen'; + +export type ExportListItemsRequestQuery = z.infer; +export const ExportListItemsRequestQuery = z.object({ + /** + * List's id to export + */ + list_id: ListId, +}); +export type ExportListItemsRequestQueryInput = z.input; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml new file mode 100644 index 000000000000..2dd518904d0f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/export_list_items/export_list_items.schema.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.0 +info: + title: Export list items API endpoint + version: '2023-10-31' +paths: + /api/lists/items/_export: + post: + x-labels: [serverless, ess] + operationId: ExportListItems + x-codegen-enabled: true + summary: Export list items + description: Export list item values from the specified list. + parameters: + - name: list_id + in: query + required: true + description: List's id to export + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + responses: + 200: + description: Successful response + content: + application/ndjson: + schema: + type: string + format: binary + description: A `.txt` file containing list items from the specified list + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts similarity index 85% rename from packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts index f693965e91e2..e40c6fe9e2fc 100644 --- a/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml similarity index 75% rename from packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml index 21cf4ffd6184..5cb15220e17c 100644 --- a/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_list_items/find_list_items.schema.yaml @@ -34,7 +34,7 @@ paths: required: false description: Determines which field is used to sort the results schema: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' - name: sort_order in: query required: false @@ -94,31 +94,31 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: FindListItemsCursor: - $ref: '../../../kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' FindListItemsFilter: type: string diff --git a/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts similarity index 84% rename from packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts index ec104f2e6c2b..74f8ba0217d6 100644 --- a/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml new file mode 100644 index 000000000000..44713827d29f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/find_lists/find_lists.schema.yaml @@ -0,0 +1,118 @@ +openapi: 3.0.0 +info: + title: Find lists API endpoint + version: '2023-10-31' +paths: + /api/lists/_find: + get: + x-labels: [serverless, ess] + operationId: FindLists + x-codegen-enabled: true + summary: Get lists + description: Get a paginated subset of lists. By default, the first page is returned, with 20 results per page. + parameters: + - name: page + in: query + required: false + description: The page number to return + schema: + type: integer + - name: per_page + in: query + required: false + description: The number of lists to return per page + schema: + type: integer + - name: sort_field + in: query + required: false + description: Determines which field is used to sort the results + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + - name: sort_order + in: query + required: false + description: Determines the sort order, which can be `desc` or `asc` + schema: + type: string + enum: [desc, asc] + - name: cursor + in: query + required: false + description: | + Returns the list that come after the last list returned in the previous call + (use the cursor value returned in the previous call). This parameter uses + the `tie_breaker_id` field to ensure all lists are sorted and returned correctly. + schema: + $ref: '#/components/schemas/FindListsCursor' + - name: filter + in: query + required: false + description: | + Filters the returned results according to the value of the specified field, + using the : syntax. + schema: + $ref: '#/components/schemas/FindListsFilter' + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + page: + type: integer + minimum: 0 + per_page: + type: integer + minimum: 0 + total: + type: integer + minimum: 0 + cursor: + $ref: '#/components/schemas/FindListsCursor' + required: + - data + - page + - per_page + - total + - cursor + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + +components: + schemas: + FindListsCursor: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + FindListsFilter: + type: string diff --git a/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts similarity index 77% rename from packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts index b71b05bd7595..baf9d9308a93 100644 --- a/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml new file mode 100644 index 000000000000..78f44f7dd7f7 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/import_list_items/import_list_items.schema.yaml @@ -0,0 +1,101 @@ +openapi: 3.0.0 +info: + title: Import list items API endpoint + version: '2023-10-31' +paths: + /api/lists/items/_import: + post: + x-labels: [serverless, ess] + operationId: ImportListItems + x-codegen-enabled: true + summary: Import list items + description: | + Import list items from a TXT or CSV file. The maximum file size is 9 million bytes. + + You can import items to a new or existing list. + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + description: A `.txt` or `.csv` file containing newline separated list items + parameters: + - name: list_id + in: query + required: false + description: | + List's id. + + Required when importing to an existing list. + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: type + in: query + required: false + description: | + Type of the importing list. + + Required when importing a new list that is `list_id` is not specified. + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListType' + - name: serializer + in: query + required: false + schema: + type: string + - name: deserializer + in: query + required: false + schema: + type: string + - name: refresh + in: query + required: false + description: Determines when changes made by the request are made visible to search + schema: + type: string + enum: ['true', 'false', 'wait_for'] + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 409: + description: List with specified list_id does not exist response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/index.ts new file mode 100644 index 000000000000..6ff15e6109c6 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/index.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './model/list_common.gen'; +export * from './model/list_schemas.gen'; +export * from './create_list_index/create_list_index.gen'; +export * from './create_list_item/create_list_item.gen'; +export * from './create_list/create_list.gen'; +export * from './delete_list_index/delete_list_index.gen'; +export * from './delete_list_item/delete_list_item.gen'; +export * from './delete_list/delete_list.gen'; +export * from './find_list_items/find_list_items.gen'; +export * from './find_lists/find_lists.gen'; +export * from './export_list_items/export_list_items.gen'; +export * from './import_list_items/import_list_items.gen'; +export * from './patch_list_item/patch_list_item.gen'; +export * from './patch_list/patch_list.gen'; +export * from './read_list_index/read_list_index.gen'; +export * from './read_list_item/read_list_item.gen'; +export * from './read_list/read_list.gen'; +export * from './update_list_item/update_list_item.gen'; +export * from './update_list/update_list.gen'; diff --git a/packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts similarity index 82% rename from packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts index 9a51bd0eeb5a..536e0b859e45 100644 --- a/packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml new file mode 100644 index 000000000000..ef29224a5b73 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_common.schema.yaml @@ -0,0 +1,59 @@ +openapi: 3.0.0 +info: + title: Common List Attributes + version: 'not applicable' +paths: {} +components: + schemas: + ListId: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListType: + type: string + enum: + - binary + - boolean + - byte + - date + - date_nanos + - date_range + - double + - double_range + - float + - float_range + - geo_point + - geo_shape + - half_float + - integer + - integer_range + - ip + - ip_range + - keyword + - long + - long_range + - shape + - short + - text + + ListName: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListDescription: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListMetadata: + type: object + additionalProperties: true + + ListItemId: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListItemValue: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListItemDescription: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/primitives.schema.yaml#/components/schemas/NonEmptyString' + + ListItemMetadata: + type: object + additionalProperties: true diff --git a/packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts similarity index 80% rename from packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts index 14d9547c35b5..cd95d20853c1 100644 --- a/packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_schemas.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-lists-common/api/model/list_schemas.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_schemas.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-lists-common/api/model/list_schemas.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/model/list_schemas.schema.yaml diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.ts new file mode 100644 index 000000000000..f2a67181d396 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.gen.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Patch list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListId, ListName, ListDescription, ListMetadata } from '../model/list_common.gen'; +import { List } from '../model/list_schemas.gen'; + +export type PatchListRequestBody = z.infer; +export const PatchListRequestBody = z.object({ + id: ListId, + name: ListName.optional(), + description: ListDescription.optional(), + meta: ListMetadata.optional(), + version: z.number().int().min(1).optional(), + _version: z.string().optional(), +}); +export type PatchListRequestBodyInput = z.input; + +export type PatchListResponse = z.infer; +export const PatchListResponse = List; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml new file mode 100644 index 000000000000..be8c5871413f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list/patch_list.schema.yaml @@ -0,0 +1,74 @@ +openapi: 3.0.0 +info: + title: Patch list API endpoint + version: '2023-10-31' +paths: + /api/lists: + patch: + x-labels: [serverless, ess] + operationId: PatchList + x-codegen-enabled: true + summary: Patch a list + description: Update specific fields of an existing list using the list ID. + requestBody: + description: List's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + name: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' + description: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' + version: + type: integer + minimum: 1 + _version: + type: string + required: + - id + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.ts new file mode 100644 index 000000000000..e5c06ddd7c25 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.gen.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Patch list item API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListItemId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; +import { ListItem } from '../model/list_schemas.gen'; + +export type PatchListItemRequestBody = z.infer; +export const PatchListItemRequestBody = z.object({ + id: ListItemId, + value: ListItemValue.optional(), + meta: ListItemMetadata.optional(), + _version: z.string().optional(), + /** + * Determines when changes made by the request are made visible to search + */ + refresh: z.enum(['true', 'false', 'wait_for']).optional(), +}); +export type PatchListItemRequestBodyInput = z.input; + +export type PatchListItemResponse = z.infer; +export const PatchListItemResponse = ListItem; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml new file mode 100644 index 000000000000..7802133dc4b1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/patch_list_item/patch_list_item.schema.yaml @@ -0,0 +1,76 @@ +openapi: 3.0.0 +info: + title: Patch list item API endpoint + version: '2023-10-31' +paths: + /api/lists/items: + patch: + x-labels: [serverless, ess] + operationId: PatchListItem + x-codegen-enabled: true + summary: Patch a list item + description: Update specific fields of an existing list item using the list item ID. + requestBody: + description: List item's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' + value: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' + _version: + type: string + refresh: + type: string + enum: + - 'true' + - 'false' + - wait_for + description: Determines when changes made by the request are made visible to search + required: + - id + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts new file mode 100644 index 000000000000..232f4b00540c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts @@ -0,0 +1,428 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Lists API client for quickstart + * version: Bundle (no version) + */ + +import type { KbnClient } from '@kbn/test'; +import { ToolingLog } from '@kbn/tooling-log'; +import { ELASTIC_HTTP_VERSION_HEADER } from '@kbn/core-http-common'; +import { catchAxiosErrorFormatAndThrow } from '@kbn/securitysolution-utils'; + +import type { CreateListIndexResponse } from './create_list_index/create_list_index.gen'; +import type { + CreateListItemRequestBodyInput, + CreateListItemResponse, +} from './create_list_item/create_list_item.gen'; +import type { CreateListRequestBodyInput, CreateListResponse } from './create_list/create_list.gen'; +import type { DeleteListIndexResponse } from './delete_list_index/delete_list_index.gen'; +import type { + DeleteListItemRequestQueryInput, + DeleteListItemResponse, +} from './delete_list_item/delete_list_item.gen'; +import type { + DeleteListRequestQueryInput, + DeleteListResponse, +} from './delete_list/delete_list.gen'; +import type { ExportListItemsRequestQueryInput } from './export_list_items/export_list_items.gen'; +import type { + FindListItemsRequestQueryInput, + FindListItemsResponse, +} from './find_list_items/find_list_items.gen'; +import type { FindListsRequestQueryInput, FindListsResponse } from './find_lists/find_lists.gen'; +import type { + ImportListItemsRequestQueryInput, + ImportListItemsResponse, +} from './import_list_items/import_list_items.gen'; +import type { + PatchListItemRequestBodyInput, + PatchListItemResponse, +} from './patch_list_item/patch_list_item.gen'; +import type { PatchListRequestBodyInput, PatchListResponse } from './patch_list/patch_list.gen'; +import type { ReadListIndexResponse } from './read_list_index/read_list_index.gen'; +import type { + ReadListItemRequestQueryInput, + ReadListItemResponse, +} from './read_list_item/read_list_item.gen'; +import type { ReadListPrivilegesResponse } from './read_list_privileges/read_list_privileges.gen'; +import type { ReadListRequestQueryInput, ReadListResponse } from './read_list/read_list.gen'; +import type { + UpdateListItemRequestBodyInput, + UpdateListItemResponse, +} from './update_list_item/update_list_item.gen'; +import type { UpdateListRequestBodyInput, UpdateListResponse } from './update_list/update_list.gen'; + +export interface ClientOptions { + kbnClient: KbnClient; + log: ToolingLog; +} + +export class Client { + readonly kbnClient: KbnClient; + readonly log: ToolingLog; + + constructor(options: ClientOptions) { + this.kbnClient = options.kbnClient; + this.log = options.log; + } + /** + * Create a new list. + */ + async createList(props: CreateListProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateList`); + return this.kbnClient + .request({ + path: '/api/lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Create `.lists` and `.items` data streams in the relevant space. + */ + async createListIndex() { + this.log.info(`${new Date().toISOString()} Calling API CreateListIndex`); + return this.kbnClient + .request({ + path: '/api/lists/index', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Create a list item and associate it with the specified list. + +All list items in the same list must be the same type. For example, each list item in an `ip` list must define a specific IP address. +> info +> Before creating a list item, you must create a list. + + */ + async createListItem(props: CreateListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API CreateListItem`); + return this.kbnClient + .request({ + path: '/api/lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Delete a list using the list ID. +> info +> When you delete a list, all of its list items are also deleted. + + */ + async deleteList(props: DeleteListProps) { + this.log.info(`${new Date().toISOString()} Calling API DeleteList`); + return this.kbnClient + .request({ + path: '/api/lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'DELETE', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Delete the `.lists` and `.items` data streams. + */ + async deleteListIndex() { + this.log.info(`${new Date().toISOString()} Calling API DeleteListIndex`); + return this.kbnClient + .request({ + path: '/api/lists/index', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'DELETE', + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Delete a list item using its `id`, or its `list_id` and `value` fields. + */ + async deleteListItem(props: DeleteListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API DeleteListItem`); + return this.kbnClient + .request({ + path: '/api/lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'DELETE', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Export list item values from the specified list. + */ + async exportListItems(props: ExportListItemsProps) { + this.log.info(`${new Date().toISOString()} Calling API ExportListItems`); + return this.kbnClient + .request({ + path: '/api/lists/items/_export', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get all list items in the specified list. + */ + async findListItems(props: FindListItemsProps) { + this.log.info(`${new Date().toISOString()} Calling API FindListItems`); + return this.kbnClient + .request({ + path: '/api/lists/items/_find', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get a paginated subset of lists. By default, the first page is returned, with 20 results per page. + */ + async findLists(props: FindListsProps) { + this.log.info(`${new Date().toISOString()} Calling API FindLists`); + return this.kbnClient + .request({ + path: '/api/lists/_find', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Import list items from a TXT or CSV file. The maximum file size is 9 million bytes. + +You can import items to a new or existing list. + + */ + async importListItems(props: ImportListItemsProps) { + this.log.info(`${new Date().toISOString()} Calling API ImportListItems`); + return this.kbnClient + .request({ + path: '/api/lists/items/_import', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'POST', + body: props.attachment, + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update specific fields of an existing list using the list ID. + */ + async patchList(props: PatchListProps) { + this.log.info(`${new Date().toISOString()} Calling API PatchList`); + return this.kbnClient + .request({ + path: '/api/lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PATCH', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update specific fields of an existing list item using the list item ID. + */ + async patchListItem(props: PatchListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API PatchListItem`); + return this.kbnClient + .request({ + path: '/api/lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PATCH', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get the details of a list using the list ID. + */ + async readList(props: ReadListProps) { + this.log.info(`${new Date().toISOString()} Calling API ReadList`); + return this.kbnClient + .request({ + path: '/api/lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Verify that `.lists` and `.items` data streams exist. + */ + async readListIndex() { + this.log.info(`${new Date().toISOString()} Calling API ReadListIndex`); + return this.kbnClient + .request({ + path: '/api/lists/index', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Get the details of a list item. + */ + async readListItem(props: ReadListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API ReadListItem`); + return this.kbnClient + .request({ + path: '/api/lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + + query: props.query, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + async readListPrivileges() { + this.log.info(`${new Date().toISOString()} Calling API ReadListPrivileges`); + return this.kbnClient + .request({ + path: '/api/lists/privileges', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'GET', + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update a list using the list ID. The original list is replaced, and all unspecified fields are deleted. +> info +> You cannot modify the `id` value. + + */ + async updateList(props: UpdateListProps) { + this.log.info(`${new Date().toISOString()} Calling API UpdateList`); + return this.kbnClient + .request({ + path: '/api/lists', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PUT', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } + /** + * Update a list item using the list item ID. The original list item is replaced, and all unspecified fields are deleted. +> info +> You cannot modify the `id` value. + + */ + async updateListItem(props: UpdateListItemProps) { + this.log.info(`${new Date().toISOString()} Calling API UpdateListItem`); + return this.kbnClient + .request({ + path: '/api/lists/items', + headers: { + [ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31', + }, + method: 'PUT', + body: props.body, + }) + .catch(catchAxiosErrorFormatAndThrow); + } +} + +export interface CreateListProps { + body: CreateListRequestBodyInput; +} +export interface CreateListItemProps { + body: CreateListItemRequestBodyInput; +} +export interface DeleteListProps { + query: DeleteListRequestQueryInput; +} +export interface DeleteListItemProps { + query: DeleteListItemRequestQueryInput; +} +export interface ExportListItemsProps { + query: ExportListItemsRequestQueryInput; +} +export interface FindListItemsProps { + query: FindListItemsRequestQueryInput; +} +export interface FindListsProps { + query: FindListsRequestQueryInput; +} +export interface ImportListItemsProps { + query: ImportListItemsRequestQueryInput; + attachment: FormData; +} +export interface PatchListProps { + body: PatchListRequestBodyInput; +} +export interface PatchListItemProps { + body: PatchListItemRequestBodyInput; +} +export interface ReadListProps { + query: ReadListRequestQueryInput; +} +export interface ReadListItemProps { + query: ReadListItemRequestQueryInput; +} +export interface UpdateListProps { + body: UpdateListRequestBodyInput; +} +export interface UpdateListItemProps { + body: UpdateListItemRequestBodyInput; +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.ts new file mode 100644 index 000000000000..d2967d71d57e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.gen.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Read list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListId } from '../model/list_common.gen'; +import { List } from '../model/list_schemas.gen'; + +export type ReadListRequestQuery = z.infer; +export const ReadListRequestQuery = z.object({ + /** + * List's `id` value + */ + id: ListId, +}); +export type ReadListRequestQueryInput = z.input; + +export type ReadListResponse = z.infer; +export const ReadListResponse = List; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml new file mode 100644 index 000000000000..e4a72d655509 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list/read_list.schema.yaml @@ -0,0 +1,58 @@ +openapi: 3.0.0 +info: + title: Read list API endpoint + version: '2023-10-31' +paths: + /api/lists: + get: + x-labels: [serverless, ess] + operationId: ReadList + x-codegen-enabled: true + summary: Get list details + description: Get the details of a list using the list ID. + parameters: + - name: id + in: query + required: true + description: List's `id` value + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.ts new file mode 100644 index 000000000000..bf0aec4dc6bc --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.gen.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Read list DS existence status API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +export type ReadListIndexResponse = z.infer; +export const ReadListIndexResponse = z.object({ + list_index: z.boolean(), + list_item_index: z.boolean(), +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml new file mode 100644 index 000000000000..b06b78ac3414 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_index/read_list_index.schema.yaml @@ -0,0 +1,57 @@ +openapi: 3.0.0 +info: + title: Read list DS existence status API endpoint + version: '2023-10-31' +paths: + /api/lists/index: + get: + x-labels: [serverless, ess] + operationId: ReadListIndex + x-codegen-enabled: true + summary: Get status of list data streams + description: Verify that `.lists` and `.items` data streams exist. + responses: + 200: + description: Successful response + content: + application/json: + schema: + type: object + properties: + list_index: + type: boolean + list_item_index: + type: boolean + required: [list_index, list_item_index] + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List data stream(s) not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.ts new file mode 100644 index 000000000000..d22ee4602226 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.gen.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Read list item API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListId } from '../model/list_common.gen'; +import { ListItem } from '../model/list_schemas.gen'; + +export type ReadListItemRequestQuery = z.infer; +export const ReadListItemRequestQuery = z.object({ + /** + * Required if `list_id` and `value` are not specified + */ + id: ListId.optional(), + /** + * Required if `id` is not specified + */ + list_id: ListId.optional(), + /** + * Required if `id` is not specified + */ + value: z.string().optional(), +}); +export type ReadListItemRequestQueryInput = z.input; + +export type ReadListItemResponse = z.infer; +export const ReadListItemResponse = z.union([ListItem, z.array(ListItem)]); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml new file mode 100644 index 000000000000..c1bb0697152b --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_item/read_list_item.schema.yaml @@ -0,0 +1,74 @@ +openapi: 3.0.0 +info: + title: Read list item API endpoint + version: '2023-10-31' +paths: + /api/lists/items: + get: + x-labels: [serverless, ess] + operationId: ReadListItem + x-codegen-enabled: true + summary: Get a list item + description: Get the details of a list item. + parameters: + - name: id + in: query + required: false + description: Required if `list_id` and `value` are not specified + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: list_id + in: query + required: false + description: Required if `id` is not specified + schema: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + - name: value + in: query + required: false + description: Required if `id` is not specified + schema: + type: string + responses: + 200: + description: Successful response + content: + application/json: + schema: + oneOf: + - $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + - type: array + items: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts similarity index 76% rename from packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts index 356915ba03cf..da6e7e95076d 100644 --- a/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.gen.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ /* diff --git a/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml similarity index 75% rename from packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml index ec8604e80694..d51e420aa4a9 100644 --- a/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/read_list_privileges/read_list_privileges.schema.yaml @@ -33,26 +33,26 @@ paths: application/json: schema: oneOf: - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' - - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' 401: description: Unsuccessful authentication response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 403: description: Not enough privileges response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' 500: description: Internal server error response content: application/json: schema: - $ref: '../../../kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' components: schemas: diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.ts new file mode 100644 index 000000000000..ffb28c3d0b53 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.gen.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Update list API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListId, ListName, ListDescription, ListMetadata } from '../model/list_common.gen'; +import { List } from '../model/list_schemas.gen'; + +export type UpdateListRequestBody = z.infer; +export const UpdateListRequestBody = z.object({ + id: ListId, + name: ListName, + description: ListDescription, + meta: ListMetadata.optional(), + version: z.number().int().min(1).optional(), + _version: z.string().optional(), +}); +export type UpdateListRequestBodyInput = z.input; + +export type UpdateListResponse = z.infer; +export const UpdateListResponse = List; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml new file mode 100644 index 000000000000..077a96d25d9e --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list/update_list.schema.yaml @@ -0,0 +1,79 @@ +openapi: 3.0.0 +info: + title: Update list API endpoint + version: '2023-10-31' +paths: + /api/lists: + put: + x-labels: [serverless, ess] + operationId: UpdateList + x-codegen-enabled: true + summary: Update a list + description: | + Update a list using the list ID. The original list is replaced, and all unspecified fields are deleted. + > info + > You cannot modify the `id` value. + requestBody: + description: List's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListId' + name: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListName' + description: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListDescription' + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListMetadata' + version: + type: integer + minimum: 1 + _version: + type: string + required: + - id + - name + - description + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/List' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.ts b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.ts new file mode 100644 index 000000000000..f5667676ab4c --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.gen.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * NOTICE: Do not edit this file manually. + * This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator. + * + * info: + * title: Update list item API endpoint + * version: 2023-10-31 + */ + +import { z } from '@kbn/zod'; + +import { ListItemId, ListItemValue, ListItemMetadata } from '../model/list_common.gen'; +import { ListItem } from '../model/list_schemas.gen'; + +export type UpdateListItemRequestBody = z.infer; +export const UpdateListItemRequestBody = z.object({ + id: ListItemId, + value: ListItemValue, + meta: ListItemMetadata.optional(), + _version: z.string().optional(), +}); +export type UpdateListItemRequestBodyInput = z.input; + +export type UpdateListItemResponse = z.infer; +export const UpdateListItemResponse = ListItem; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml new file mode 100644 index 000000000000..897137221047 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/update_list_item/update_list_item.schema.yaml @@ -0,0 +1,73 @@ +openapi: 3.0.0 +info: + title: Update list item API endpoint + version: '2023-10-31' +paths: + /api/lists/items: + put: + x-labels: [serverless, ess] + operationId: UpdateListItem + x-codegen-enabled: true + summary: Update a list item + description: | + Update a list item using the list item ID. The original list item is replaced, and all unspecified fields are deleted. + > info + > You cannot modify the `id` value. + requestBody: + description: List item's properties + required: true + content: + application/json: + schema: + type: object + properties: + id: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemId' + value: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemValue' + meta: + $ref: '../model/list_common.schema.yaml#/components/schemas/ListItemMetadata' + _version: + type: string + required: + - id + - value + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '../model/list_schemas.schema.yaml#/components/schemas/ListItem' + 400: + description: Invalid input data response + content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + - $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 401: + description: Unsuccessful authentication response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 403: + description: Not enough privileges response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/PlatformErrorResponse' + 404: + description: List item not found response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' + 500: + description: Internal server error response + content: + application/json: + schema: + $ref: '../../../../../../../src/platform/packages/shared/kbn-openapi-common/schemas/error_responses.schema.yaml#/components/schemas/SiemErrorResponse' diff --git a/packages/kbn-securitysolution-lists-common/docs/openapi/ess/security_solution_lists_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/ess/security_solution_lists_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-lists-common/docs/openapi/ess/security_solution_lists_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/ess/security_solution_lists_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-lists-common/docs/openapi/serverless/security_solution_lists_api_2023_10_31.bundled.schema.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/serverless/security_solution_lists_api_2023_10_31.bundled.schema.yaml similarity index 100% rename from packages/kbn-securitysolution-lists-common/docs/openapi/serverless/security_solution_lists_api_2023_10_31.bundled.schema.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/serverless/security_solution_lists_api_2023_10_31.bundled.schema.yaml diff --git a/packages/kbn-securitysolution-lists-common/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-lists-common/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/package.json new file mode 100644 index 000000000000..4e2b03521859 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/package.json @@ -0,0 +1,11 @@ +{ + "description": "Security Solution Lists common package", + "license": "Elastic License 2.0", + "name": "@kbn/securitysolution-lists-common", + "private": true, + "version": "1.0.0", + "scripts": { + "openapi:generate": "node scripts/openapi_generate", + "openapi:bundle": "node scripts/openapi_bundle" + } +} diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js new file mode 100644 index 000000000000..609ed8bb0807 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { bundle } = require('@kbn/openapi-bundler'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/serverless/security_solution_lists_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['serverless'], + prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/lists_serverless.info.yaml'), + }, + }); + + await bundle({ + sourceGlob: join(ROOT, 'api/**/*.schema.yaml'), + outputFilePath: join( + ROOT, + 'docs/openapi/ess/security_solution_lists_api_{version}.bundled.schema.yaml' + ), + options: { + includeLabels: ['ess'], + prototypeDocument: join(ROOT, 'scripts/openapi_bundle_info/lists_ess.info.yaml'), + }, + }); +})(); diff --git a/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_ess.info.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_ess.info.yaml similarity index 100% rename from packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_ess.info.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_ess.info.yaml diff --git a/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_serverless.info.yaml b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_serverless.info.yaml similarity index 100% rename from packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_serverless.info.yaml rename to x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle_info/lists_serverless.info.yaml diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js new file mode 100644 index 000000000000..ecda1a791e1f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_generate.js @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +require('../../../../../../src/setup_node_env'); +// eslint-disable-next-line import/no-nodejs-modules +const { join, resolve } = require('path'); +const { generate } = require('@kbn/openapi-generator'); +const { REPO_ROOT } = require('@kbn/repo-info'); + +const ROOT = resolve(__dirname, '..'); + +(async () => { + await generate({ + title: 'OpenAPI Lists API Schemas', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'zod_operation_schema', + }); + + await generate({ + title: 'Lists API client for tests', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'api_client_supertest', + skipLinting: true, + bundle: { + outFile: join( + REPO_ROOT, + 'x-pack/test/api_integration/services/security_solution_lists_api.gen.ts' + ), + }, + }); + + await generate({ + title: 'Lists API client for quickstart', + rootDir: ROOT, + sourceGlob: './api/**/*.schema.yaml', + templateName: 'api_client_quickstart', + skipLinting: true, + bundle: { + outFile: join( + REPO_ROOT, + 'x-pack/solutions/security/packages/kbn-securitysolution-lists-common/api/quickstart_client.gen.ts' + ), + }, + }); +})(); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/tsconfig.json new file mode 100644 index 000000000000..6a6637ff64a2 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-lists-common/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "outDir": "target/types", + "types": ["jest", "node"] + }, + "exclude": ["target/**/*"], + "extends": "../../../../../tsconfig.base.json", + "include": ["**/*.ts"], + "kbn_references": [ + "@kbn/zod-helpers", + "@kbn/openapi-common", + "@kbn/test", + "@kbn/tooling-log", + "@kbn/core-http-common", + "@kbn/securitysolution-utils", + "@kbn/zod", + ] +} diff --git a/packages/kbn-securitysolution-t-grid/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/README.md similarity index 100% rename from packages/kbn-securitysolution-t-grid/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-t-grid/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/index.ts new file mode 100644 index 000000000000..371d48e06c14 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/constants'; +export * from './src/utils'; +// eslint-disable-next-line @kbn/imports/no_boundary_crossing +export * from './src/mock'; diff --git a/packages/kbn-securitysolution-t-grid/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-t-grid/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-t-grid/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/package.json new file mode 100644 index 000000000000..d2f04084da36 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/package.json @@ -0,0 +1,7 @@ +{ + "name": "@kbn/securitysolution-t-grid", + "version": "1.0.0", + "description": "security solution t-grid packages will allow sharing components between timelines and security_solution plugin until we transfer all functionality to timelines plugin", + "license": "Elastic License 2.0", + "private": true +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/constants/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/constants/index.ts new file mode 100644 index 000000000000..a57893d63995 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/constants/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const HIGHLIGHTED_DROP_TARGET_CLASS_NAME = 'highlighted-drop-target'; +export const EMPTY_PROVIDERS_GROUP_CLASS_NAME = 'empty-providers-group'; + +/** The draggable will move this many pixels via the keyboard when the arrow key is pressed */ +export const KEYBOARD_DRAG_OFFSET = 20; + +export const DRAGGABLE_KEYBOARD_WRAPPER_CLASS_NAME = 'draggable-keyboard-wrapper'; + +export const ROW_RENDERER_CLASS_NAME = 'row-renderer'; + +export const NOTES_CONTAINER_CLASS_NAME = 'notes-container'; + +export const NOTE_CONTENT_CLASS_NAME = 'note-content'; + +/** This class is added to the document body while dragging */ +export const IS_DRAGGING_CLASS_NAME = 'is-dragging'; + +export const HOVER_ACTIONS_ALWAYS_SHOW_CLASS_NAME = 'hover-actions-always-show'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/index.ts new file mode 100644 index 000000000000..770bf1ffb018 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './mock_event_details'; diff --git a/packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts similarity index 97% rename from packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts index 5152132cda4b..538f6fa2cadc 100644 --- a/packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/mock/mock_event_details.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ export const eventHit = { diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/api/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/api/index.ts new file mode 100644 index 000000000000..add7df10fe13 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/api/index.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { has } from 'lodash/fp'; + +export interface AppError extends Error { + body: { + message: string; + }; +} + +export interface KibanaError extends AppError { + body: { + message: string; + statusCode: number; + }; +} + +export interface SecurityAppError extends AppError { + body: { + message: string; + status_code: number; + }; +} + +export const isKibanaError = (error: unknown): error is KibanaError => + has('message', error) && has('body.message', error) && has('body.statusCode', error); + +export const isSecurityAppError = (error: unknown): error is SecurityAppError => + has('message', error) && has('body.message', error) && has('body.status_code', error); + +export const isAppError = (error: unknown): error is AppError => + isKibanaError(error) || isSecurityAppError(error); + +export const isNotFoundError = (error: unknown) => + (isKibanaError(error) && error.body.statusCode === 404) || + (isSecurityAppError(error) && error.body.status_code === 404); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.ts new file mode 100644 index 000000000000..d954ebb055f1 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/drag_and_drop/index.ts @@ -0,0 +1,132 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { DropResult } from '@hello-pangea/dnd'; + +export const draggableIdPrefix = 'draggableId'; + +export const droppableIdPrefix = 'droppableId'; + +export const draggableContentPrefix = `${draggableIdPrefix}.content.`; + +export const draggableTimelineProvidersPrefix = `${draggableIdPrefix}.timelineProviders.`; + +export const draggableFieldPrefix = `${draggableIdPrefix}.field.`; + +export const droppableContentPrefix = `${droppableIdPrefix}.content.`; + +export const droppableFieldPrefix = `${droppableIdPrefix}.field.`; + +export const droppableTimelineProvidersPrefix = `${droppableIdPrefix}.timelineProviders.`; + +export const droppableTimelineColumnsPrefix = `${droppableIdPrefix}.timelineColumns.`; + +export const droppableTimelineFlyoutBottomBarPrefix = `${droppableIdPrefix}.flyoutButton.`; + +export const getDraggableId = (dataProviderId: string): string => + `${draggableContentPrefix}${dataProviderId}`; + +export const getDraggableFieldId = ({ + contextId, + fieldId, +}: { + contextId: string; + fieldId: string; +}): string => `${draggableFieldPrefix}${escapeContextId(contextId)}.${escapeFieldId(fieldId)}`; + +export const getTimelineProviderDroppableId = ({ + groupIndex, + timelineId, +}: { + groupIndex: number; + timelineId: string; +}): string => `${droppableTimelineProvidersPrefix}${timelineId}.group.${groupIndex}`; + +export const getTimelineProviderDraggableId = ({ + dataProviderId, + groupIndex, + timelineId, +}: { + dataProviderId: string; + groupIndex: number; + timelineId: string; +}): string => + `${draggableTimelineProvidersPrefix}${timelineId}.group.${groupIndex}.${dataProviderId}`; + +export const getDroppableId = (visualizationPlaceholderId: string): string => + `${droppableContentPrefix}${visualizationPlaceholderId}`; + +export const sourceIsContent = (result: DropResult): boolean => + result.source.droppableId.startsWith(droppableContentPrefix); + +export const sourceAndDestinationAreSameTimelineProviders = (result: DropResult): boolean => { + const regex = /^droppableId\.timelineProviders\.(\S+)\./; + const sourceMatches = result.source.droppableId.match(regex) || []; + const destinationMatches = + (result.destination && result.destination.droppableId.match(regex)) || []; + + return ( + sourceMatches.length >= 2 && + destinationMatches.length >= 2 && + sourceMatches[1] === destinationMatches[1] + ); +}; + +export const draggableIsContent = (result: DropResult | { draggableId: string }): boolean => + result.draggableId.startsWith(draggableContentPrefix); + +export const draggableIsField = (result: DropResult | { draggableId: string }): boolean => + result.draggableId.startsWith(draggableFieldPrefix); + +export const reasonIsDrop = (result: DropResult): boolean => result.reason === 'DROP'; + +export const destinationIsTimelineProviders = (result: DropResult): boolean => + result.destination != null && + result.destination.droppableId.startsWith(droppableTimelineProvidersPrefix); + +export const destinationIsTimelineColumns = (result: DropResult): boolean => + result.destination != null && + result.destination.droppableId.startsWith(droppableTimelineColumnsPrefix); + +export const destinationIsTimelineButton = (result: DropResult): boolean => + result.destination != null && + result.destination.droppableId.startsWith(droppableTimelineFlyoutBottomBarPrefix); + +export const getProviderIdFromDraggable = (result: DropResult): string => + result.draggableId.substring(result.draggableId.lastIndexOf('.') + 1); + +export const getFieldIdFromDraggable = (result: DropResult): string => + unEscapeFieldId(result.draggableId.substring(result.draggableId.lastIndexOf('.') + 1)); + +export const escapeDataProviderId = (path: string) => path.replace(/\./g, '_'); + +export const escapeContextId = (path: string) => path.replace(/\./g, '_'); + +export const escapeFieldId = (path: string) => path.replace(/\./g, '!!!DOT!!!'); + +export const unEscapeFieldId = (path: string) => path.replace(/!!!DOT!!!/g, '.'); + +export const providerWasDroppedOnTimeline = (result: DropResult): boolean => + reasonIsDrop(result) && + draggableIsContent(result) && + sourceIsContent(result) && + destinationIsTimelineProviders(result); + +export const userIsReArrangingProviders = (result: DropResult): boolean => + reasonIsDrop(result) && sourceAndDestinationAreSameTimelineProviders(result); + +export const fieldWasDroppedOnTimelineColumns = (result: DropResult): boolean => + reasonIsDrop(result) && draggableIsField(result) && destinationIsTimelineColumns(result); + +/** + * Prevents fields from being dragged or dropped to any area other than column + * header drop zone in the timeline + */ +export const DRAG_TYPE_FIELD = 'drag-type-field'; + +/** This class is added to the document body while timeline field dragging */ +export const IS_TIMELINE_FIELD_DRAGGING_CLASS_NAME = 'is-timeline-field-dragging'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/index.ts new file mode 100644 index 000000000000..cafe8ec570c8 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/src/utils/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './api'; +export * from './drag_and_drop'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/tsconfig.json new file mode 100644 index 000000000000..131ff3e6bb43 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-t-grid/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/packages/kbn-securitysolution-utils/README.md b/x-pack/solutions/security/packages/kbn-securitysolution-utils/README.md similarity index 100% rename from packages/kbn-securitysolution-utils/README.md rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/README.md diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/index.ts new file mode 100644 index 000000000000..dcf5ee7c4779 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './src/add_remove_id_to_item'; +export * from './src/axios'; +export * from './src/transform_data_to_ndjson'; +export * from './src/path_validations'; +export * from './src/esql'; +export * from './src/debounce_async/debounce_async'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/jest.config.js b/x-pack/solutions/security/packages/kbn-securitysolution-utils/jest.config.js new file mode 100644 index 000000000000..c25893390c68 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/jest.config.js @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/packages/kbn-securitysolution-utils'], +}; diff --git a/packages/kbn-securitysolution-utils/kibana.jsonc b/x-pack/solutions/security/packages/kbn-securitysolution-utils/kibana.jsonc similarity index 100% rename from packages/kbn-securitysolution-utils/kibana.jsonc rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/kibana.jsonc diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/package.json b/x-pack/solutions/security/packages/kbn-securitysolution-utils/package.json new file mode 100644 index 000000000000..d9311ef37a28 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/securitysolution-utils", + "version": "1.0.0", + "description": "security solution utilities to use across plugins such lists, security_solution, cases, etc...", + "license": "Elastic License 2.0", + "private": true, + "sideEffects": false +} \ No newline at end of file diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts new file mode 100644 index 000000000000..13d13b2acf89 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.test.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { addIdToItem, removeIdFromItem } from '.'; + +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/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts new file mode 100644 index 000000000000..5133a13bdbec --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/add_remove_id_to_item/index.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { v4 as uuidv4 } 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 = item as typeof item & { id?: string }; + if (maybeId.id != null) { + return item; + } else { + return { ...item, id: uuidv4() }; + } +}; + +/** + * 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 = item as typeof item & { id?: string }; + if (maybeId.id != null) { + const { id, ...noId } = maybeId; + return noId; + } else { + return item; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/axios/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/axios/index.ts new file mode 100644 index 000000000000..44972dba9356 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/axios/index.ts @@ -0,0 +1,71 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { AxiosError } from 'axios'; + +export class FormattedAxiosError extends Error { + public readonly request: { + method: string; + url: string; + data: unknown; + }; + public readonly response: { + status: number; + statusText: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data: any; + }; + + constructor(axiosError: AxiosError) { + const method = axiosError.config?.method ?? ''; + const url = axiosError.config?.url ?? ''; + + super( + `${axiosError.message}${ + axiosError?.response?.data ? `: ${JSON.stringify(axiosError?.response?.data)}` : '' + }${url ? `\n(Request: ${method} ${url})` : ''}` + ); + + this.request = { + method, + url, + data: axiosError.config?.data ?? '', + }; + + this.response = { + status: axiosError?.response?.status ?? 0, + statusText: axiosError?.response?.statusText ?? '', + data: axiosError?.response?.data, + }; + + this.name = this.constructor.name; + } + + toJSON() { + return { + message: this.message, + request: this.request, + response: this.response, + }; + } + + toString() { + return JSON.stringify(this.toJSON(), null, 2); + } +} + +/** + * Used with `promise.catch()`, it will format the Axios error to a new error and will re-throw + * @param error + */ +export const catchAxiosErrorFormatAndThrow = (error: Error): never => { + if (error instanceof AxiosError) { + throw new FormattedAxiosError(error); + } + + throw error; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts new file mode 100644 index 000000000000..3a44e5061d09 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/client_concurrency/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import limit from 'p-limit'; + +/** + * This type is just an async function's type + */ +type RequestFactory = () => Promise; + +/** + * Helper function to call a large number of async functions with limited concurrency. + * Example pattern of how to create functions to pass in: + * + * const ruleCopies = duplicateRuleParams(basicRule, 200); + * const functions = ruleCopies.map((rule) => () => detectionsClient.createRule({ body: rule })); + * + * Note that the `map` call in the example returns a *function* that calls detectionsClient.createRule, it doesn't call createRule immediately. + * + * @param functions Async functions to call with limited concurrency + * @param concurrency Maximum number of concurrent function calls + * @returns Results from all functions passed in + */ +export const concurrentlyExec = async ( + requestFactories: Array>, + concurrency: number = 10 +) => { + const limiter = limit(concurrency); + const promises = requestFactories.map((f) => limiter(f)); + return Promise.all(promises); +}; diff --git a/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts similarity index 77% rename from packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts index d7e1201e44e8..7508e99a891f 100644 --- a/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { debounceAsync } from './debounce_async'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.ts new file mode 100644 index 000000000000..ac9f2348d0be --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/debounce_async/debounce_async.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/** + * Unlike lodash's debounce, which resolves intermediate calls with the most + * recent value, this implementation waits to resolve intermediate calls until + * the next invocation resolves. + * + * @param fn an async function + * + * @returns A debounced async function that resolves on the next invocation + */ +export function debounceAsync( + fn: (...args: Args) => Result, + intervalMs: number +): (...args: Args) => Promise> { + let timeoutId: ReturnType | undefined; + let resolve: (value: Awaited) => void; + let promise = new Promise>((_resolve) => { + resolve = _resolve; + }); + + return (...args) => { + if (timeoutId) { + clearTimeout(timeoutId); + } + + timeoutId = setTimeout(async () => { + resolve(await fn(...args)); + promise = new Promise((_resolve) => { + resolve = _resolve; + }); + }, intervalMs); + + return promise; + }; +} diff --git a/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts similarity index 84% rename from packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts index cb92d34b33ec..41268ac0fa85 100644 --- a/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { computeIsESQLQueryAggregating } from './compute_if_esql_query_aggregating'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.ts new file mode 100644 index 000000000000..d38abdaa481a --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/compute_if_esql_query_aggregating.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { type ESQLAstQueryExpression, parse } from '@kbn/esql-ast'; + +export const isAggregatingQuery = (astExpression: ESQLAstQueryExpression): boolean => + astExpression.commands.some((command) => command.name === 'stats'); + +/** + * compute if esqlQuery is aggregating/grouping, i.e. using STATS...BY command + * @param esqlQuery + * @returns boolean + */ +export const computeIsESQLQueryAggregating = (esqlQuery: string): boolean => { + const { root } = parse(esqlQuery); + return isAggregatingQuery(root); +}; diff --git a/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts similarity index 80% rename from packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts index 7a7726c47e14..39dc934dcdd2 100644 --- a/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.ts new file mode 100644 index 000000000000..654f09cd0b84 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/get_index_list_from_esql_query.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils'; + +/** + * parses ES|QL query and returns array of indices + */ +export const getIndexListFromEsqlQuery = (query: string | undefined): string[] => { + try { + const indexString = getIndexPatternFromESQLQuery(query); + + return getIndexListFromIndexString(indexString); + } catch (e) { + return []; + } +}; + +/** + * transforms sting of indices, separated by commas to array + * index*, index2* => [index*, index2*] + */ +export const getIndexListFromIndexString = (indexString: string | undefined): string[] => { + if (!indexString) { + return []; + } + return indexString.split(',').map((index) => index.trim()); +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/index.ts new file mode 100644 index 000000000000..ff6f8a455244 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './compute_if_esql_query_aggregating'; +export * from './get_index_list_from_esql_query'; +export * from './parse_esql_query'; diff --git a/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts similarity index 90% rename from packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts index 6c4fdafd8e70..1e7484fd6e4b 100644 --- a/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.test.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { parseEsqlQuery } from './parse_esql_query'; diff --git a/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts similarity index 83% rename from packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts rename to x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts index 2a62aed8873a..6e088bf386fb 100644 --- a/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/esql/parse_esql_query.ts @@ -1,10 +1,8 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the "Elastic License - * 2.0", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public - * License v3.0 only", or the "Server Side Public License, v 1". + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. */ import { type ESQLAstQueryExpression, parse, ESQLCommandOption, EditorError } from '@kbn/esql-ast'; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts new file mode 100644 index 000000000000..5304c3a71061 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.test.ts @@ -0,0 +1,758 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + isPathValid, + hasSimpleExecutableName, + OperatingSystem, + ConditionEntryField, + validateWildcardInput, + validateHasWildcardWithWrongOperator, + validatePotentialWildcardInput, + validateFilePathInput, + WILDCARD_WARNING, + FILEPATH_WARNING, +} from '.'; + +describe('validatePotentialWildcardInput', () => { + it('warns on wildcard when field is file.path.text', () => { + expect( + validatePotentialWildcardInput({ + field: 'file.path.text', + os: OperatingSystem.WINDOWS, + value: 'c:\\path*.exe', + }) + ).toEqual(WILDCARD_WARNING); + }); + it('warns on wildcard when field is not file.path.text', () => { + expect( + validatePotentialWildcardInput({ + field: 'event.category', + os: OperatingSystem.WINDOWS, + value: 'some*value', + }) + ).toEqual(WILDCARD_WARNING); + }); +}); + +describe('validateWildcardInput', () => { + it('warns on wildcard for fields that are not file paths', () => { + expect(validateWildcardInput('*')).toEqual(WILDCARD_WARNING); + }); + it('does not warn if no wildcard', () => { + expect(validateWildcardInput('non-wildcard')).toEqual(undefined); + }); +}); + +describe('validateFilePathInput', () => { + describe('windows', () => { + const os = OperatingSystem.WINDOWS; + + it('does not warn on valid filenames', () => { + expect( + validateFilePathInput({ + os, + value: 'C:\\Windows\\*\\FILENAME.EXE-1231205124.gz', + }) + ).not.toBeDefined(); + expect( + validateFilePathInput({ + os, + value: "C:\\Windows\\*\\test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", + }) + ).toEqual(undefined); + }); + + it('warns on wildcard in file name at the end of the path', () => { + expect(validateFilePathInput({ os, value: 'c:\\path*.exe' })).toEqual(WILDCARD_WARNING); + expect( + validateFilePathInput({ + os, + value: 'C:\\Windows\\*\\FILENAME.EXE-*.gz', + }) + ).toEqual(WILDCARD_WARNING); + }); + + it('warns on unix paths or non-windows paths', () => { + expect(validateFilePathInput({ os, value: '/opt/bin' })).toEqual(FILEPATH_WARNING); + }); + + it('warns on malformed paths', () => { + expect(validateFilePathInput({ os, value: 'c:\\path/opt' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: '1242' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: 'w12efdfa' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: 'c:\\folder\\' })).toEqual(FILEPATH_WARNING); + }); + }); + describe('unix paths', () => { + const os = + parseInt((Math.random() * 2).toString(), 10) === 1 + ? OperatingSystem.MAC + : OperatingSystem.LINUX; + + it('does not warn on valid filenames', () => { + expect( + validateFilePathInput({ + os, + value: '/opt/*/FILENAME.EXE-1231205124.gz', + }) + ).not.toEqual(WILDCARD_WARNING); + expect( + validateFilePathInput({ + os, + value: "/opt/*/test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", + }) + ).not.toEqual(WILDCARD_WARNING); + }); + it('warns on wildcard in file name at the end of the path', () => { + expect(validateFilePathInput({ os, value: '/opt/bin*' })).toEqual(WILDCARD_WARNING); + expect(validateFilePathInput({ os, value: '/opt/FILENAME.EXE-*.gz' })).toEqual( + WILDCARD_WARNING + ); + }); + + it('warns on windows paths', () => { + expect(validateFilePathInput({ os, value: 'd:\\path\\file.exe' })).toEqual(FILEPATH_WARNING); + }); + + it('warns on malformed paths', () => { + expect(validateFilePathInput({ os, value: 'opt/bin\\file.exe' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: '1242' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: 'w12efdfa' })).toEqual(FILEPATH_WARNING); + expect(validateFilePathInput({ os, value: '/folder/' })).toEqual(FILEPATH_WARNING); + }); + }); +}); + +describe('Wildcard and invalid operator', () => { + it('should return TRUE when operator is not "WILDCARD" and value contains a wildcard', () => { + expect(validateHasWildcardWithWrongOperator({ operator: 'match', value: 'asdf*' })).toEqual( + true + ); + }); + it('should return FALSE when operator is not "WILDCARD" and value does not contain a wildcard', () => { + expect(validateHasWildcardWithWrongOperator({ operator: 'match', value: 'asdf' })).toEqual( + false + ); + }); + it('should return FALSE when operator is "WILDCARD" and value contains a wildcard', () => { + expect(validateHasWildcardWithWrongOperator({ operator: 'wildcard', value: 'asdf*' })).toEqual( + false + ); + }); + it('should return FALSE when operator is "WILDCARD" and value does not contain a wildcard', () => { + expect(validateHasWildcardWithWrongOperator({ operator: 'wildcard', value: 'asdf' })).toEqual( + false + ); + }); +}); + +describe('No Warnings', () => { + it('should not show warnings on non path entries ', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.HASH, + type: 'match', + value: '5d5b09f6dcb2d53a5fffc60c4ac0d55fabdf556069d6631545f42aa6e3500f2e', + }) + ).toEqual(true); + + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.SIGNER, + type: 'match', + value: '', + }) + ).toEqual(true); + }); +}); + +describe('Unacceptable Windows wildcard paths', () => { + it('should not accept paths that do not have a folder name with a wildcard ', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:\\folder', + }) + ).toEqual(false); + }); + + it('should not accept paths that do not have a file name with a wildcard ', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:\\path.exe', + }) + ).toEqual(false); + }); + + it('should not accept nested paths that do not have a wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:\\folder\\path.exe', + }) + ).toEqual(false); + }); + + it('should not accept paths with * wildcard and /', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:/**/path.exe', + }) + ).toEqual(false); + }); + + it('should not accept paths with ? wildcard and /', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:/?indows/pat?', + }) + ).toEqual(false); + }); +}); + +describe('Acceptable Windows wildcard paths', () => { + it('should accept wildcards for folders', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:\\**\\path.exe', + }) + ).toEqual(true); + }); + + it('should accept wildcards for folders and files', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'e:\\**\\*.exe', + }) + ).toEqual(true); + }); + + it('should accept paths with single wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'f:\\*', + }) + ).toEqual(true); + + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'f:\\?', + }) + ).toEqual(true); + }); + + it('should accept paths that have wildcard in filenames', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'a:\\*.*', + }) + ).toEqual(true); + }); + + it('should accept paths with ? as wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:\\?indows\\pat?', + }) + ).toEqual(true); + }); + + it('should accept paths with both ? and * as wildcards', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:\\*?', + }) + ).toEqual(true); + }); + + it('should accept paths with multiple wildcards', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:\\**', + }) + ).toEqual(true); + + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:\\??', + }) + ).toEqual(true); + }); +}); + +describe('Acceptable Windows exact paths', () => { + it('should accept paths when it ends with a folder name', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\folder', + }) + ).toEqual(true); + }); + + it('should accept paths when it ends with a file name', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\path.exe', + }) + ).toEqual(true); + }); + + it('should accept paths when it ends with a filename in a folder', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\folder\\path.exe', + }) + ).toEqual(true); + }); +}); + +describe('Acceptable Windows exact paths with hyphens', () => { + it('should accept paths when paths have folder names with hyphens', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\hype-folder-name', + }) + ).toEqual(true); + }); + + it('should accept paths when file names have hyphens', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\file-name.exe', + }) + ).toEqual(true); + }); +}); + +describe('Unacceptable Windows exact paths', () => { + it('should not accept paths with /', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:/folder/path.exe', + }) + ).toEqual(false); + }); + + it('should not accept paths not having a in the suffix', () => { + expect( + isPathValid({ + os: OperatingSystem.WINDOWS, + field: ConditionEntryField.PATH, + type: 'match', + value: '\\folder\\path.exe', + }) + ).toEqual(false); + }); +}); + +/// +describe('Unacceptable Mac/Linux wildcard paths', () => { + it('should not accept paths that do not have a folder name with a wildcard ', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/folder', + }) + ).toEqual(false); + }); + + it('should not accept paths that do not have a file name with a wildcard ', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/zip.zip', + }) + ).toEqual(false); + }); + + it('should not accept nested paths that do not have a wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/opt/pack.tar', + }) + ).toEqual(false); + }); + + it('should not accept paths with * wildcard and \\', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'c:\\**\\path.exe', + }) + ).toEqual(false); + }); + + it('should not accept paths with ? wildcard and \\', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: 'C:\\?indows\\pat?', + }) + ).toEqual(false); + }); +}); + +describe('Acceptable Mac/Linux wildcard paths', () => { + it('should accept wildcards for folders', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/**/file.', + }) + ).toEqual(true); + }); + + it('should accept wildcards for folders and files', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/usr/bi?/*.js', + }) + ).toEqual(true); + }); + + it('should accept paths with single wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/op*', + }) + ).toEqual(true); + + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/op?', + }) + ).toEqual(true); + }); + + it('should accept paths that have wildcard in filenames', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/*.*', + }) + ).toEqual(true); + }); + + it('should accept paths with ? as wildcard', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/usr/?inux/pat?', + }) + ).toEqual(true); + }); + + it('should accept paths with both ? and * as wildcards', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/usr/*?', + }) + ).toEqual(true); + }); + + it('should accept paths with multiple wildcards', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/usr/**', + }) + ).toEqual(true); + + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'wildcard', + value: '/opt/??', + }) + ).toEqual(true); + }); +}); + +describe('Acceptable Mac/Linux exact paths', () => { + it('should accept paths when it is the root path', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'match', + value: '/', + }) + ).toEqual(true); + }); + + it('should accept paths when it ends with a file name', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'match', + value: '/usr/file.ts', + }) + ).toEqual(true); + }); + + it('should accept paths when it ends with a filename in a folder', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'match', + value: '/opt/z.dmg', + }) + ).toEqual(true); + }); +}); + +describe('Acceptable Mac/Linux exact paths with hyphens', () => { + it('should accept paths when paths have folder names with hyphens', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'match', + value: '/hype-folder-name', + }) + ).toEqual(true); + }); + + it('should accept paths when file names have hyphens', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'match', + value: '/file-name.dmg', + }) + ).toEqual(true); + }); +}); + +describe('Unacceptable Mac/Linux exact paths', () => { + it('should not accept paths with \\', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'match', + value: 'c:\\folder\\path.exe', + }) + ).toEqual(false); + }); + + it('should not accept paths not starting with /', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'match', + value: 'opt/bin', + }) + ).toEqual(false); + }); + + it('should not accept paths ending with /', () => { + expect( + isPathValid({ + os: OperatingSystem.MAC, + field: ConditionEntryField.PATH, + type: 'match', + value: '/opt/bin/', + }) + ).toEqual(false); + }); + + it('should not accept file extensions with hyphens', () => { + expect( + isPathValid({ + os: OperatingSystem.LINUX, + field: ConditionEntryField.PATH, + type: 'match', + value: '/opt/bin/file.d-mg', + }) + ).toEqual(false); + }); +}); + +describe('hasSimpleExecutableName', () => { + it('should return TRUE when MAC/LINUX wildcard paths have an executable name', () => { + const os = + parseInt((Math.random() * 2).toString(), 10) === 1 + ? OperatingSystem.MAC + : OperatingSystem.LINUX; + + expect( + hasSimpleExecutableName({ + os, + type: 'wildcard', + value: '/opt/*/app', + }) + ).toEqual(true); + expect( + hasSimpleExecutableName({ + os, + type: 'wildcard', + value: '/op*/**/app.dmg', + }) + ).toEqual(true); + expect( + hasSimpleExecutableName({ + os, + type: 'wildcard', + value: "/sy*/test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", + }) + ).toEqual(true); + }); + + it('should return FALSE when MAC/LINUX wildcard paths have a wildcard in executable name', () => { + const os = + parseInt((Math.random() * 2).toString(), 10) === 1 + ? OperatingSystem.MAC + : OperatingSystem.LINUX; + + expect( + hasSimpleExecutableName({ + os, + type: 'wildcard', + value: '/op/*/*pp', + }) + ).toEqual(false); + expect( + hasSimpleExecutableName({ + os, + type: 'wildcard', + value: '/op*/b**/ap.m**', + }) + ).toEqual(false); + }); + + it('should return TRUE when WINDOWS wildcards paths have a executable name', () => { + expect( + hasSimpleExecutableName({ + os: OperatingSystem.WINDOWS, + type: 'wildcard', + value: 'c:\\**\\path.exe', + }) + ).toEqual(true); + expect( + hasSimpleExecutableName({ + os: OperatingSystem.WINDOWS, + type: 'wildcard', + value: 'C:\\*\\file-name.path华语 1234.txt', + }) + ).toEqual(true); + expect( + hasSimpleExecutableName({ + os: OperatingSystem.WINDOWS, + type: 'wildcard', + value: "C:\\*\\test$ as2@13---12!@#A,DS.#$^&$!#~ 'as'd.华语.txt", + }) + ).toEqual(true); + }); + + it('should return FALSE when WINDOWS wildcards paths have a wildcard in executable name', () => { + expect( + hasSimpleExecutableName({ + os: OperatingSystem.WINDOWS, + type: 'wildcard', + value: 'c:\\**\\pa*h.exe', + }) + ).toEqual(false); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.ts new file mode 100644 index 000000000000..965a5b9fbe0f --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/path_validations/index.ts @@ -0,0 +1,243 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const WILDCARD_WARNING = i18n.translate('utils.wildcardWarning', { + defaultMessage: `Using wildcards can impact Endpoint performance`, +}); + +export const FILEPATH_WARNING = i18n.translate('utils.filename.pathWarning', { + defaultMessage: `Path may be formed incorrectly; verify value`, +}); + +export enum ConditionEntryField { + HASH = 'process.hash.*', + PATH = 'process.executable.caseless', + SIGNER = 'process.Ext.code_signature', + SIGNER_MAC = 'process.code_signature', +} + +export enum EntryFieldType { + HASH = '.hash.', + EXECUTABLE = '.executable.caseless', + PATH = '.path', + SIGNER = '.code_signature', +} + +export type TrustedAppConditionEntryField = + | 'process.hash.*' + | 'process.executable.caseless' + | 'process.Ext.code_signature' + | 'process.code_signature'; + +export type BlocklistConditionEntryField = + | 'file.hash.*' + | 'file.path' + | 'file.Ext.code_signature' + | 'file.path.caseless'; +export type AllConditionEntryFields = + | TrustedAppConditionEntryField + | BlocklistConditionEntryField + | 'file.path.text'; + +export enum OperatingSystem { + LINUX = 'linux', + MAC = 'macos', + WINDOWS = 'windows', +} + +export type EntryTypes = 'match' | 'wildcard' | 'match_any'; +export type TrustedAppEntryTypes = Extract; +export type EventFiltersTypes = EntryTypes | 'exists' | 'nested'; + +export const validatePotentialWildcardInput = ({ + field = '', + os, + value = '', +}: { + field?: string; + os: OperatingSystem; + value?: string; +}): string | undefined => { + const textInput = value.trim(); + if (field === 'file.path.text') { + return validateFilePathInput({ os, value: textInput }); + } + return validateWildcardInput(textInput); +}; + +export const validateFilePathInput = ({ + os, + value, +}: { + os: OperatingSystem; + value: string; +}): string | undefined => { + const isValidFilePath = isPathValid({ + os, + field: 'file.path.text', + type: 'wildcard', + value, + }); + const hasSimpleFileName = hasSimpleExecutableName({ + os, + type: 'wildcard', + value, + }); + + if (!value.length) { + return FILEPATH_WARNING; + } + + if (isValidFilePath) { + if (hasSimpleFileName !== undefined && !hasSimpleFileName) { + return WILDCARD_WARNING; + } + } else { + return FILEPATH_WARNING; + } +}; + +export const validateWildcardInput = (value: string | string[]): string | undefined => { + const wildcardRegex = /[*?]/; + if (Array.isArray(value)) { + const doesAnyValueContainWildcardInput = value.some((v) => wildcardRegex.test(v)); + if (doesAnyValueContainWildcardInput) { + return WILDCARD_WARNING; + } + } else { + if (wildcardRegex.test(value)) { + return WILDCARD_WARNING; + } + } +}; + +export const validateHasWildcardWithWrongOperator = ({ + operator, + value, +}: { + operator: TrustedAppEntryTypes | EventFiltersTypes; + value: string | string[]; +}): boolean => { + if (operator !== 'wildcard' && validateWildcardInput(value)) { + return true; + } else { + return false; + } +}; + +export const hasSimpleExecutableName = ({ + os, + type, + value, +}: { + os: OperatingSystem; + type: EntryTypes; + value: string; +}): boolean | undefined => { + const separator = os === OperatingSystem.WINDOWS ? '\\' : '/'; + const lastString = value.split(separator).pop(); + if (!lastString) { + return; + } + if (type === 'wildcard') { + return (lastString.split('*').length || lastString.split('?').length) === 1; + } + return true; +}; + +export const isPathValid = ({ + os, + field, + type, + value, +}: { + os: OperatingSystem; + field: AllConditionEntryFields; + type: EntryTypes; + value: string; +}): boolean => { + const pathFields: AllConditionEntryFields[] = [ + 'process.executable.caseless', + 'file.path', + 'file.path.text', + ]; + if (pathFields.includes(field)) { + if (type === 'wildcard') { + return os === OperatingSystem.WINDOWS + ? isWindowsWildcardPathValid(value) + : isLinuxMacWildcardPathValid(value); + } + return doesPathMatchRegex({ value, os }); + } + return true; +}; + +const doesPathMatchRegex = ({ os, value }: { os: OperatingSystem; value: string }): boolean => { + if (os === OperatingSystem.WINDOWS) { + const filePathRegex = + /^[a-z]:(?:|\\\\[^<>:"'/\\|?*]+\\[^<>:"'/\\|?*]+|%\w+%|)[\\](?:[^<>:"'/\\|?*]+[\\/])*([^<>:"'/\\|?*])+$/i; + return filePathRegex.test(value); + } + return /^(\/|(\/[\w\-]+)+|\/[\w\-]+\.[\w]+|(\/[\w-]+)+\/[\w\-]+\.[\w]+)$/i.test(value); +}; + +const isWindowsWildcardPathValid = (path: string): boolean => { + const firstCharacter = path[0]; + const lastCharacter = path.slice(-1); + const trimmedValue = path.trim(); + const hasSlash = /\//.test(trimmedValue); + if (path.length === 0) { + return false; + } else if ( + hasSlash || + trimmedValue.length !== path.length || + firstCharacter === '^' || + lastCharacter === '\\' || + !hasWildcard({ path, isWindowsPath: true }) + ) { + return false; + } else { + return true; + } +}; + +const isLinuxMacWildcardPathValid = (path: string): boolean => { + const firstCharacter = path[0]; + const lastCharacter = path.slice(-1); + const trimmedValue = path.trim(); + if (path.length === 0) { + return false; + } else if ( + trimmedValue.length !== path.length || + firstCharacter !== '/' || + lastCharacter === '/' || + path.length > 1024 === true || + path.includes('//') === true || + !hasWildcard({ path, isWindowsPath: false }) + ) { + return false; + } else { + return true; + } +}; + +const hasWildcard = ({ + path, + isWindowsPath, +}: { + path: string; + isWindowsPath: boolean; +}): boolean => { + for (const pathComponent of path.split(isWindowsPath ? '\\' : '/')) { + if (/[\*|\?]+/.test(pathComponent) === true) { + return true; + } + } + return false; +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts new file mode 100644 index 000000000000..d91eb687d86d --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { transformDataToNdjson } from '.'; + +export const ANCHOR_DATE = '2020-02-20T03:57:54.037Z'; + +const getRulesSchemaMock = (anchorDate: string = ANCHOR_DATE) => ({ + author: [], + id: '7a7065d7-6e8b-4aae-8d20-c93613dec9f9', + created_at: new Date(anchorDate).toISOString(), + updated_at: new Date(anchorDate).toISOString(), + created_by: 'elastic', + description: 'some description', + enabled: true, + false_positives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + immutable: false, + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + references: ['test 1', 'test 2'], + severity: 'high', + severity_mapping: [], + updated_by: 'elastic_kibana', + tags: ['some fake tag 1', 'some fake tag 2'], + to: 'now', + type: 'query', + threat: [], + version: 1, + output_index: '.siem-signals-default', + max_signals: 100, + risk_score: 55, + risk_score_mapping: [], + language: 'kuery', + rule_id: 'query-rule-id', + interval: '5m', + exceptions_list: [], +}); + +describe('transformDataToNdjson', () => { + test('if rules are empty it returns an empty string', () => { + const ruleNdjson = transformDataToNdjson([]); + expect(ruleNdjson).toEqual(''); + }); + + test('single rule will transform with new line ending character for ndjson', () => { + const rule = getRulesSchemaMock(); + const ruleNdjson = transformDataToNdjson([rule]); + expect(ruleNdjson.endsWith('\n')).toBe(true); + }); + + test('multiple rules will transform with two new line ending characters for ndjson', () => { + const result1 = getRulesSchemaMock(); + const result2 = getRulesSchemaMock(); + result2.id = 'some other id'; + result2.rule_id = 'some other id'; + result2.name = 'Some other rule'; + + const ruleNdjson = transformDataToNdjson([result1, result2]); + // this is how we count characters in JavaScript :-) + const count = ruleNdjson.split('\n').length - 1; + expect(count).toBe(2); + }); + + test('you can parse two rules back out without errors', () => { + const result1 = getRulesSchemaMock(); + const result2 = getRulesSchemaMock(); + result2.id = 'some other id'; + result2.rule_id = 'some other id'; + result2.name = 'Some other rule'; + + const ruleNdjson = transformDataToNdjson([result1, result2]); + const ruleStrings = ruleNdjson.split('\n'); + const reParsed1 = JSON.parse(ruleStrings[0]); + const reParsed2 = JSON.parse(ruleStrings[1]); + expect(reParsed1).toEqual(result1); + expect(reParsed2).toEqual(result2); + }); +}); diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts new file mode 100644 index 000000000000..572b777731c4 --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/src/transform_data_to_ndjson/index.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export const transformDataToNdjson = (data: unknown[]): string => { + if (data.length !== 0) { + const dataString = data.map((item) => JSON.stringify(item)).join('\n'); + return `${dataString}\n`; + } else { + return ''; + } +}; diff --git a/x-pack/solutions/security/packages/kbn-securitysolution-utils/tsconfig.json b/x-pack/solutions/security/packages/kbn-securitysolution-utils/tsconfig.json new file mode 100644 index 000000000000..063735a114da --- /dev/null +++ b/x-pack/solutions/security/packages/kbn-securitysolution-utils/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types", + "types": [ + "jest", + "node" + ] + }, + "include": [ + "**/*.ts" + ], + "kbn_references": [ + "@kbn/i18n", + "@kbn/esql-utils", + "@kbn/esql-ast", + "@kbn/esql-validation-autocomplete" + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/x-pack/solutions/security/plugins/asset_inventory/README.md b/x-pack/solutions/security/plugins/asset_inventory/README.md index e1dd9d4ac890..313a45cec6f7 100755 --- a/x-pack/solutions/security/plugins/asset_inventory/README.md +++ b/x-pack/solutions/security/plugins/asset_inventory/README.md @@ -8,6 +8,14 @@ Centralized asset inventory experience within the Elastic Security solution. A c See the [kibana contributing guide](https://github.com/elastic/kibana/blob/main/CONTRIBUTING.md) for instructions setting up your development environment. +### Feature flag + +First, enable the `assetInventoryStoreEnabled` experimental feature flag by adding the following to your `kibana.dev.yml`: + +```yml +xpack.securitySolution.enableExperimental: ['assetInventoryStoreEnabled'] +``` + ## Testing For general guidelines, read [Kibana Testing Guide](https://www.elastic.co/guide/en/kibana/current/development-tests.html) for more details diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/route.ts b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/route.ts index f9544b656f92..f65574781585 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/route.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/route.ts @@ -43,7 +43,7 @@ export const defineGraphRoute = (router: CspRouter) => const cspContext = await context.csp; const { nodesLimit, showUnknownTarget = false } = request.body; - const { eventIds, start, end, esQuery } = request.body.query as GraphRequest['query']; + const { originEventIds, start, end, esQuery } = request.body.query as GraphRequest['query']; const spaceId = (await cspContext.spaces?.spacesService?.getActiveSpace(request))?.id; try { @@ -53,7 +53,7 @@ export const defineGraphRoute = (router: CspRouter) => esClient: cspContext.esClient, }, query: { - eventIds, + originEventIds, spaceId, start, end, diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/v1.ts b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/v1.ts index b14a2ba3e06a..d506bb856e76 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/v1.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/graph/v1.ts @@ -33,7 +33,8 @@ interface GraphEdge { action: string; targetIds: string[] | string; eventOutcome: string; - isAlert: boolean; + isOrigin: boolean; + isOriginAlert: boolean; } interface LabelEdges { @@ -46,10 +47,15 @@ interface GraphContextServices { esClient: IScopedClusterClient; } +interface OriginEventId { + id: string; + isAlert: boolean; +} + interface GetGraphParams { services: GraphContextServices; query: { - eventIds: string[]; + originEventIds: OriginEventId[]; spaceId?: string; start: string | number; end: string | number; @@ -61,11 +67,13 @@ interface GetGraphParams { export const getGraph = async ({ services: { esClient, logger }, - query: { eventIds, spaceId = 'default', start, end, esQuery }, + query: { originEventIds, spaceId = 'default', start, end, esQuery }, showUnknownTarget, nodesLimit, }: GetGraphParams): Promise> => { - logger.trace(`Fetching graph for [eventIds: ${eventIds.join(', ')}] in [spaceId: ${spaceId}]`); + logger.trace( + `Fetching graph for [originEventIds: ${originEventIds.join(', ')}] in [spaceId: ${spaceId}]` + ); const results = await fetchGraph({ esClient, @@ -73,7 +81,7 @@ export const getGraph = async ({ logger, start, end, - eventIds, + originEventIds, esQuery, }); @@ -132,7 +140,7 @@ const fetchGraph = async ({ logger, start, end, - eventIds, + originEventIds, showUnknownTarget, esQuery, }: { @@ -140,15 +148,21 @@ const fetchGraph = async ({ logger: Logger; start: string | number; end: string | number; - eventIds: string[]; + originEventIds: OriginEventId[]; showUnknownTarget: boolean; esQuery?: EsQuery; }): Promise> => { + const originAlertIds = originEventIds.filter((originEventId) => originEventId.isAlert); const query = `from logs-* | WHERE event.action IS NOT NULL AND actor.entity.id IS NOT NULL -| EVAL isAlert = ${ - eventIds.length > 0 - ? `event.id in (${eventIds.map((_id, idx) => `?al_id${idx}`).join(', ')})` +| EVAL isOrigin = ${ + originEventIds.length > 0 + ? `event.id in (${originEventIds.map((_id, idx) => `?og_id${idx}`).join(', ')})` + : 'false' + } +| EVAL isOriginAlert = isOrigin AND ${ + originAlertIds.length > 0 + ? `event.id in (${originAlertIds.map((_id, idx) => `?og_alrt_id${idx}`).join(', ')})` : 'false' } | STATS badge = COUNT(*), @@ -159,19 +173,26 @@ const fetchGraph = async ({ action = event.action, targetIds = target.entity.id, eventOutcome = event.outcome, - isAlert + isOrigin, + isOriginAlert | LIMIT 1000 -| SORT isAlert DESC`; +| SORT isOrigin DESC`; logger.trace(`Executing query [${query}]`); + const eventIds = originEventIds.map((originEventId) => originEventId.id); return await esClient.asCurrentUser.helpers .esql({ columnar: false, filter: buildDslFilter(eventIds, showUnknownTarget, start, end, esQuery), query, // @ts-ignore - types are not up to date - params: [...eventIds.map((id, idx) => ({ [`al_id${idx}`]: id }))], + params: [ + ...originEventIds.map((originEventId, idx) => ({ [`og_id${idx}`]: originEventId.id })), + ...originEventIds + .filter((originEventId) => originEventId.isAlert) + .map((originEventId, idx) => ({ [`og_alrt_id${idx}`]: originEventId.id })), + ], }) .toRecords(); }; @@ -238,7 +259,7 @@ const createNodes = (records: GraphEdge[], context: Omit ({ + acknowledged: true, +}); diff --git a/x-pack/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/exception_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/exception_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/exception_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/exception_list_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/exception_list_summary_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_summary_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/exception_list_summary_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/exception_list_summary_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/found_all_list_items_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_all_list_items_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_all_list_items_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/found_all_list_items_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/found_exception_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_exception_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_exception_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/found_exception_list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/found_exception_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_exception_list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_exception_list_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/found_exception_list_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/found_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/found_list_item_schema.mock.ts diff --git a/x-pack/solutions/security/plugins/lists/common/schemas/response/found_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_list_schema.mock.ts new file mode 100644 index 000000000000..1691221842d3 --- /dev/null +++ b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_list_schema.mock.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; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { FoundListSchema } from '@kbn/securitysolution-io-ts-list-types'; + +import { getListResponseMock } from './list_schema.mock'; + +export const getFoundListSchemaMock = (): FoundListSchema => ({ + cursor: '123', + data: [getListResponseMock()], + page: 1, + per_page: 1, + total: 1, +}); diff --git a/x-pack/plugins/lists/common/schemas/response/found_lists_by_size_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/found_lists_by_size_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/found_lists_by_size_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/found_lists_by_size_schema.mock.ts diff --git a/x-pack/solutions/security/plugins/lists/common/schemas/response/list_item_index_exist_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/list_item_index_exist_schema.mock.ts new file mode 100644 index 000000000000..afbb03cab870 --- /dev/null +++ b/x-pack/solutions/security/plugins/lists/common/schemas/response/list_item_index_exist_schema.mock.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { ListItemIndexExistSchema } from '@kbn/securitysolution-io-ts-list-types'; + +export const getListItemIndexExistSchemaResponseMock = (): ListItemIndexExistSchema => ({ + list_index: true, + list_item_index: true, +}); diff --git a/x-pack/plugins/lists/common/schemas/response/list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/list_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/list_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/response/search_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/response/search_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/response/search_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/response/search_list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/comment.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/comment.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/comment.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/comment.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/create_comment.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/create_comment.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/create_comment.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/create_comment.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entries.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entries.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entries.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entries.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_exists.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_exists.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_exists.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_exists.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_list.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_list.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_list.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_list.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_match.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_match.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_match_any.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match_any.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_match_any.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match_any.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_match_wildcard.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match_wildcard.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_match_wildcard.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_match_wildcard.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/entry_nested.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/entry_nested.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/entry_nested.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/entry_nested.mock.ts diff --git a/x-pack/plugins/lists/common/schemas/types/update_comment.mock.ts b/x-pack/solutions/security/plugins/lists/common/schemas/types/update_comment.mock.ts similarity index 100% rename from x-pack/plugins/lists/common/schemas/types/update_comment.mock.ts rename to x-pack/solutions/security/plugins/lists/common/schemas/types/update_comment.mock.ts diff --git a/x-pack/solutions/security/plugins/lists/jest.config.js b/x-pack/solutions/security/plugins/lists/jest.config.js new file mode 100644 index 000000000000..3bbf109f51ab --- /dev/null +++ b/x-pack/solutions/security/plugins/lists/jest.config.js @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +module.exports = { + collectCoverageFrom: [ + '/x-pack/solutions/security/plugins/lists/{common,public,server}/**/*.{ts,tsx}', + ], + coverageDirectory: + '/target/kibana-coverage/jest/x-pack/solutions/security/plugins/lists', + coverageReporters: ['text', 'html'], + preset: '@kbn/test', + rootDir: '../../../../..', + roots: ['/x-pack/solutions/security/plugins/lists'], +}; diff --git a/x-pack/plugins/lists/kibana.jsonc b/x-pack/solutions/security/plugins/lists/kibana.jsonc similarity index 100% rename from x-pack/plugins/lists/kibana.jsonc rename to x-pack/solutions/security/plugins/lists/kibana.jsonc diff --git a/x-pack/plugins/lists/public/common/empty_value.ts b/x-pack/solutions/security/plugins/lists/public/common/empty_value.ts similarity index 100% rename from x-pack/plugins/lists/public/common/empty_value.ts rename to x-pack/solutions/security/plugins/lists/public/common/empty_value.ts diff --git a/x-pack/plugins/lists/public/exceptions/api.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/api.test.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/api.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/api.test.ts diff --git a/x-pack/plugins/lists/public/exceptions/components/__mock__/show_value_list_modal.mock.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/__mock__/show_value_list_modal.mock.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/__mock__/show_value_list_modal.mock.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/__mock__/show_value_list_modal.mock.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.stories.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.stories.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.stories.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.stories.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/index.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/index.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/rounded_badge_antenna.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/and_or_badge/translations.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/translations.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/and_or_badge/translations.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/and_or_badge/translations.ts diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/and_badge.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/and_badge.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/and_badge.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/and_badge.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/and_badge.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/and_badge.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/and_badge.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/and_badge.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/builder.stories.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/builder.stories.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/builder.stories.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/builder.stories.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/entry_delete_button.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_delete_button.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/entry_delete_button.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_delete_button.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/entry_delete_button.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_delete_button.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/entry_delete_button.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_delete_button.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.stories.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.stories.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.stories.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.stories.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/entry_renderer.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/entry_renderer.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/exception_item_renderer.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_item_renderer.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/exception_item_renderer.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_item_renderer.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/exception_item_renderer.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_item_renderer.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/exception_item_renderer.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_item_renderer.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_items_renderer.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_items_renderer.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/helpers.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/helpers.test.ts similarity index 99% rename from x-pack/plugins/lists/public/exceptions/components/builder/helpers.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/helpers.test.ts index 2c0f8b198b38..c5afe22bb73c 100644 --- a/x-pack/plugins/lists/public/exceptions/components/builder/helpers.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/helpers.test.ts @@ -1669,7 +1669,7 @@ describe('Exception builder helpers', () => { }); describe('#filterExceptionItems', () => { - // Please see `x-pack/plugins/lists/public/exceptions/transforms.ts` doc notes + // Please see `x-pack/solutions/security/plugins/lists/public/exceptions/transforms.ts` doc notes // for context around the temporary `id` test('it correctly validates entries that include a temporary `id`', () => { const output: ExceptionsBuilderReturnExceptionItem[] = filterExceptionItems([ diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/index.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/index.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/index.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/index.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/logic_buttons.test.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/logic_buttons.test.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/logic_buttons.test.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/logic_buttons.test.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/logic_buttons.tsx b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/logic_buttons.tsx similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/logic_buttons.tsx rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/logic_buttons.tsx diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/reducer.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/reducer.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/reducer.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/reducer.ts diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/selectors.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/selectors.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/selectors.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/selectors.ts diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/translations.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/translations.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/components/builder/translations.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/components/builder/translations.ts diff --git a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts similarity index 96% rename from x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts index 95ca6285f0d7..029488f850d4 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts @@ -17,7 +17,7 @@ import { getExceptionListItemSchemaMock } from '../../../common/schemas/response const mockKibanaHttpService = coreMock.createStart().http; -// TODO: Port this test over to packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.test.ts once the other mocks are added to the kbn package system +// TODO: Port this test over to x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_item/index.test.ts once the other mocks are added to the kbn package system describe('usePersistExceptionItem', () => { let addExceptionListItemSpy: jest.SpyInstance>; diff --git a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts similarity index 95% rename from x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts index c27888b6d8cc..159426d71160 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts @@ -18,7 +18,7 @@ const mockKibanaHttpService = coreMock.createStart().http; jest.mock('@kbn/securitysolution-list-api'); -// TODO: Port this to the kbn package of: packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.test.ts once the kibana mocks are ported +// TODO: Port this to the kbn package of: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_persist_exception_list/index.test.ts once the kibana mocks are ported describe('usePersistExceptionList', () => { const onError = jest.fn(); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_api.test.ts similarity index 99% rename from x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_api.test.ts index a980261ba5f8..2ceaab63cc04 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_api.test.ts @@ -32,7 +32,7 @@ jest.mock('uuid', () => ({ const mockKibanaHttpService = coreMock.createStart().http; -// TODO: Once the mocks are figured out and the types are moved into kbn core this test should be moved next to the file: packages/kbn-securitysolution-list-hooks/src/use_api/index.test.ts +// TODO: Once the mocks are figured out and the types are moved into kbn core this test should be moved next to the file: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_api/index.test.ts describe('useApi', () => { const onErrorMock = jest.fn(); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts similarity index 97% rename from x-pack/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts index 6c684d199e53..db01cc54e855 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/exceptions/hooks/use_exception_lists.test.ts @@ -20,7 +20,7 @@ const mockKibanaHttpService = coreMock.createStart().http; const mockKibanaNotificationsService = coreMock.createStart().notifications; jest.mock('@kbn/securitysolution-list-api'); -// TODO: Move this test to the kbn package: packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.test.ts once mocks are ported over +// TODO: Move this test to the kbn package: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.test.ts once mocks are ported over describe('useExceptionLists', () => { beforeEach(() => { diff --git a/x-pack/plugins/lists/public/exceptions/transforms.test.ts b/x-pack/solutions/security/plugins/lists/public/exceptions/transforms.test.ts similarity index 100% rename from x-pack/plugins/lists/public/exceptions/transforms.test.ts rename to x-pack/solutions/security/plugins/lists/public/exceptions/transforms.test.ts diff --git a/x-pack/plugins/lists/public/index.ts b/x-pack/solutions/security/plugins/lists/public/index.ts similarity index 100% rename from x-pack/plugins/lists/public/index.ts rename to x-pack/solutions/security/plugins/lists/public/index.ts diff --git a/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_create_list_index.test.ts similarity index 93% rename from x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts rename to x-pack/solutions/security/plugins/lists/public/lists/hooks/use_create_list_index.test.ts index 7021d49940f2..806d8b633708 100644 --- a/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_create_list_index.test.ts @@ -15,7 +15,7 @@ import { createQueryWrapperMock } from '../mocks/query_wrapper'; jest.mock('@kbn/securitysolution-list-api'); -// TODO: This test should be ported to the package: packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.test.ts once we have mocks in kbn packages +// TODO: This test should be ported to the package: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_create_list_index/index.test.ts once we have mocks in kbn packages const { wrapper: queryWrapper, queryClient } = createQueryWrapperMock(); diff --git a/x-pack/plugins/lists/public/lists/hooks/use_delete_list.test.ts b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_delete_list.test.ts similarity index 86% rename from x-pack/plugins/lists/public/lists/hooks/use_delete_list.test.ts rename to x-pack/solutions/security/plugins/lists/public/lists/hooks/use_delete_list.test.ts index 7a339f3e12a4..72276e7c474d 100644 --- a/x-pack/plugins/lists/public/lists/hooks/use_delete_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_delete_list.test.ts @@ -14,7 +14,7 @@ import { getListResponseMock } from '../../../common/schemas/response/list_schem jest.mock('@kbn/securitysolution-list-api'); -// TODO: This test should be ported to the package: packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.test.ts once we have mocks in kbn packages +// TODO: This test should be ported to the package: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_delete_list/index.test.ts once we have mocks in kbn packages describe('useDeleteList', () => { let httpMock: ReturnType; diff --git a/x-pack/plugins/lists/public/lists/hooks/use_export_list.test.ts b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_export_list.test.ts similarity index 86% rename from x-pack/plugins/lists/public/lists/hooks/use_export_list.test.ts rename to x-pack/solutions/security/plugins/lists/public/lists/hooks/use_export_list.test.ts index 8f08ad5c8bd0..6cafd4958f7a 100644 --- a/x-pack/plugins/lists/public/lists/hooks/use_export_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_export_list.test.ts @@ -12,7 +12,7 @@ import { httpServiceMock } from '@kbn/core/public/mocks'; jest.mock('@kbn/securitysolution-list-api'); -// TODO: Move this test to the kbn package: packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts once Mocks are ported from Kibana +// TODO: Move this test to the kbn package: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_export_list/index.ts once Mocks are ported from Kibana describe('useExportList', () => { let httpMock: ReturnType; diff --git a/x-pack/plugins/lists/public/lists/hooks/use_import_list.test.ts b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_import_list.test.ts similarity index 94% rename from x-pack/plugins/lists/public/lists/hooks/use_import_list.test.ts rename to x-pack/solutions/security/plugins/lists/public/lists/hooks/use_import_list.test.ts index d56478a0321b..00a3a39f1f1a 100644 --- a/x-pack/plugins/lists/public/lists/hooks/use_import_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_import_list.test.ts @@ -14,7 +14,7 @@ import { getListResponseMock } from '../../../common/schemas/response/list_schem jest.mock('@kbn/securitysolution-list-api'); -// TODO: Port this test over to: packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts once mocks are moved to packages +// TODO: Port this test over to: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_import_list/index.ts once mocks are moved to packages describe('useImportList', () => { let httpMock: ReturnType; diff --git a/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_read_list_index.test.ts similarity index 91% rename from x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts rename to x-pack/solutions/security/plugins/lists/public/lists/hooks/use_read_list_index.test.ts index 643ac2df5b05..cd36b6d53106 100644 --- a/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts +++ b/x-pack/solutions/security/plugins/lists/public/lists/hooks/use_read_list_index.test.ts @@ -17,7 +17,7 @@ jest.mock('@kbn/securitysolution-list-api'); const { wrapper: queryWrapper } = createQueryWrapperMock(); -// TODO: Port this code over to the package: packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.test.ts once kibana has mocks in packages +// TODO: Port this code over to the package: x-pack/solutions/security/packages/kbn-securitysolution-list-hooks/src/use_read_list_index/index.test.ts once kibana has mocks in packages // FLAKY: https://github.com/elastic/kibana/issues/178026 describe.skip('useReadListIndex', () => { diff --git a/x-pack/plugins/lists/public/lists/mocks/query_wrapper.tsx b/x-pack/solutions/security/plugins/lists/public/lists/mocks/query_wrapper.tsx similarity index 100% rename from x-pack/plugins/lists/public/lists/mocks/query_wrapper.tsx rename to x-pack/solutions/security/plugins/lists/public/lists/mocks/query_wrapper.tsx diff --git a/x-pack/plugins/lists/public/lists/types.ts b/x-pack/solutions/security/plugins/lists/public/lists/types.ts similarity index 100% rename from x-pack/plugins/lists/public/lists/types.ts rename to x-pack/solutions/security/plugins/lists/public/lists/types.ts diff --git a/x-pack/plugins/lists/public/plugin.ts b/x-pack/solutions/security/plugins/lists/public/plugin.ts similarity index 100% rename from x-pack/plugins/lists/public/plugin.ts rename to x-pack/solutions/security/plugins/lists/public/plugin.ts diff --git a/x-pack/plugins/lists/public/shared_exports.ts b/x-pack/solutions/security/plugins/lists/public/shared_exports.ts similarity index 100% rename from x-pack/plugins/lists/public/shared_exports.ts rename to x-pack/solutions/security/plugins/lists/public/shared_exports.ts diff --git a/x-pack/plugins/lists/public/types.ts b/x-pack/solutions/security/plugins/lists/public/types.ts similarity index 100% rename from x-pack/plugins/lists/public/types.ts rename to x-pack/solutions/security/plugins/lists/public/types.ts diff --git a/x-pack/plugins/lists/scripts/storybook.js b/x-pack/solutions/security/plugins/lists/scripts/storybook.js similarity index 100% rename from x-pack/plugins/lists/scripts/storybook.js rename to x-pack/solutions/security/plugins/lists/scripts/storybook.js diff --git a/x-pack/plugins/lists/server/config.mock.ts b/x-pack/solutions/security/plugins/lists/server/config.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/config.mock.ts rename to x-pack/solutions/security/plugins/lists/server/config.mock.ts diff --git a/x-pack/plugins/lists/server/config.test.ts b/x-pack/solutions/security/plugins/lists/server/config.test.ts similarity index 100% rename from x-pack/plugins/lists/server/config.test.ts rename to x-pack/solutions/security/plugins/lists/server/config.test.ts diff --git a/x-pack/plugins/lists/server/config.ts b/x-pack/solutions/security/plugins/lists/server/config.ts similarity index 100% rename from x-pack/plugins/lists/server/config.ts rename to x-pack/solutions/security/plugins/lists/server/config.ts diff --git a/x-pack/plugins/lists/server/error_with_status_code.ts b/x-pack/solutions/security/plugins/lists/server/error_with_status_code.ts similarity index 100% rename from x-pack/plugins/lists/server/error_with_status_code.ts rename to x-pack/solutions/security/plugins/lists/server/error_with_status_code.ts diff --git a/x-pack/plugins/lists/server/get_space_id.test.ts b/x-pack/solutions/security/plugins/lists/server/get_space_id.test.ts similarity index 100% rename from x-pack/plugins/lists/server/get_space_id.test.ts rename to x-pack/solutions/security/plugins/lists/server/get_space_id.test.ts diff --git a/x-pack/plugins/lists/server/get_space_id.ts b/x-pack/solutions/security/plugins/lists/server/get_space_id.ts similarity index 100% rename from x-pack/plugins/lists/server/get_space_id.ts rename to x-pack/solutions/security/plugins/lists/server/get_space_id.ts diff --git a/x-pack/plugins/lists/server/get_user.test.ts b/x-pack/solutions/security/plugins/lists/server/get_user.test.ts similarity index 100% rename from x-pack/plugins/lists/server/get_user.test.ts rename to x-pack/solutions/security/plugins/lists/server/get_user.test.ts diff --git a/x-pack/plugins/lists/server/get_user.ts b/x-pack/solutions/security/plugins/lists/server/get_user.ts similarity index 100% rename from x-pack/plugins/lists/server/get_user.ts rename to x-pack/solutions/security/plugins/lists/server/get_user.ts diff --git a/x-pack/plugins/lists/server/handlers/create_exception_list_handler.ts b/x-pack/solutions/security/plugins/lists/server/handlers/create_exception_list_handler.ts similarity index 100% rename from x-pack/plugins/lists/server/handlers/create_exception_list_handler.ts rename to x-pack/solutions/security/plugins/lists/server/handlers/create_exception_list_handler.ts diff --git a/x-pack/plugins/lists/server/index.ts b/x-pack/solutions/security/plugins/lists/server/index.ts similarity index 100% rename from x-pack/plugins/lists/server/index.ts rename to x-pack/solutions/security/plugins/lists/server/index.ts diff --git a/x-pack/plugins/lists/server/mocks.ts b/x-pack/solutions/security/plugins/lists/server/mocks.ts similarity index 100% rename from x-pack/plugins/lists/server/mocks.ts rename to x-pack/solutions/security/plugins/lists/server/mocks.ts diff --git a/x-pack/plugins/lists/server/plugin.ts b/x-pack/solutions/security/plugins/lists/server/plugin.ts similarity index 100% rename from x-pack/plugins/lists/server/plugin.ts rename to x-pack/solutions/security/plugins/lists/server/plugin.ts diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/create_endpoint_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/create_endpoint_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/create_endpoint_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/create_endpoint_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/create_exception_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/create_exception_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/create_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/create_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/create_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/delete_endpoint_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/delete_endpoint_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/delete_exception_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/delete_exception_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/delete_exception_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/delete_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/delete_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/delete_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/delete_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/duplicate_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/duplicate_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/duplicate_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/duplicate_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts b/x-pack/solutions/security/plugins/lists/server/routes/endpoint_disallowed_fields.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts rename to x-pack/solutions/security/plugins/lists/server/routes/endpoint_disallowed_fields.ts diff --git a/x-pack/plugins/lists/server/routes/export_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/export_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/export_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/export_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/find_endpoint_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/find_endpoint_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/find_exception_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/find_exception_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/find_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/find_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/find_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/find_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/import_exceptions_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/import_exceptions_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/import_exceptions_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/import_exceptions_route.ts diff --git a/x-pack/plugins/lists/server/routes/index.ts b/x-pack/solutions/security/plugins/lists/server/routes/index.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/index.ts rename to x-pack/solutions/security/plugins/lists/server/routes/index.ts diff --git a/x-pack/plugins/lists/server/routes/init_routes.ts b/x-pack/solutions/security/plugins/lists/server/routes/init_routes.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/init_routes.ts rename to x-pack/solutions/security/plugins/lists/server/routes/init_routes.ts diff --git a/x-pack/plugins/lists/server/routes/internal/create_exception_filter_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/internal/create_exception_filter_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/internal/create_exception_filter_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/internal/create_exception_filter_route.ts diff --git a/x-pack/plugins/lists/server/routes/internal/create_exceptions_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/internal/create_exceptions_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/internal/create_exceptions_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/internal/create_exceptions_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/internal/find_lists_by_size_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/internal/find_lists_by_size_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/internal/find_lists_by_size_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/internal/find_lists_by_size_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/create_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/create_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/create_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/create_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/delete_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/delete_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/delete_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/delete_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/import_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/import_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/import_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/import_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/patch_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/patch_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/patch_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/patch_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/read_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/read_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/read_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/read_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list/update_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list/update_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list/update_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list/update_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_index/create_list_index_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_index/create_list_index_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_index/create_list_index_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_index/create_list_index_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_index/delete_list_index_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_index/delete_list_index_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_index/delete_list_index_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_index/delete_list_index_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_index/export_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_index/export_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_index/export_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_index/export_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_index/find_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_index/find_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_index/find_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_index/find_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_index/read_list_index_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_index/read_list_index_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_index/read_list_index_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_index/read_list_index_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/create_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/create_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/create_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/create_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/delete_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/delete_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/delete_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/delete_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/find_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/find_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/find_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/find_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/patch_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/patch_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/patch_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/patch_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/read_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/read_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/read_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/read_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_item/update_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_item/update_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_item/update_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_item/update_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/list_privileges/read_list_privileges_route.mock.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_privileges/read_list_privileges_route.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_privileges/read_list_privileges_route.mock.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_privileges/read_list_privileges_route.mock.ts diff --git a/x-pack/plugins/lists/server/routes/list_privileges/read_list_privileges_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/list_privileges/read_list_privileges_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/list_privileges/read_list_privileges_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/list_privileges/read_list_privileges_route.ts diff --git a/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/read_endpoint_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/read_endpoint_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/read_exception_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/read_exception_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/read_exception_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/read_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/read_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/read_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/read_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/summary_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/summary_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/summary_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/summary_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/update_endpoint_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/update_endpoint_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/update_exception_list_item_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/update_exception_list_item_route.ts diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_route.ts b/x-pack/solutions/security/plugins/lists/server/routes/update_exception_list_route.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/update_exception_list_route.ts rename to x-pack/solutions/security/plugins/lists/server/routes/update_exception_list_route.ts diff --git a/x-pack/plugins/lists/server/routes/utils/build_siem_response.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/build_siem_response.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/build_siem_response.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/build_siem_response.ts diff --git a/x-pack/plugins/lists/server/routes/utils/create_stream_from_buffer.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/create_stream_from_buffer.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/create_stream_from_buffer.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/create_stream_from_buffer.ts diff --git a/x-pack/plugins/lists/server/routes/utils/get_error_message_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/get_error_message_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/get_error_message_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/get_error_message_exception_list.ts diff --git a/x-pack/plugins/lists/server/routes/utils/get_error_message_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/get_error_message_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/get_error_message_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/get_error_message_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/get_exception_list_client.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/get_exception_list_client.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/get_exception_list_client.ts diff --git a/x-pack/plugins/lists/server/routes/utils/get_internal_list_client.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/get_internal_list_client.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/get_internal_list_client.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/get_internal_list_client.ts diff --git a/x-pack/plugins/lists/server/routes/utils/get_list_client.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/get_list_client.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/get_list_client.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/get_list_client.ts diff --git a/x-pack/plugins/lists/server/routes/utils/index.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/index.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/index.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/index.ts diff --git a/x-pack/plugins/lists/server/routes/utils/route_validation.test.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/route_validation.test.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/route_validation.test.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/route_validation.test.ts diff --git a/x-pack/plugins/lists/server/routes/utils/route_validation.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/route_validation.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/route_validation.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/route_validation.ts diff --git a/x-pack/plugins/lists/server/routes/utils/validate_comments_to_update.test.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/validate_comments_to_update.test.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/validate_comments_to_update.test.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/validate_comments_to_update.test.ts diff --git a/x-pack/plugins/lists/server/routes/utils/validate_comments_to_update.ts b/x-pack/solutions/security/plugins/lists/server/routes/utils/validate_comments_to_update.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/utils/validate_comments_to_update.ts rename to x-pack/solutions/security/plugins/lists/server/routes/utils/validate_comments_to_update.ts diff --git a/x-pack/plugins/lists/server/routes/validate.ts b/x-pack/solutions/security/plugins/lists/server/routes/validate.ts similarity index 100% rename from x-pack/plugins/lists/server/routes/validate.ts rename to x-pack/solutions/security/plugins/lists/server/routes/validate.ts diff --git a/x-pack/plugins/lists/server/saved_objects/exception_list.ts b/x-pack/solutions/security/plugins/lists/server/saved_objects/exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/saved_objects/exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/saved_objects/exception_list.ts diff --git a/x-pack/plugins/lists/server/saved_objects/index.ts b/x-pack/solutions/security/plugins/lists/server/saved_objects/index.ts similarity index 100% rename from x-pack/plugins/lists/server/saved_objects/index.ts rename to x-pack/solutions/security/plugins/lists/server/saved_objects/index.ts diff --git a/x-pack/plugins/lists/server/saved_objects/init_saved_objects.ts b/x-pack/solutions/security/plugins/lists/server/saved_objects/init_saved_objects.ts similarity index 100% rename from x-pack/plugins/lists/server/saved_objects/init_saved_objects.ts rename to x-pack/solutions/security/plugins/lists/server/saved_objects/init_saved_objects.ts diff --git a/x-pack/plugins/lists/server/saved_objects/migrations.test.ts b/x-pack/solutions/security/plugins/lists/server/saved_objects/migrations.test.ts similarity index 100% rename from x-pack/plugins/lists/server/saved_objects/migrations.test.ts rename to x-pack/solutions/security/plugins/lists/server/saved_objects/migrations.test.ts diff --git a/x-pack/plugins/lists/server/saved_objects/migrations.ts b/x-pack/solutions/security/plugins/lists/server/saved_objects/migrations.ts similarity index 100% rename from x-pack/plugins/lists/server/saved_objects/migrations.ts rename to x-pack/solutions/security/plugins/lists/server/saved_objects/migrations.ts diff --git a/x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts diff --git a/x-pack/plugins/lists/server/schemas/common/schemas.test.ts b/x-pack/solutions/security/plugins/lists/server/schemas/common/schemas.test.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/common/schemas.test.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/common/schemas.test.ts diff --git a/x-pack/plugins/lists/server/schemas/common/schemas.ts b/x-pack/solutions/security/plugins/lists/server/schemas/common/schemas.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/common/schemas.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/common/schemas.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/create_es_bulk_type.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/create_es_bulk_type.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/create_es_bulk_type.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/create_es_bulk_type.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/index.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_item_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_schema.mock.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/update_es_list_item_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/update_es_list_item_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/update_es_list_item_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/update_es_list_item_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/update_es_list_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/update_es_list_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_query/update_es_list_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_query/update_es_list_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/index.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/index.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/index.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/index.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.test.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.test.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.test.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.test.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.test.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.test.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.test.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.test.ts diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts b/x-pack/solutions/security/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts diff --git a/x-pack/plugins/lists/server/schemas/saved_objects/index.ts b/x-pack/solutions/security/plugins/lists/server/schemas/saved_objects/index.ts similarity index 100% rename from x-pack/plugins/lists/server/schemas/saved_objects/index.ts rename to x-pack/solutions/security/plugins/lists/server/schemas/saved_objects/index.ts diff --git a/x-pack/plugins/lists/server/scripts/check_env_variables.sh b/x-pack/solutions/security/plugins/lists/server/scripts/check_env_variables.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/check_env_variables.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/check_env_variables.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_all_exception_lists.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_all_exception_lists.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_endpoint_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_endpoint_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_exception_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_exception_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_exception_list_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_exception_list_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_exception_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_exception_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_exception_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_exception_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_exception_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_list.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_list_index.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_list_index.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_list_index.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_list_index.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/delete_list_item_by_value.sh b/x-pack/solutions/security/plugins/lists/server/scripts/delete_list_item_by_value.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/delete_list_item_by_value.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/delete_list_item_by_value.sh diff --git a/x-pack/plugins/lists/server/scripts/download_load_lists_example.sh b/x-pack/solutions/security/plugins/lists/server/scripts/download_load_lists_example.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/download_load_lists_example.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/download_load_lists_example.sh diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/files/import.ndjson b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/files/import.ndjson similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/files/import.ndjson rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/files/import.ndjson diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_agnostic.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_agnostic.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_agnostic.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_agnostic.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_auto_id.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_auto_id.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_auto_id.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_auto_id.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_agnostic.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_agnostic.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_agnostic.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_agnostic.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_1.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_1.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_1.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_1.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_2_agnostic.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_2_agnostic.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_2_agnostic.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_2_agnostic.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_3.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_3.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_3.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_detection_3.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_multi_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_multi_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_multi_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_multi_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_non_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_non_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_non_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_1_non_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_multi_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_multi_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_multi_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_multi_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_non_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_non_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_non_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_2_non_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_non_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_non_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_non_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_non_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_single_value_list.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_single_value_list.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_single_value_list.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/references/exception_list_item_3_single_value_list.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/trusted_app_list_item_agnostic.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/trusted_app_list_item_agnostic.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/new/trusted_app_list_item_agnostic.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/new/trusted_app_list_item_agnostic.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_agnostic.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update_agnostic.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_agnostic.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update_agnostic.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json diff --git a/x-pack/plugins/lists/server/scripts/export_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/export_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/export_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/export_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh b/x-pack/solutions/security/plugins/lists/server/scripts/export_list_items_to_file.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/export_list_items_to_file.sh diff --git a/x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_endpoint_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_endpoint_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/find_exception_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_exception_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_exception_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_exception_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh diff --git a/x-pack/plugins/lists/server/scripts/find_exception_lists.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_exception_lists.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_exception_lists.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_exception_lists.sh diff --git a/x-pack/plugins/lists/server/scripts/find_exception_lists_by_filter.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_exception_lists_by_filter.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_exception_lists_by_filter.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_exception_lists_by_filter.sh diff --git a/x-pack/plugins/lists/server/scripts/find_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_cursor.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_cursor.sh diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_sort.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_sort.sh diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh diff --git a/x-pack/plugins/lists/server/scripts/find_lists.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_lists.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_lists.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_lists.sh diff --git a/x-pack/plugins/lists/server/scripts/find_lists_with_cursor.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_cursor.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_lists_with_cursor.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_cursor.sh diff --git a/x-pack/plugins/lists/server/scripts/find_lists_with_filter.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_filter.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_lists_with_filter.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_filter.sh diff --git a/x-pack/plugins/lists/server/scripts/find_lists_with_sort.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_sort.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_lists_with_sort.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_sort.sh diff --git a/x-pack/plugins/lists/server/scripts/find_lists_with_sort_cursor.sh b/x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_sort_cursor.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/find_lists_with_sort_cursor.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/find_lists_with_sort_cursor.sh diff --git a/x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_endpoint_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_endpoint_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/get_exception_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_exception_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list.sh diff --git a/x-pack/plugins/lists/server/scripts/get_exception_list_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_exception_list_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/get_exception_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_exception_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/get_exception_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_exception_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_exception_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/get_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_list.sh diff --git a/x-pack/plugins/lists/server/scripts/get_list_item_by_id.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_list_item_by_id.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_list_item_by_id.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_list_item_by_id.sh diff --git a/x-pack/plugins/lists/server/scripts/get_list_item_by_value.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_list_item_by_value.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_list_item_by_value.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_list_item_by_value.sh diff --git a/x-pack/plugins/lists/server/scripts/get_privileges.sh b/x-pack/solutions/security/plugins/lists/server/scripts/get_privileges.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/get_privileges.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/get_privileges.sh diff --git a/x-pack/plugins/lists/server/scripts/hard_reset.sh b/x-pack/solutions/security/plugins/lists/server/scripts/hard_reset.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/hard_reset.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/hard_reset.sh diff --git a/x-pack/plugins/lists/server/scripts/import_exception_lists.sh b/x-pack/solutions/security/plugins/lists/server/scripts/import_exception_lists.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/import_exception_lists.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/import_exception_lists.sh diff --git a/x-pack/plugins/lists/server/scripts/import_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/import_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/import_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/import_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/import_list_items_by_filename.sh b/x-pack/solutions/security/plugins/lists/server/scripts/import_list_items_by_filename.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/import_list_items_by_filename.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/import_list_items_by_filename.sh diff --git a/x-pack/plugins/lists/server/scripts/lists/files/binary.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/binary.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/binary.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/binary.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/boolean.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/boolean.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/boolean.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/boolean.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/byte.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/byte.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/byte.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/byte.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/date.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/date.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/date_nanos.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_nanos.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/date_nanos.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_nanos.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/date_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/date_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/date_range_custom_format.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_range_custom_format.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/date_range_custom_format.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/date_range_custom_format.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/double.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/double.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/double.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/double.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/double_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/double_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/double_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/double_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/float.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/float.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/float.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/float.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/float_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/float_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/float_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/float_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/geo_hash.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_hash.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/geo_hash.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_hash.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/geo_point.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_point.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/geo_point.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_point.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/geo_point_wkt.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_point_wkt.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/geo_point_wkt.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/geo_point_wkt.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/half_float.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/half_float.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/half_float.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/half_float.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/hosts.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/hosts.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/hosts.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/hosts.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/integer.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/integer.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/integer.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/integer.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/integer_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/integer_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/integer_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/integer_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/ip_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/ip_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/ip_range_cidr.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range_cidr.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/ip_range_cidr.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range_cidr.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/ip_range_mixed.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range_mixed.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/ip_range_mixed.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ip_range_mixed.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/ips.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ips.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/ips.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/ips.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/long.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/long.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/long.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/long.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/long_range.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/long_range.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/long_range.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/long_range.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/short.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/short.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/short.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/short.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/files/text.txt b/x-pack/solutions/security/plugins/lists/server/scripts/lists/files/text.txt similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/files/text.txt rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/files/text.txt diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/binary_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/binary_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/binary_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/binary_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/boolean_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/boolean_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/boolean_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/boolean_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/byte_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/byte_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/byte_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/byte_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/date_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/date_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/date_nanos_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_nanos_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/date_nanos_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_nanos_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/date_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/date_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/date_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/double_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/double_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/double_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/double_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/double_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/double_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/double_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/double_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/float_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/float_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/float_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/float_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/float_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/float_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/float_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/float_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/geo_point_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/geo_point_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/geo_point_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/geo_point_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/geo_shape_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/geo_shape_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/geo_shape_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/geo_shape_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/half_float_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/half_float_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/half_float_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/half_float_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/integer_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/integer_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/integer_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/integer_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/integer_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/integer_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/integer_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/integer_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item_everything.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_item_everything.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/ip_item_everything.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_item_everything.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/ip_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/ip_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/ip_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/keyword_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/keyword_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/long_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/long_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/long_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/long_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/long_range_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/long_range_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/long_range_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/long_range_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/shape_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/shape_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/shape_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/shape_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/short_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/short_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/short_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/short_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/text_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/text_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/items/text_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/items/text_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/list_ip_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/list_ip_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/list_keyword_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/list_keyword_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/list_keyword_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/list_keyword_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/auto_id.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/auto_id.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/auto_id.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/auto_id.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/binary.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/binary.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/binary.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/binary.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/boolean.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/boolean.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/boolean.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/boolean.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/byte.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/byte.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/byte.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/byte.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/date.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/date.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/date_nanos.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_nanos.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/date_nanos.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_nanos.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/date_range.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_range.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/date_range.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_range.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/date_range_custom_format.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_range_custom_format.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/date_range_custom_format.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/date_range_custom_format.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/double.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/double.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/double.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/double.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/double_range.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/double_range.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/double_range.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/double_range.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/everything.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/everything.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/everything.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/everything.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/float.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/float.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/float.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/float.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/float_range.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/float_range.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/float_range.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/float_range.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/geo_point.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/geo_point.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/geo_point.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/geo_point.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/geo_shape.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/geo_shape.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/geo_shape.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/geo_shape.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/half_float.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/half_float.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/half_float.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/half_float.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/integer.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/integer.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/integer.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/integer.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/integer_range.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/integer_range.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/integer_range.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/integer_range.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/ip.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/ip.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/ip_custom_format.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_custom_format.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/ip_custom_format.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_custom_format.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/ip_no_id.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_no_id.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/ip_no_id.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_no_id.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/ip_range.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_range.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/ip_range.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/ip_range.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/keyword.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/keyword.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/keyword.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/keyword.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/keyword_custom_format.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/keyword_custom_format.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/keyword_custom_format.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/keyword_custom_format.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/long.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/long.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/long.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/long.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/shape.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/shape.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/shape.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/shape.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/short.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/short.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/short.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/short.json diff --git a/x-pack/plugins/lists/server/scripts/lists/new/lists/text.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/text.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/new/lists/text.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/new/lists/text.json diff --git a/x-pack/plugins/lists/server/scripts/lists/patches/ip_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/patches/ip_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/patches/ip_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/patches/ip_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/patches/simplest_updated_name.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/patches/simplest_updated_name.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/patches/simplest_updated_name.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/patches/simplest_updated_name.json diff --git a/x-pack/plugins/lists/server/scripts/lists/updates/ip_item.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/updates/ip_item.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/updates/ip_item.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/updates/ip_item.json diff --git a/x-pack/plugins/lists/server/scripts/lists/updates/simple_update.json b/x-pack/solutions/security/plugins/lists/server/scripts/lists/updates/simple_update.json similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists/updates/simple_update.json rename to x-pack/solutions/security/plugins/lists/server/scripts/lists/updates/simple_update.json diff --git a/x-pack/plugins/lists/server/scripts/lists_index_exists.sh b/x-pack/solutions/security/plugins/lists/server/scripts/lists_index_exists.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/lists_index_exists.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/lists_index_exists.sh diff --git a/x-pack/plugins/lists/server/scripts/patch_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/patch_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/patch_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/patch_list.sh diff --git a/x-pack/plugins/lists/server/scripts/patch_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/patch_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/patch_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/patch_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/post_endpoint_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_endpoint_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_endpoint_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_endpoint_list.sh diff --git a/x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_endpoint_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_endpoint_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/post_exception_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_exception_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_exception_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_exception_list.sh diff --git a/x-pack/plugins/lists/server/scripts/post_exception_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_exception_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_exception_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_exception_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/post_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_list.sh diff --git a/x-pack/plugins/lists/server/scripts/post_list_index.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_list_index.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_list_index.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_list_index.sh diff --git a/x-pack/plugins/lists/server/scripts/post_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/post_x_exception_list_items.sh b/x-pack/solutions/security/plugins/lists/server/scripts/post_x_exception_list_items.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/post_x_exception_list_items.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/post_x_exception_list_items.sh diff --git a/x-pack/plugins/lists/server/scripts/quick_start.sh b/x-pack/solutions/security/plugins/lists/server/scripts/quick_start.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/quick_start.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/quick_start.sh diff --git a/x-pack/plugins/lists/server/scripts/quick_start_value_list_references.sh b/x-pack/solutions/security/plugins/lists/server/scripts/quick_start_value_list_references.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/quick_start_value_list_references.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/quick_start_value_list_references.sh diff --git a/x-pack/plugins/lists/server/scripts/summary_exception_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/summary_exception_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/summary_exception_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/summary_exception_list.sh diff --git a/x-pack/plugins/lists/server/scripts/update_endpoint_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/update_endpoint_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/update_endpoint_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/update_endpoint_item.sh diff --git a/x-pack/plugins/lists/server/scripts/update_exception_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/update_exception_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/update_exception_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/update_exception_list.sh diff --git a/x-pack/plugins/lists/server/scripts/update_exception_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/update_exception_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/update_exception_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/update_exception_list_item.sh diff --git a/x-pack/plugins/lists/server/scripts/update_list.sh b/x-pack/solutions/security/plugins/lists/server/scripts/update_list.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/update_list.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/update_list.sh diff --git a/x-pack/plugins/lists/server/scripts/update_list_item.sh b/x-pack/solutions/security/plugins/lists/server/scripts/update_list_item.sh similarity index 100% rename from x-pack/plugins/lists/server/scripts/update_list_item.sh rename to x-pack/solutions/security/plugins/lists/server/scripts/update_list_item.sh diff --git a/x-pack/plugins/lists/server/services/exception_lists/build_exception_filter.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/build_exception_filter.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/build_exception_filter.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/build_exception_filter.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/bulk_create_exception_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/bulk_create_exception_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/bulk_create_exception_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/bulk_create_exception_list_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/close_point_in_time.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/close_point_in_time.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/close_point_in_time.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/close_point_in_time.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_endpoint_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_endpoint_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/create_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/delete_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/duplicate_exception_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/duplicate_exception_list.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/duplicate_exception_list.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/duplicate_exception_list.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/duplicate_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/duplicate_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/duplicate_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/duplicate_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/exception_list_client.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.mock.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/exception_list_client.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client_types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/exception_list_client_types.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/export_exception_list_and_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/export_exception_list_and_items.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item_point_in_time_finder.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_item_point_in_time_finder.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item_point_in_time_finder.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_item_point_in_time_finder.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_summary.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_summary.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/import_exception_list_and_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/import_exception_list_and_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/import_exception_list_and_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/import_exception_list_and_items.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/import_exception_list_and_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/import_exception_list_and_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/import_exception_list_and_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/import_exception_list_and_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/index.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/index.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/open_point_in_time.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/open_point_in_time.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/open_point_in_time.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/open_point_in_time.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_exception_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_exception_list.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_overwrite_exception_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_overwrite_exception_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/update_overwrite_exception_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/update_overwrite_exception_list_item.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/errors.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/errors.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/errors.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/errors.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_list_filter.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/get_exception_lists_item_filter.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_create_imported_lists.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/bulk_update_imported_lists.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/create_exceptions_stream_logic.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/dedupe_incoming_lists.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/delete_list_items_to_overwrite.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/import_exception_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/import_exception_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/import_exception_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/import_exception_list_items.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/import_exception_lists.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/import_exception_lists.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/import_exception_lists.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/import_exception_lists.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/is_import_regular.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_or_update.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_or_update.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_or_update.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_or_update.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_update.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_update.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_update.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_items_to_create_update.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_or_update.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_or_update.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_or_update.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_or_update.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_update.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_update.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_update.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_exception_lists_to_create_update.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_by_namespace.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/import/sort_import_responses.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/index.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/index.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/index.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/index.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/index.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/index.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/validate_data.test.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/validate_data.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/validate_data.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/validate_data.test.ts diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/validate_data.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/validate_data.ts similarity index 100% rename from x-pack/plugins/lists/server/services/exception_lists/utils/validate_data.ts rename to x-pack/solutions/security/plugins/lists/server/services/exception_lists/utils/validate_data.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/errors.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/errors.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/errors.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/errors.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/extension_point_storage.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/extension_point_storage.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.mock.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/extension_point_storage.test.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/extension_point_storage.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.test.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/extension_point_storage.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/extension_point_storage.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/extension_point_storage_client.test.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage_client.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/extension_point_storage_client.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage_client.test.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/extension_point_storage_client.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage_client.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/extension_point_storage_client.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/extension_point_storage_client.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/index.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/index.ts diff --git a/x-pack/plugins/lists/server/services/extension_points/types.ts b/x-pack/solutions/security/plugins/lists/server/services/extension_points/types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/extension_points/types.ts rename to x-pack/solutions/security/plugins/lists/server/services/extension_points/types.ts diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/buffer_lines.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/buffer_lines.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/buffer_lines.test.ts diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.ts b/x-pack/solutions/security/plugins/lists/server/services/items/buffer_lines.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/buffer_lines.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/buffer_lines.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_item.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_item.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_item.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_items_bulk.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_items_bulk.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_items_bulk.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_items_bulk.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.test.ts diff --git a/x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts b/x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/create_list_items_bulk.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item_by_value.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item_by_value.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts diff --git a/x-pack/plugins/lists/server/services/items/find_all_list_items.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_all_list_items.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/find_all_list_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_all_list_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.test.ts diff --git a/x-pack/plugins/lists/server/services/items/find_all_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_all_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_list_item.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/find_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_value.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_value.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_value.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_value.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.test.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_value.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_value.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_value.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_values.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.test.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_index.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_index.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_index.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_index.test.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_index.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_index.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_index.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_template.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_template.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_template.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_template.test.ts diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_template.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_template.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/get_list_item_template.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_template.ts diff --git a/x-pack/plugins/lists/server/services/items/index.ts b/x-pack/solutions/security/plugins/lists/server/services/items/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/index.ts diff --git a/x-pack/plugins/lists/server/services/items/list_item_mappings.json b/x-pack/solutions/security/plugins/lists/server/services/items/list_item_mappings.json similarity index 100% rename from x-pack/plugins/lists/server/services/items/list_item_mappings.json rename to x-pack/solutions/security/plugins/lists/server/services/items/list_item_mappings.json diff --git a/x-pack/plugins/lists/server/services/items/list_item_policy.json b/x-pack/solutions/security/plugins/lists/server/services/items/list_item_policy.json similarity index 100% rename from x-pack/plugins/lists/server/services/items/list_item_policy.json rename to x-pack/solutions/security/plugins/lists/server/services/items/list_item_policy.json diff --git a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/search_list_item_by_values.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.test.ts diff --git a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts b/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts diff --git a/x-pack/plugins/lists/server/services/items/test_readable.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/test_readable.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/test_readable.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/test_readable.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/update_list_item.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/update_list_item.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/update_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/update_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/items/update_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/update_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/update_list_item.ts diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.mock.ts diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.test.ts diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_streams.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_streams.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/items/write_list_items_to_streams.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_streams.mock.ts diff --git a/x-pack/plugins/lists/server/services/lists/create_list.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/create_list.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/create_list.mock.ts diff --git a/x-pack/plugins/lists/server/services/lists/create_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/create_list.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/create_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/create_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts diff --git a/x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts diff --git a/x-pack/plugins/lists/server/services/lists/delete_list.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/delete_list.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.mock.ts diff --git a/x-pack/plugins/lists/server/services/lists/delete_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/delete_list.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/delete_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/delete_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts diff --git a/x-pack/plugins/lists/server/services/lists/find_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/find_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list_index.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list_index.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list_index.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list_index.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list_index.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list_index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list_index.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list_index.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list_template.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list_template.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list_template.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list_template.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/get_list_template.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list_template.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/get_list_template.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/get_list_template.ts diff --git a/x-pack/plugins/lists/server/services/lists/index.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/index.ts diff --git a/x-pack/plugins/lists/server/services/lists/list_client.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/list_client.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_client.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_client.mock.ts diff --git a/x-pack/plugins/lists/server/services/lists/list_client.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/list_client.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_client.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_client.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/list_client.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/list_client.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_client.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_client.ts diff --git a/x-pack/plugins/lists/server/services/lists/list_client_types.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/list_client_types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_client_types.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_client_types.ts diff --git a/x-pack/plugins/lists/server/services/lists/list_mappings.json b/x-pack/solutions/security/plugins/lists/server/services/lists/list_mappings.json similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_mappings.json rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_mappings.json diff --git a/x-pack/plugins/lists/server/services/lists/list_policy.json b/x-pack/solutions/security/plugins/lists/server/services/lists/list_policy.json similarity index 100% rename from x-pack/plugins/lists/server/services/lists/list_policy.json rename to x-pack/solutions/security/plugins/lists/server/services/lists/list_policy.json diff --git a/x-pack/plugins/lists/server/services/lists/types.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/types.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/types.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/types.ts diff --git a/x-pack/plugins/lists/server/services/lists/update_list.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/update_list.mock.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/update_list.mock.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/update_list.mock.ts diff --git a/x-pack/plugins/lists/server/services/lists/update_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/update_list.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/update_list.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/update_list.test.ts diff --git a/x-pack/plugins/lists/server/services/lists/update_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/update_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/lists/update_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/lists/update_list.ts diff --git a/x-pack/plugins/lists/server/services/utils/calculate_scroll_math.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/calculate_scroll_math.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/calculate_scroll_math.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/calculate_scroll_math.ts diff --git a/x-pack/plugins/lists/server/services/utils/check_version_conflict.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/check_version_conflict.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/check_version_conflict.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/check_version_conflict.ts diff --git a/x-pack/plugins/lists/server/services/utils/encode_decode_cursor.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/encode_decode_cursor.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/encode_decode_cursor.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/encode_decode_cursor.ts diff --git a/x-pack/plugins/lists/server/services/utils/escape_query.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/escape_query.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/escape_query.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/escape_query.ts diff --git a/x-pack/plugins/lists/server/services/utils/find_source_type.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/find_source_type.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/find_source_type.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/find_source_type.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/find_source_type.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/find_source_type.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/find_source_type.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/find_source_type.ts diff --git a/x-pack/plugins/lists/server/services/utils/find_source_value.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/find_source_value.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/find_source_value.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/find_source_value.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/find_source_value.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/find_source_value.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/find_source_value.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/find_source_value.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_query_filter.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_query_filter.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_query_filter.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_query_filter.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts diff --git a/x-pack/plugins/lists/server/services/utils/get_source_with_tie_breaker.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_source_with_tie_breaker.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/get_source_with_tie_breaker.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/get_source_with_tie_breaker.ts diff --git a/x-pack/plugins/lists/server/services/utils/index.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/index.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/index.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/index.ts diff --git a/x-pack/plugins/lists/server/services/utils/scroll_to_start_page.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/scroll_to_start_page.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/scroll_to_start_page.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/scroll_to_start_page.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.test.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.test.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.test.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.test.ts diff --git a/x-pack/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/transform_list_item_to_elastic_query.ts diff --git a/x-pack/plugins/lists/server/services/utils/wait_until_document_indexed.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/wait_until_document_indexed.ts similarity index 100% rename from x-pack/plugins/lists/server/services/utils/wait_until_document_indexed.ts rename to x-pack/solutions/security/plugins/lists/server/services/utils/wait_until_document_indexed.ts diff --git a/x-pack/plugins/lists/server/types.ts b/x-pack/solutions/security/plugins/lists/server/types.ts similarity index 100% rename from x-pack/plugins/lists/server/types.ts rename to x-pack/solutions/security/plugins/lists/server/types.ts diff --git a/x-pack/solutions/security/plugins/lists/tsconfig.json b/x-pack/solutions/security/plugins/lists/tsconfig.json new file mode 100644 index 000000000000..c0f751d665ee --- /dev/null +++ b/x-pack/solutions/security/plugins/lists/tsconfig.json @@ -0,0 +1,50 @@ +{ + "extends": "../../../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types" + }, + "include": [ + "common/**/*", + "public/**/*", + "server/**/*", + // have to declare *.json explicitly due to https://github.com/microsoft/TypeScript/issues/25636 + "server/**/*.json" + ], + "kbn_references": [ + "@kbn/core", + "@kbn/spaces-plugin", + "@kbn/security-plugin", + "@kbn/unified-search-plugin", + "@kbn/securitysolution-io-ts-list-types", + "@kbn/securitysolution-list-constants", + "@kbn/securitysolution-list-hooks", + "@kbn/securitysolution-list-api", + "@kbn/securitysolution-lists-common", + "@kbn/securitysolution-exceptions-common", + "@kbn/securitysolution-endpoint-exceptions-common", + "@kbn/kibana-react-plugin", + "@kbn/i18n", + "@kbn/data-plugin", + "@kbn/securitysolution-list-utils", + "@kbn/securitysolution-utils", + "@kbn/es-query", + "@kbn/i18n-react", + "@kbn/securitysolution-autocomplete", + "@kbn/config-schema", + "@kbn/securitysolution-io-ts-utils", + "@kbn/core-http-server", + "@kbn/securitysolution-es-utils", + "@kbn/securitysolution-io-ts-types", + "@kbn/std", + "@kbn/utils", + "@kbn/logging-mocks", + "@kbn/utility-types", + "@kbn/core-elasticsearch-client-server-mocks", + "@kbn/core-saved-objects-server", + "@kbn/zod-helpers", + "@kbn/core-security-server", + "@kbn/core-http-server-mocks", + "@kbn/core-http-server-utils" + ], + "exclude": ["target/**/*"] +} diff --git a/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/common/response_actions.ts b/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/common/response_actions.ts index 56b1fafdb5a7..3a765e0c8313 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/common/response_actions.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/common/response_actions.ts @@ -17,6 +17,7 @@ import { GetProcessesRouteRequestSchema } from '../response_actions/running_proc import { KillProcessRouteRequestSchema } from '../response_actions/kill_process'; import { SuspendProcessRouteRequestSchema } from '../response_actions/suspend_process'; import { UploadActionRequestSchema } from '../response_actions/upload'; +import { RunScriptActionRequestSchema } from '../response_actions/run_script'; export const ResponseActionBodySchema = schema.oneOf([ IsolateRouteRequestSchema.body, @@ -28,6 +29,7 @@ export const ResponseActionBodySchema = schema.oneOf([ ExecuteActionRequestSchema.body, UploadActionRequestSchema.body, ScanActionRequestSchema.body, + RunScriptActionRequestSchema.body, ]); export type ResponseActionsRequestBody = TypeOf; diff --git a/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/response_actions/run_script/run_script.ts b/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/response_actions/run_script/run_script.ts index dfa88941b34e..95c035e86688 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/response_actions/run_script/run_script.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/api/endpoint/actions/response_actions/run_script/run_script.ts @@ -26,27 +26,27 @@ export const RunScriptActionRequestSchema = { /** * The script to run */ - Raw: schema.maybe(NonEmptyString), + raw: schema.maybe(NonEmptyString), /** * The path to the script on the host to run */ - HostPath: schema.maybe(NonEmptyString), + hostPath: schema.maybe(NonEmptyString), /** * The path to the script in the cloud to run */ - CloudFile: schema.maybe(NonEmptyString), + cloudFile: schema.maybe(NonEmptyString), /** * The command line to run */ - CommandLine: schema.maybe(NonEmptyString), + commandLine: schema.maybe(NonEmptyString), /** * The max timeout value before the command is killed. Number represents milliseconds */ - Timeout: schema.maybe(schema.number({ min: 1 })), + timeout: schema.maybe(schema.number({ min: 1 })), }, { validate: (params) => { - if (!params.Raw && !params.HostPath && !params.CloudFile) { + if (!params.raw && !params.hostPath && !params.cloudFile) { return 'At least one of Raw, HostPath, or CloudFile must be provided'; } }, diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/service/response_actions/type_guards.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/service/response_actions/type_guards.ts index 707be0a4d1e6..ece0a9501e3f 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/service/response_actions/type_guards.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/service/response_actions/type_guards.ts @@ -15,6 +15,8 @@ import type { ResponseActionUploadOutputContent, ResponseActionUploadParameters, GetProcessesActionOutputContent, + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters, } from '../../types'; import { RESPONSE_ACTION_AGENT_TYPE, RESPONSE_ACTION_TYPE } from './constants'; @@ -47,6 +49,15 @@ export const isProcessesAction = ( return action.command === 'running-processes'; }; +export const isRunScriptAction = ( + action: MaybeImmutable +): action is ActionDetails< + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters +> => { + return action.command === 'runscript'; +}; + // type guards to ensure only the matching string values are attached to the types filter type export const isAgentType = (type: string): type is (typeof RESPONSE_ACTION_AGENT_TYPE)[number] => RESPONSE_ACTION_AGENT_TYPE.includes(type as (typeof RESPONSE_ACTION_AGENT_TYPE)[number]); diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/types/actions.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/types/actions.ts index 131a8d0c6df5..e3c47102ce71 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/types/actions.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/types/actions.ts @@ -97,7 +97,8 @@ export interface ResponseActionScanOutputContent { } export interface ResponseActionRunScriptOutputContent { - output: string; + stdout: string; + stderr: string; code: string; } diff --git a/x-pack/solutions/security/plugins/security_solution/common/experimental_features.ts b/x-pack/solutions/security/plugins/security_solution/common/experimental_features.ts index 428a48cf4b7b..56f4657500c4 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/experimental_features.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/experimental_features.ts @@ -109,11 +109,6 @@ export const allowedExperimentalValues = Object.freeze({ */ securitySolutionNotesDisabled: false, - /** - * Disables entity and alert previews - */ - entityAlertPreviewDisabled: false, - /** * Enables the Assistant Model Evaluation advanced setting and API endpoint, introduced in `8.11.0`. */ @@ -266,8 +261,12 @@ export const allowedExperimentalValues = Object.freeze({ /** * Enables CrowdStrike's RunScript RTR command */ - crowdstrikeRunScriptEnabled: false, + + /** + * Enables the Asset Inventory feature + */ + assetInventoryStoreEnabled: false, }); type ExperimentalConfigKeys = Array; diff --git a/x-pack/solutions/security/plugins/security_solution/docs/openapi/README.md b/x-pack/solutions/security/plugins/security_solution/docs/openapi/README.md index 4c3b55c8ab23..3cbe1c1f4233 100644 --- a/x-pack/solutions/security/plugins/security_solution/docs/openapi/README.md +++ b/x-pack/solutions/security/plugins/security_solution/docs/openapi/README.md @@ -32,8 +32,8 @@ Security Solution has multiple API domains scattered across Kibana. Currently th - Security Endpoint Exceptions - - Bundling script: `packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js` - - Bundles location: `packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/{ess|serverless}` + - Bundling script: `x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/scripts/openapi_bundle.js` + - Bundles location: `x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common/docs/openapi/{ess|serverless}` - Security Endpoint Management @@ -47,13 +47,13 @@ Security Solution has multiple API domains scattered across Kibana. Currently th - Security Security Exceptions - - Bundling script: `packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js` - - Bundles location: `packages/kbn-securitysolution-exceptions-common/docs/openapi/{ess|serverless}` + - Bundling script: `x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/scripts/openapi_bundle.js` + - Bundles location: `x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common/docs/openapi/{ess|serverless}` - Security Lists - - Bundling script: `packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js` - - Bundles location: `packages/kbn-securitysolution-lists-common/docs/openapi/{ess|serverless}` + - Bundling script: `x-pack/solutions/security/packages/kbn-securitysolution-lists-common/scripts/openapi_bundle.js` + - Bundles location: `x-pack/solutions/security/packages/kbn-securitysolution-lists-common/docs/openapi/{ess|serverless}` - Security Osquery diff --git a/x-pack/solutions/security/plugins/security_solution/public/app/actions/copy_to_clipboard/lens/copy_to_clipboard.ts b/x-pack/solutions/security/plugins/security_solution/public/app/actions/copy_to_clipboard/lens/copy_to_clipboard.ts index f4c61c1e7bf7..1666a2e65f9c 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/app/actions/copy_to_clipboard/lens/copy_to_clipboard.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/app/actions/copy_to_clipboard/lens/copy_to_clipboard.ts @@ -9,9 +9,10 @@ import type { CellValueContext, IEmbeddable } from '@kbn/embeddable-plugin/publi import { isErrorEmbeddable } from '@kbn/embeddable-plugin/public'; import { createAction } from '@kbn/ui-actions-plugin/public'; import copy from 'copy-to-clipboard'; +import { isLensApi } from '@kbn/lens-plugin/public'; import { isInSecurityApp } from '../../../../common/hooks/is_in_security_app'; import { KibanaServices } from '../../../../common/lib/kibana'; -import { fieldHasCellActions, isCountField, isLensEmbeddable } from '../../utils'; +import { fieldHasCellActions, isCountField } from '../../utils'; import { COPY_TO_CLIPBOARD, COPY_TO_CLIPBOARD_ICON, COPY_TO_CLIPBOARD_SUCCESS } from '../constants'; export const ACTION_ID = 'embeddable_copyToClipboard'; @@ -39,7 +40,7 @@ export const createCopyToClipboardLensAction = ({ order }: { order?: number }) = getDisplayName: () => COPY_TO_CLIPBOARD, isCompatible: async ({ embeddable, data }) => !isErrorEmbeddable(embeddable as IEmbeddable) && - isLensEmbeddable(embeddable as IEmbeddable) && + isLensApi(embeddable) && isDataColumnsValid(data) && isInSecurityApp(currentAppId), execute: async ({ data }) => { diff --git a/x-pack/solutions/security/plugins/security_solution/public/app/actions/filter/lens/create_action.ts b/x-pack/solutions/security/plugins/security_solution/public/app/actions/filter/lens/create_action.ts index e26446676728..79bcd0e87ced 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/app/actions/filter/lens/create_action.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/app/actions/filter/lens/create_action.ts @@ -16,9 +16,10 @@ import type { CellValueContext, IEmbeddable } from '@kbn/embeddable-plugin/publi import { createAction } from '@kbn/ui-actions-plugin/public'; import { ACTION_INCOMPATIBLE_VALUE_WARNING } from '@kbn/cell-actions/src/actions/translations'; import { i18n } from '@kbn/i18n'; +import { isLensApi } from '@kbn/lens-plugin/public'; import { isInSecurityApp } from '../../../../common/hooks/is_in_security_app'; import { timelineSelectors } from '../../../../timelines/store'; -import { fieldHasCellActions, isLensEmbeddable } from '../../utils'; +import { fieldHasCellActions } from '../../utils'; import { TimelineId } from '../../../../../common/types'; import { DefaultCellActionTypes } from '../../constants'; import type { SecurityAppStore } from '../../../../common/store'; @@ -79,7 +80,7 @@ export const createFilterLensAction = ({ type: DefaultCellActionTypes.FILTER, isCompatible: async ({ embeddable, data }) => !isErrorEmbeddable(embeddable as IEmbeddable) && - isLensEmbeddable(embeddable as IEmbeddable) && + isLensApi(embeddable) && isDataColumnsValid(data) && isInSecurityApp(currentAppId), execute: async ({ data }) => { diff --git a/x-pack/solutions/security/plugins/security_solution/public/app/actions/utils.ts b/x-pack/solutions/security/plugins/security_solution/public/app/actions/utils.ts index 3da597db60c0..568a5f10f31e 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/app/actions/utils.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/app/actions/utils.ts @@ -4,8 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { IEmbeddable } from '@kbn/embeddable-plugin/public'; -import { isLensApi } from '@kbn/lens-plugin/public'; import type { Serializable } from '@kbn/utility-types'; // All cell actions are disabled for these fields in Security @@ -16,12 +14,6 @@ const FIELDS_WITHOUT_CELL_ACTIONS = [ 'kibana.alert.reason', ]; -// @TODO: this is a temporary fix. It needs a better refactor on the consumer side here to -// adapt to the new Embeddable architecture -export const isLensEmbeddable = (embeddable: IEmbeddable): embeddable is IEmbeddable => { - return isLensApi(embeddable); -}; - export const fieldHasCellActions = (field?: string): boolean => { return !!field && !FIELDS_WITHOUT_CELL_ACTIONS.includes(field); }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/hooks/use_ml_rule_config.ts b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/hooks/use_ml_rule_config.ts index 139acb0473c8..9b60c15dc135 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/hooks/use_ml_rule_config.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/hooks/use_ml_rule_config.ts @@ -5,16 +5,15 @@ * 2.0. */ -import { useMemo } from 'react'; import type { DataViewFieldBase } from '@kbn/es-query'; import type { FieldSpec } from '@kbn/data-plugin/common'; -import { getTermsAggregationFields } from '../../../../detection_engine/rule_creation_ui/components/step_define_rule/utils'; import { useRuleFields } from '../../../../detection_engine/rule_management/logic/use_rule_fields'; import { useMlCapabilities } from './use_ml_capabilities'; import { useMlRuleValidations } from './use_ml_rule_validations'; import { hasMlAdminPermissions } from '../../../../../common/machine_learning/has_ml_admin_permissions'; import { hasMlLicense } from '../../../../../common/machine_learning/has_ml_license'; +import { useTermsAggregationFields } from '../../../hooks/use_terms_aggregation_fields'; export interface UseMlRuleConfigReturn { hasMlAdminPermissions: boolean; @@ -45,10 +44,7 @@ export const useMLRuleConfig = ({ const { loading: mlFieldsLoading, fields: mlFields } = useRuleFields({ machineLearningJobId, }); - const mlSuppressionFields = useMemo( - () => getTermsAggregationFields(mlFields as FieldSpec[]), - [mlFields] - ); + const mlSuppressionFields = useTermsAggregationFields(mlFields); return { hasMlAdminPermissions: hasMlAdminPermissions(mlCapabilities), diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/constants.ts b/x-pack/solutions/security/plugins/security_solution/public/common/constants.ts index c114f70915a7..a9761e87c20e 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/constants.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/constants.ts @@ -18,3 +18,5 @@ export const RISK_SCORE_HIGH = 73; export const RISK_SCORE_CRITICAL = 99; export const ONBOARDING_VIDEO_SOURCE = '//play.vidyard.com/K6kKDBbP9SpXife9s2tHNP.html?'; + +export const DEFAULT_HISTORY_WINDOW_SIZE = '7d'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_terms_aggregation_fields.ts b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_terms_aggregation_fields.ts new file mode 100644 index 000000000000..e62b16e82676 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_terms_aggregation_fields.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useMemo } from 'react'; +import type { FieldSpec } from '@kbn/data-views-plugin/common'; +import type { DataViewFieldBase } from '@kbn/es-query'; +import { getTermsAggregationFields } from '../../detection_engine/rule_creation_ui/components/step_define_rule/utils'; + +export function useTermsAggregationFields(fields?: DataViewFieldBase[]) { + const termsAggregationFields = useMemo( + /** + * Typecasting to FieldSpec because fields is + * typed as DataViewFieldBase[] which does not have + * the 'aggregatable' property, however the type is incorrect + * + * fields does contain elements with the aggregatable property. + * We will need to determine where these types are defined and + * figure out where the discrepancy is. + */ + () => getTermsAggregationFields((fields as FieldSpec[]) ?? []), + [fields] + ); + + return termsAggregationFields; +} diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/utils/date_math.ts b/x-pack/solutions/security/plugins/security_solution/public/common/utils/date_math.ts new file mode 100644 index 000000000000..28dbe15955a2 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/common/utils/date_math.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/** + * Converts a date math string to a duration string by removing the 'now-' prefix. + * + * @param historyStart - Date math string to convert. For example, "now-30d". + * @returns Resulting duration string. For example, "30d". + */ +export const convertDateMathToDuration = (dateMathString: string): string => { + if (dateMathString.startsWith('now-')) { + return dateMathString.substring(4); + } + + return dateMathString; +}; + +/** + * Converts a duration string to a dateMath string by adding the 'now-' prefix. + * + * @param durationString - Duration string to convert. For example, "30d". + * @returns Resulting date math string. For example, "now-30d". + */ +export const convertDurationToDateMath = (durationString: string): string => + `now-${durationString}`; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/history_window_start_edit.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/history_window_start_edit.tsx new file mode 100644 index 000000000000..c876fe926ce4 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/history_window_start_edit.tsx @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { ScheduleItemField } from '../schedule_item_field'; +import { type FieldConfig, UseField } from '../../../../shared_imports'; +import { type HistoryWindowStart } from '../../../../../common/api/detection_engine'; +import * as i18n from './translations'; +import { validateHistoryWindowStart } from './validate_history_window_start'; + +const COMPONENT_PROPS = { + idAria: 'historyWindowSize', + dataTestSubj: 'historyWindowSize', + timeTypes: ['m', 'h', 'd'], +}; + +interface HistoryWindowStartEditProps { + path: string; +} + +export function HistoryWindowStartEdit({ path }: HistoryWindowStartEditProps): JSX.Element { + return ( + + ); +} + +const HISTORY_WINDOW_START_FIELD_CONFIG: FieldConfig = { + label: i18n.HISTORY_WINDOW_START_LABEL, + helpText: i18n.HELP_TEXT, + validations: [ + { + validator: validateHistoryWindowStart, + }, + ], +}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/index.tsx new file mode 100644 index 000000000000..a904f5d42771 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/index.tsx @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { HistoryWindowStartEdit } from './history_window_start_edit'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/translations.ts new file mode 100644 index 000000000000..75ff11fe5e1b --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/translations.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const HISTORY_WINDOW_START_LABEL = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.historyWindowSizeLabel', + { + defaultMessage: 'History Window Size', + } +); + +export const HELP_TEXT = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRule.historyWindowSizeHelpText', + { + defaultMessage: "New terms rules only alert if terms don't appear in historical data.", + } +); + +export const MUST_BE_POSITIVE_INTEGER_VALIDATION_ERROR = i18n.translate( + 'xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errNumber', + { + defaultMessage: 'History window size must be a positive number.', + } +); + +export const MUST_BE_GREATER_THAN_ZERO_VALIDATION_ERROR = i18n.translate( + 'xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errMin', + { + defaultMessage: 'History window size must be greater than 0.', + } +); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/validate_history_window_start.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/validate_history_window_start.ts new file mode 100644 index 000000000000..4e274683ad08 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/history_window_start_edit/validate_history_window_start.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { type ValidationFunc } from '../../../../shared_imports'; +import * as i18n from './translations'; + +export function validateHistoryWindowStart(...args: Parameters) { + const [{ path, value }] = args; + + const historyWindowSize = Number.parseInt(String(value), 10); + + if (Number.isNaN(historyWindowSize)) { + return { + code: 'ERR_NOT_INT_NUMBER', + path, + message: i18n.MUST_BE_POSITIVE_INTEGER_VALIDATION_ERROR, + }; + } + + if (historyWindowSize <= 0) { + return { + code: 'ERR_MIN_LENGTH', + path, + message: i18n.MUST_BE_GREATER_THAN_ZERO_VALIDATION_ERROR, + }; + } +} diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/index.tsx new file mode 100644 index 000000000000..22c3c9e9047c --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/index.tsx @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { NewTermsFieldsEdit } from './new_terms_fields_edit'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_edit.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_edit.tsx new file mode 100644 index 000000000000..f50c62ed8f7a --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_edit.tsx @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; +import { UseField, fieldValidators } from '../../../../shared_imports'; +import { NewTermsFieldsField } from './new_terms_fields_field'; +import * as i18n from './translations'; + +interface NewTermsFieldsEditProps { + path: string; + fieldNames: string[]; +} + +export const NewTermsFieldsEdit = memo(function NewTermsFieldsEdit({ + path, + fieldNames, +}: NewTermsFieldsEditProps): JSX.Element { + return ( + + ); +}); + +const NEW_TERMS_FIELDS_CONFIG = { + label: i18n.NEW_TERMS_FIELDS_LABEL, + helpText: i18n.HELP_TEXT, + validations: [ + { + validator: fieldValidators.emptyField(i18n.MIN_FIELDS_COUNT_VALIDATION_ERROR), + }, + { + validator: fieldValidators.maxLengthField(i18n.MAX_FIELDS_COUNT_VALIDATION_ERROR), + }, + ], +}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_field.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_field.tsx new file mode 100644 index 000000000000..a9c1148402f1 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/new_terms_fields_field.tsx @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo } from 'react'; + +import type { DataViewFieldBase } from '@kbn/es-query'; +import { ComboBoxField } from '@kbn/es-ui-shared-plugin/static/forms/components'; +import type { FieldHook } from '../../../../shared_imports'; +import { PLACEHOLDER } from './translations'; + +interface NewTermsFieldsProps { + fieldNames: DataViewFieldBase[]; + field: FieldHook; +} + +const FIELD_COMBO_BOX_WIDTH = 410; + +const fieldDescribedByIds = 'newTermsFieldEdit'; + +export const NewTermsFieldsField = memo(function NewTermsFieldsField({ + fieldNames, + field, +}: NewTermsFieldsProps): JSX.Element { + const fieldEuiFieldProps = { + fullWidth: true, + noSuggestions: false, + options: fieldNames.map((name) => ({ label: name })), + placeholder: PLACEHOLDER, + onCreateOption: undefined, + style: { width: `${FIELD_COMBO_BOX_WIDTH}px` }, + }; + + return ( + + ); +}); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/translations.ts new file mode 100644 index 000000000000..4eb18b9a318e --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/new_terms_fields_edit/translations.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; +import { MAX_NUMBER_OF_NEW_TERMS_FIELDS } from '../../../../../common/constants'; + +export const NEW_TERMS_FIELDS_LABEL = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsLabel', + { + defaultMessage: 'Fields', + } +); + +export const PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.placeholderText', + { + defaultMessage: 'Select a field', + } +); + +export const HELP_TEXT = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldNewTermsFieldHelpText', + { + defaultMessage: 'Select a field to check for new terms.', + } +); + +export const MIN_FIELDS_COUNT_VALIDATION_ERROR = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.minFieldsCountError', + { + defaultMessage: 'A minimum of one field is required.', + } +); + +export const MAX_FIELDS_COUNT_VALIDATION_ERROR = { + length: MAX_NUMBER_OF_NEW_TERMS_FIELDS, + message: i18n.translate( + 'xpack.securitySolution.detectionEngine.validations.stepDefineRule.newTermsField.maxFieldsCountError', + { + defaultMessage: 'Number of fields must be 3 or less.', + } + ), +}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/index.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/index.ts new file mode 100644 index 000000000000..f2458bbb5a4e --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { ScheduleItemField } from './schedule_item_field'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.test.tsx new file mode 100644 index 000000000000..bf019bd43f2f --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.test.tsx @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { mount, shallow } from 'enzyme'; + +import { ScheduleItemField } from './schedule_item_field'; +import { TestProviders, useFormFieldMock } from '../../../../common/mock'; + +describe('ScheduleItemField', () => { + it('renders correctly', () => { + const mockField = useFormFieldMock(); + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="schedule-item"]')).toHaveLength(1); + }); + + it('accepts a large number via user input', () => { + const mockField = useFormFieldMock(); + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="interval"]') + .last() + .simulate('change', { target: { value: '5000000' } }); + + expect(mockField.setValue).toHaveBeenCalledWith('5000000s'); + }); + + it('clamps a number value greater than MAX_SAFE_INTEGER to MAX_SAFE_INTEGER', () => { + const unsafeInput = '99999999999999999999999'; + + const mockField = useFormFieldMock(); + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="interval"]') + .last() + .simulate('change', { target: { value: unsafeInput } }); + + const expectedValue = `${Number.MAX_SAFE_INTEGER}s`; + expect(mockField.setValue).toHaveBeenCalledWith(expectedValue); + }); + + it('converts a non-numeric value to 0', () => { + const unsafeInput = 'this is not a number'; + + const mockField = useFormFieldMock(); + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="interval"]') + .last() + .simulate('change', { target: { value: unsafeInput } }); + + expect(mockField.setValue).toHaveBeenCalledWith('0s'); + }); +}); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.tsx new file mode 100644 index 000000000000..241e3869958a --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/schedule_item_field.tsx @@ -0,0 +1,181 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { EuiSelectProps, EuiFieldNumberProps } from '@elastic/eui'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiFieldNumber, + EuiFormRow, + EuiSelect, + transparentize, +} from '@elastic/eui'; +import { isEmpty } from 'lodash/fp'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import styled from 'styled-components'; + +import type { FieldHook } from '../../../../shared_imports'; +import { getFieldValidityAndErrorMessage } from '../../../../shared_imports'; + +import * as I18n from './translations'; + +interface ScheduleItemProps { + field: FieldHook; + dataTestSubj: string; + idAria: string; + isDisabled: boolean; + minimumValue?: number; + timeTypes?: string[]; + fullWidth?: boolean; +} + +const timeTypeOptions = [ + { value: 's', text: I18n.SECONDS }, + { value: 'm', text: I18n.MINUTES }, + { value: 'h', text: I18n.HOURS }, + { value: 'd', text: I18n.DAYS }, +]; + +// move optional label to the end of input +const StyledLabelAppend = styled(EuiFlexItem)` + &.euiFlexItem { + margin-left: 31px; + } +`; + +const StyledEuiFormRow = styled(EuiFormRow)` + max-width: none; + + .euiFormControlLayout__append { + padding-inline: 0 !important; + } + + .euiFormControlLayoutIcons { + color: ${({ theme }) => theme.eui.euiColorPrimary}; + } +`; + +const MyEuiSelect = styled(EuiSelect)` + min-width: 106px; // Preserve layout when disabled & dropdown arrow is not rendered + background: ${({ theme }) => + transparentize(theme.eui.euiColorPrimary, 0.1)} !important; // Override focus states etc. + color: ${({ theme }) => theme.eui.euiColorPrimary}; + box-shadow: none; +`; + +const getNumberFromUserInput = (input: string, minimumValue = 0): number => { + const number = parseInt(input, 10); + if (Number.isNaN(number)) { + return minimumValue; + } else { + return Math.max(minimumValue, Math.min(number, Number.MAX_SAFE_INTEGER)); + } +}; + +export const ScheduleItemField = ({ + dataTestSubj, + field, + idAria, + isDisabled, + minimumValue = 0, + timeTypes = ['s', 'm', 'h'], + fullWidth = false, +}: ScheduleItemProps) => { + const [timeType, setTimeType] = useState(timeTypes[0]); + const [timeVal, setTimeVal] = useState(0); + const { isInvalid, errorMessage } = getFieldValidityAndErrorMessage(field); + const { value, setValue } = field; + + const onChangeTimeType = useCallback>( + (e) => { + setTimeType(e.target.value); + setValue(`${timeVal}${e.target.value}`); + }, + [setValue, timeVal] + ); + + const onChangeTimeVal = useCallback>( + (e) => { + const sanitizedValue = getNumberFromUserInput(e.target.value, minimumValue); + setTimeVal(sanitizedValue); + setValue(`${sanitizedValue}${timeType}`); + }, + [minimumValue, setValue, timeType] + ); + + useEffect(() => { + if (value !== `${timeVal}${timeType}`) { + const filterTimeVal = value.match(/\d+/g); + const filterTimeType = value.match(/[a-zA-Z]+/g); + if ( + !isEmpty(filterTimeVal) && + filterTimeVal != null && + !isNaN(Number(filterTimeVal[0])) && + Number(filterTimeVal[0]) !== Number(timeVal) + ) { + setTimeVal(Number(filterTimeVal[0])); + } + if ( + !isEmpty(filterTimeType) && + filterTimeType != null && + timeTypes.includes(filterTimeType[0]) && + filterTimeType[0] !== timeType + ) { + setTimeType(filterTimeType[0]); + } + } + }, [timeType, timeTypes, timeVal, value]); + + // EUI missing some props + const rest = { disabled: isDisabled }; + const label = useMemo( + () => ( + + + {field.label} + + + {field.labelAppend} + + + ), + [field.label, field.labelAppend] + ); + + return ( + + timeTypes.includes(type.value))} + onChange={onChangeTimeType} + value={timeType} + aria-label={field.label} + data-test-subj="timeType" + {...rest} + /> + } + fullWidth + min={minimumValue} + max={Number.MAX_SAFE_INTEGER} + onChange={onChangeTimeVal} + value={timeVal} + data-test-subj="interval" + {...rest} + /> + + ); +}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/translations.ts new file mode 100644 index 000000000000..c460d2f7198b --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/schedule_item_field/translations.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const SECONDS = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRuleForm.secondsOptionDescription', + { + defaultMessage: 'Seconds', + } +); + +export const MINUTES = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRuleForm.minutesOptionDescription', + { + defaultMessage: 'Minutes', + } +); + +export const HOURS = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRuleForm.hoursOptionDescription', + { + defaultMessage: 'Hours', + } +); + +export const DAYS = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRuleForm.daysOptionDescription', + { + defaultMessage: 'Days', + } +); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/description_step/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/description_step/index.tsx index 26c81f325ea1..a91487afc448 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/description_step/index.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/description_step/index.tsx @@ -72,6 +72,8 @@ import { ALERT_SUPPRESSION_MISSING_FIELDS_FIELD_NAME, } from '../../../rule_creation/components/alert_suppression_edit'; import { THRESHOLD_ALERT_SUPPRESSION_ENABLED } from '../../../rule_creation/components/threshold_alert_suppression_edit'; +import { NEW_TERMS_FIELDS_LABEL } from '../../../rule_creation/components/new_terms_fields_edit/translations'; +import { HISTORY_WINDOW_START_LABEL } from '../../../rule_creation/components/history_window_start_edit/translations'; import type { FieldValueQueryBar } from '../query_bar_field'; const DescriptionListContainer = styled(EuiDescriptionList)` @@ -341,6 +343,9 @@ export const getDescriptionItem = ( } else if (field === 'threatMapping') { const threatMap: ThreatMapping = get(field, data); return buildThreatMappingDescription(label, threatMap); + } else if (field === 'newTermsFields') { + const values: string[] = get(field, data); + return buildStringArrayDescription(NEW_TERMS_FIELDS_LABEL, field, values); } else if (Array.isArray(get(field, data)) && field !== 'threatMapping') { const values: string[] = get(field, data); return buildStringArrayDescription(label, field, values); @@ -357,6 +362,9 @@ export const getDescriptionItem = ( } else if (field === 'maxSignals') { const value: number | undefined = get(field, data); return value ? [{ title: label, description: value }] : []; + } else if (field === 'historyWindowSize') { + const value: number = get(field, data); + return value ? [{ title: HISTORY_WINDOW_START_LABEL, description: value }] : []; } const description: string = get(field, data); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/index.tsx deleted file mode 100644 index 7dfb24200e64..000000000000 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/index.tsx +++ /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 React, { useMemo } from 'react'; - -import type { DataViewFieldBase } from '@kbn/es-query'; -import type { FieldHook } from '../../../../shared_imports'; -import { Field } from '../../../../shared_imports'; -import { NEW_TERMS_FIELD_PLACEHOLDER } from './translations'; - -interface NewTermsFieldsProps { - browserFields: DataViewFieldBase[]; - field: FieldHook; -} - -const FIELD_COMBO_BOX_WIDTH = 410; - -const fieldDescribedByIds = 'detectionEngineStepDefineRuleNewTermsField'; - -export const NewTermsFieldsComponent: React.FC = ({ - browserFields, - field, -}: NewTermsFieldsProps) => { - const fieldEuiFieldProps = useMemo( - () => ({ - fullWidth: true, - noSuggestions: false, - options: browserFields.map((browserField) => ({ label: browserField.name })), - placeholder: NEW_TERMS_FIELD_PLACEHOLDER, - onCreateOption: undefined, - style: { width: `${FIELD_COMBO_BOX_WIDTH}px` }, - }), - [browserFields] - ); - return ; -}; - -export const NewTermsFields = React.memo(NewTermsFieldsComponent); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/translations.ts deleted file mode 100644 index 1bf73b4a46b4..000000000000 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/new_terms_fields/translations.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { i18n } from '@kbn/i18n'; - -export const NEW_TERMS_FIELD_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsField.placeholderText', - { - defaultMessage: 'Select a field', - } -); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/rule_preview/helpers.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/rule_preview/helpers.ts index 045e957c4e12..fcbdfdf4f86b 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/rule_preview/helpers.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/rule_preview/helpers.ts @@ -107,7 +107,7 @@ export const getIsRulePreviewDisabled = ({ threatMapping, machineLearningJobId, queryBar, - newTermsFields, + newTermsFields = [], }: { ruleType: Type; isQueryBarValid: boolean; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/index.tsx index 7b056b596979..f7845c31378a 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/index.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/index.tsx @@ -55,7 +55,6 @@ import { } from '../../../../shared_imports'; import type { FormHook, FieldHook } from '../../../../shared_imports'; import { schema } from './schema'; -import { getTermsAggregationFields } from './utils'; import { useExperimentalFeatureFieldsTransform } from './use_experimental_feature_fields_transform'; import * as i18n from './translations'; import { @@ -72,8 +71,6 @@ import { EqlQueryEdit } from '../../../rule_creation/components/eql_query_edit'; import { DataViewSelectorField } from '../data_view_selector_field'; import { ThreatMatchInput } from '../threatmatch_input'; import { useFetchIndex } from '../../../../common/containers/source'; -import { NewTermsFields } from '../new_terms_fields'; -import { ScheduleItem } from '../../../rule_creation/components/schedule_item_form'; import { RequiredFields } from '../../../rule_creation/components/required_fields'; import { DocLink } from '../../../../common/components/links_to_docs/doc_link'; import { useLicense } from '../../../../common/hooks/use_license'; @@ -90,6 +87,10 @@ import { } from '../../../rule_creation/components/alert_suppression_edit'; import { ThresholdAlertSuppressionEdit } from '../../../rule_creation/components/threshold_alert_suppression_edit'; import { usePersistentAlertSuppressionState } from './use_persistent_alert_suppression_state'; +import { useTermsAggregationFields } from '../../../../common/hooks/use_terms_aggregation_fields'; +import { HistoryWindowStartEdit } from '../../../rule_creation/components/history_window_start_edit'; +import { NewTermsFieldsEdit } from '../../../rule_creation/components/new_terms_fields_edit'; +import { usePersistentNewTermsState } from './use_persistent_new_terms_state'; import { EsqlQueryEdit } from '../../../rule_creation/components/esql_query_edit'; import { usePersistentQuery } from './use_persistent_query'; @@ -211,18 +212,11 @@ const StepDefineRuleComponent: FC = ({ () => (indexPattern.fields as FieldSpec[]).filter((field) => field.aggregatable === true), [indexPattern.fields] ); - const termsAggregationFields = useMemo( - /** - * Typecasting to FieldSpec because fields is - * typed as DataViewFieldBase[] which does not have - * the 'aggregatable' property, however the type is incorrect - * - * fields does contain elements with the aggregatable property. - * We will need to determine where these types are defined and - * figure out where the discrepency is. - */ - () => getTermsAggregationFields(indexPattern.fields as FieldSpec[]), - [indexPattern.fields] + + const termsAggregationFields = useTermsAggregationFields(indexPattern.fields); + const termsAggregationFieldNames = useMemo( + () => termsAggregationFields.map((field) => field.name), + [termsAggregationFields] ); const [threatIndexPatternsLoading, { indexPatterns: threatIndexPatterns }] = @@ -245,6 +239,12 @@ const StepDefineRuleComponent: FC = ({ form, }); usePersistentAlertSuppressionState({ form }); + usePersistentNewTermsState({ + form, + ruleTypePath: 'ruleType', + newTermsFieldsPath: 'newTermsFields', + historyWindowStartPath: 'historyWindowSize', + }); const handleSetRuleFromTimeline = useCallback( ({ index: timelineIndex, queryBar: timelineQueryBar, eqlOptions }) => { @@ -730,30 +730,14 @@ const StepDefineRuleComponent: FC = ({ - - <> - - - - + {isNewTermsRule(ruleType) && ( + + <> + + + + + )} diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/schema.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/schema.tsx index 323e321eee8d..4f168d94388d 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/schema.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/schema.tsx @@ -17,12 +17,10 @@ import { } from '../../../../common/components/threat_match/helpers'; import { isEsqlRule, - isNewTermsRule, isThreatMatchRule, isThresholdRule, isSuppressionRuleConfiguredWithGroupBy, } from '../../../../../common/detection_engine/utils'; -import { MAX_NUMBER_OF_NEW_TERMS_FIELDS } from '../../../../../common/constants'; import { isMlRule } from '../../../../../common/machine_learning/helpers'; import type { ERROR_CODE, FormSchema, ValidationFunc } from '../../../../shared_imports'; import { FIELD_TYPES, fieldValidators } from '../../../../shared_imports'; @@ -478,106 +476,8 @@ export const schema: FormSchema = { }, ], }, - newTermsFields: { - type: FIELD_TYPES.COMBO_BOX, - label: i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsLabel', - { - defaultMessage: 'Fields', - } - ), - helpText: i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldNewTermsFieldHelpText', - { - defaultMessage: 'Select a field to check for new terms.', - } - ), - validations: [ - { - validator: ( - ...args: Parameters - ): ReturnType> | undefined => { - const [{ formData }] = args; - const needsValidation = isNewTermsRule(formData.ruleType); - if (!needsValidation) { - return; - } - - return fieldValidators.emptyField( - i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.newTermsFieldsMin', - { - defaultMessage: 'A minimum of one field is required.', - } - ) - )(...args); - }, - }, - { - validator: ( - ...args: Parameters - ): ReturnType> | undefined => { - const [{ formData }] = args; - const needsValidation = isNewTermsRule(formData.ruleType); - if (!needsValidation) { - return; - } - return fieldValidators.maxLengthField({ - length: MAX_NUMBER_OF_NEW_TERMS_FIELDS, - message: i18n.translate( - 'xpack.securitySolution.detectionEngine.validations.stepDefineRule.newTermsFieldsMax', - { - defaultMessage: 'Number of fields must be 3 or less.', - } - ), - })(...args); - }, - }, - ], - }, - historyWindowSize: { - label: i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepDefineRule.historyWindowSizeLabel', - { - defaultMessage: 'History Window Size', - } - ), - helpText: i18n.translate( - 'xpack.securitySolution.detectionEngine.createRule.stepScheduleRule.historyWindowSizeHelpText', - { - defaultMessage: "New terms rules only alert if terms don't appear in historical data.", - } - ), - validations: [ - { - validator: ( - ...args: Parameters - ): ReturnType> | undefined => { - const [{ path, formData }] = args; - const needsValidation = isNewTermsRule(formData.ruleType); - - if (!needsValidation) { - return; - } - - const filterTimeVal = formData.historyWindowSize.match(/\d+/g); - - if (filterTimeVal <= 0) { - return { - code: 'ERR_MIN_LENGTH', - path, - message: i18n.translate( - 'xpack.securitySolution.detectionEngine.validations.stepDefineRule.historyWindowSize.errMin', - { - defaultMessage: 'History window size must be greater than 0.', - } - ), - }; - } - }, - }, - ], - }, + newTermsFields: {}, + historyWindowSize: {}, [ALERT_SUPPRESSION_FIELDS_FIELD_NAME]: { validations: [ { diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/use_persistent_new_terms_state.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/use_persistent_new_terms_state.tsx new file mode 100644 index 000000000000..61bfa45ba8a7 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_define_rule/use_persistent_new_terms_state.tsx @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useEffect, useRef } from 'react'; +import usePrevious from 'react-use/lib/usePrevious'; +import { isNewTermsRule } from '../../../../../common/detection_engine/utils'; +import type { FormHook } from '../../../../shared_imports'; +import { useFormData } from '../../../../shared_imports'; +import { type DefineStepRule } from '../../../../detections/pages/detection_engine/rules/types'; +import { + type NewTermsFields, + type HistoryWindowStart, +} from '../../../../../common/api/detection_engine'; + +interface UsePersistentNewTermsStateParams { + form: FormHook; + ruleTypePath: string; + newTermsFieldsPath: string; + historyWindowStartPath: string; +} + +interface LastNewTermsState { + newTermsFields: NewTermsFields; + historyWindowStart: HistoryWindowStart; +} + +export function usePersistentNewTermsState({ + form, + ruleTypePath, + newTermsFieldsPath, + historyWindowStartPath, +}: UsePersistentNewTermsStateParams): void { + const lastNewTermsState = useRef(); + const [formData] = useFormData({ form, watch: [newTermsFieldsPath, historyWindowStartPath] }); + + const { + [ruleTypePath]: ruleType, + [newTermsFieldsPath]: newTermsFields, + [historyWindowStartPath]: historyWindowStart, + } = formData; + const previousRuleType = usePrevious(ruleType); + + useEffect(() => { + if ( + isNewTermsRule(ruleType) && + !isNewTermsRule(previousRuleType) && + lastNewTermsState.current + ) { + form.updateFieldValues({ + [newTermsFieldsPath]: lastNewTermsState.current.newTermsFields, + [historyWindowStartPath]: lastNewTermsState.current.historyWindowStart, + }); + + return; + } + + if (isNewTermsRule(ruleType)) { + lastNewTermsState.current = { newTermsFields, historyWindowStart }; + } + }, [ + form, + ruleType, + previousRuleType, + newTermsFieldsPath, + historyWindowStartPath, + newTermsFields, + historyWindowStart, + ]); +} diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_schedule_rule/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_schedule_rule/index.tsx index 2197b069de40..7c309ed32a68 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_schedule_rule/index.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation_ui/components/step_schedule_rule/index.tsx @@ -13,11 +13,11 @@ import type { ScheduleStepRule, } from '../../../../detections/pages/detection_engine/rules/types'; import { StepRuleDescription } from '../description_step'; -import { ScheduleItem } from '../../../rule_creation/components/schedule_item_form'; import { Form, UseField } from '../../../../shared_imports'; import type { FormHook } from '../../../../shared_imports'; import { StepContentWrapper } from '../../../rule_creation/components/step_content_wrapper'; import { schema } from './schema'; +import { ScheduleItemField } from '../../../rule_creation/components/schedule_item_field'; const StyledForm = styled(Form)` max-width: 235px !important; @@ -43,7 +43,7 @@ const StepScheduleRuleComponent: FC = ({ = ({ /> { const timeObj: { unit: Unit; value: number } = { @@ -530,7 +531,7 @@ export const formatDefineStepData = (defineStepData: DefineStepRule): DefineStep query: ruleFields.queryBar?.query?.query as string, required_fields: requiredFields, new_terms_fields: ruleFields.newTermsFields, - history_window_start: `now-${ruleFields.historyWindowSize}`, + history_window_start: convertDurationToDateMath(ruleFields.historyWindowSize), ...alertSuppressionFields, } : isEsqlFields(ruleFields) && !('index' in ruleFields) diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_definition_section.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_definition_section.tsx index 3e08f4ce3acc..de4fce3da368 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_definition_section.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_definition_section.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React from 'react'; +import React, { useMemo } from 'react'; import { isEmpty } from 'lodash/fp'; import { EuiDescriptionList, @@ -23,8 +23,8 @@ import type { import type { Filter } from '@kbn/es-query'; import type { SavedQuery } from '@kbn/data-plugin/public'; import { mapAndFlattenFilters } from '@kbn/data-plugin/public'; -import type { DataView } from '@kbn/data-views-plugin/public'; import { FilterItems } from '@kbn/unified-search-plugin/public'; +import { isDataView } from '../../../../common/components/query_bar'; import type { AlertSuppressionMissingFieldsStrategy, EqlOptionalFields, @@ -40,10 +40,7 @@ import { AlertSuppressionLabel } from '../../../rule_creation_ui/components/desc import { useGetSavedQuery } from '../../../../detections/pages/detection_engine/rules/use_get_saved_query'; import * as threatMatchI18n from '../../../../common/components/threat_match/translations'; import * as timelinesI18n from '../../../../timelines/components/timeline/translations'; -import { useRuleIndexPattern } from '../../../rule_creation_ui/pages/form'; -import { DataSourceType } from '../../../../detections/pages/detection_engine/rules/types'; import type { Duration } from '../../../../detections/pages/detection_engine/rules/types'; -import { convertHistoryStartToSize } from '../../../../detections/pages/detection_engine/rules/helpers'; import { MlJobsDescription } from '../../../rule_creation/components/ml_jobs_description/ml_jobs_description'; import { MlJobLink } from '../../../rule_creation/components/ml_job_link/ml_job_link'; import { useSecurityJobs } from '../../../../common/components/ml_popover/hooks/use_security_jobs'; @@ -60,11 +57,14 @@ import { } from './rule_definition_section.styles'; import { getQueryLanguageLabel } from './helpers'; import { useDefaultIndexPattern } from '../../hooks/use_default_index_pattern'; +import { convertDateMathToDuration } from '../../../../common/utils/date_math'; +import { DEFAULT_HISTORY_WINDOW_SIZE } from '../../../../common/constants'; import { EQL_OPTIONS_EVENT_CATEGORY_FIELD_LABEL, EQL_OPTIONS_EVENT_TIEBREAKER_FIELD_LABEL, EQL_OPTIONS_EVENT_TIMESTAMP_FIELD_LABEL, } from '../../../rule_creation/components/eql_query_edit/translations'; +import { useDataView } from './three_way_diff/final_edit/fields/hooks/use_data_view'; interface SavedQueryNameProps { savedQueryName: string; @@ -89,16 +89,34 @@ export const Filters = ({ index, 'data-test-subj': dataTestSubj, }: FiltersProps) => { - const flattenedFilters = mapAndFlattenFilters(filters); - const defaultIndexPattern = useDefaultIndexPattern(); + const useDataViewParams = dataViewId + ? { dataViewId } + : { indexPatterns: index ?? defaultIndexPattern }; + const { dataView } = useDataView(useDataViewParams); + const isEsql = filters.some((filter) => filter?.query?.language === 'esql'); + const searchBarFilters = useMemo(() => { + if (!index || isDataView(index) || isEsql) { + return filters; + } + const filtersWithUpdatedMetaIndex = filters.map((filter) => { + return { + ...filter, + meta: { + ...filter.meta, + index: index.join(','), + }, + }; + }); - const { indexPattern } = useRuleIndexPattern({ - dataSourceType: dataViewId ? DataSourceType.DataView : DataSourceType.IndexPatterns, - index: index ?? defaultIndexPattern, - dataViewId, - }); + return filtersWithUpdatedMetaIndex; + }, [filters, index, isEsql]); + + if (!dataView) { + return null; + } + const flattenedFilters = mapAndFlattenFilters(searchBarFilters); const styles = filtersStyles; return ( @@ -109,7 +127,7 @@ export const Filters = ({ responsive={false} gutterSize="xs" > - + ); }; @@ -418,7 +436,9 @@ interface HistoryWindowSizeProps { } export const HistoryWindowSize = ({ historyWindowStart }: HistoryWindowSizeProps) => { - const size = historyWindowStart ? convertHistoryStartToSize(historyWindowStart) : '7d'; + const size = historyWindowStart + ? convertDateMathToDuration(historyWindowStart) + : DEFAULT_HISTORY_WINDOW_SIZE; return ( diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_details_flyout.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_details_flyout.tsx index 3425779926f7..3909a9af5a60 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_details_flyout.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/rule_details_flyout.tsx @@ -40,6 +40,13 @@ const StyledEuiFlyoutBody = styled(EuiFlyoutBody)` display: flex; flex: 1; overflow: hidden; + /* + Removes "transform: translateZ(0)" from EuiFlyoutBody styles to avoid creating a new stacking context. + Fixed elements inside the flyout body are now correctly positioned relative to the viewport. + See: https://github.com/elastic/eui/blob/ffd0cbca4d323ad0b1d5a73c252380d93178e5e7/packages/eui/src/global_styling/mixins/_helpers.ts#L122 + The Chrome bug mentioned in the link above no longer reproduces, so this change is safe. + */ + transform: none; .euiFlyoutBody__overflowContent { flex: 1; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/comparison_side/comparison_side_help_info.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/comparison_side/comparison_side_help_info.tsx index 37b23652bfcb..1f4e6a255fb8 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/comparison_side/comparison_side_help_info.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/comparison_side/comparison_side_help_info.tsx @@ -57,7 +57,7 @@ export function ComparisonSideHelpInfo({ options }: ComparisonSideHelpInfoProps)
    {optionsWithDescriptions.map( ({ title: displayName, description: explanation }) => ( -
  • +
  • {displayName} {'-'} {explanation}
  • ) diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_adapter.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_adapter.tsx new file mode 100644 index 000000000000..084a81e3b959 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_adapter.tsx @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { HistoryWindowStartEdit } from '../../../../../../../rule_creation/components/history_window_start_edit'; + +export function HistoryWindowStartEditAdapter(): JSX.Element { + return ; +} diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_form.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_form.tsx new file mode 100644 index 000000000000..87ac2fee64e7 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/history_window_start/history_window_start_edit_form.tsx @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { type FormData } from '../../../../../../../../shared_imports'; +import { HistoryWindowStartEditAdapter } from './history_window_start_edit_adapter'; +import type { HistoryWindowStart } from '../../../../../../../../../common/api/detection_engine'; +import { + convertDurationToDateMath, + convertDateMathToDuration, +} from '../../../../../../../../common/utils/date_math'; +import { DEFAULT_HISTORY_WINDOW_SIZE } from '../../../../../../../../common/constants'; +import { RuleFieldEditFormWrapper } from '../../../field_final_side'; + +export function HistoryWindowStartEditForm(): JSX.Element { + return ( + + ); +} + +interface HistoryWindowFormData { + historyWindowSize: HistoryWindowStart; +} + +function deserializer(defaultValue: FormData): HistoryWindowFormData { + return { + historyWindowSize: defaultValue.history_window_start + ? convertDateMathToDuration(defaultValue.history_window_start) + : DEFAULT_HISTORY_WINDOW_SIZE, + }; +} + +function serializer(formData: FormData): { history_window_start: HistoryWindowStart } { + return { + history_window_start: convertDurationToDateMath(formData.historyWindowSize), + }; +} + +const schema = {}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/hooks/use_data_view.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/hooks/use_data_view.ts index 4cfb30766530..123a7b3cffb5 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/hooks/use_data_view.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/hooks/use_data_view.ts @@ -9,7 +9,7 @@ import { useEffect, useState } from 'react'; import type { DataView } from '@kbn/data-views-plugin/common'; import { useKibana } from '../../../../../../../../common/lib/kibana'; -type UseDataViewParams = +export type UseDataViewParams = | { indexPatterns: string[]; dataViewId?: never } | { indexPatterns?: never; dataViewId: string }; @@ -33,6 +33,7 @@ export function useDataView(indexPatternsOrDataViewId: UseDataViewParams): UseDa if (indexPatternsOrDataViewId.indexPatterns) { const indexPatternsDataView = await dataViewsService.create({ title: indexPatternsOrDataViewId.indexPatterns.join(','), + id: indexPatternsOrDataViewId.indexPatterns.join(','), allowNoIndex: true, }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_adapter.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_adapter.tsx new file mode 100644 index 000000000000..476bf9869bd9 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_adapter.tsx @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { NewTermsFieldsEdit } from '../../../../../../../rule_creation/components/new_terms_fields_edit'; +import { useDiffableRuleDataView } from '../hooks/use_diffable_rule_data_view'; +import type { DiffableRule } from '../../../../../../../../../common/api/detection_engine'; +import { useTermsAggregationFields } from '../../../../../../../../common/hooks/use_terms_aggregation_fields'; + +interface NewTermsFieldsEditAdapterProps { + finalDiffableRule: DiffableRule; +} + +export function NewTermsFieldsEditAdapter({ + finalDiffableRule, +}: NewTermsFieldsEditAdapterProps): JSX.Element { + const { dataView } = useDiffableRuleDataView(finalDiffableRule); + const termsAggregationFields = useTermsAggregationFields(dataView?.fields ?? []); + const fieldNames = termsAggregationFields.map((field) => field.name); + + return ; +} diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_form.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_form.tsx new file mode 100644 index 000000000000..9b8d709b27f0 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/new_terms_fields/new_terms_fields_edit_form.tsx @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { RuleFieldEditFormWrapper } from '../../../field_final_side'; +import { NewTermsFieldsEditAdapter } from './new_terms_fields_edit_adapter'; + +export function NewTermsFieldsEditForm(): JSX.Element { + return ( + + ); +} + +const schema = {}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/rule_schedule.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/rule_schedule.tsx index 12e7bbea9a20..3acd7c3050fb 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/rule_schedule.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/fields/rule_schedule.tsx @@ -10,8 +10,8 @@ import { parseDuration } from '@kbn/alerting-plugin/common'; import { type FormSchema, type FormData, UseField } from '../../../../../../../shared_imports'; import { schema } from '../../../../../../rule_creation_ui/components/step_schedule_rule/schema'; import type { RuleSchedule } from '../../../../../../../../common/api/detection_engine'; -import { ScheduleItem } from '../../../../../../rule_creation/components/schedule_item_form'; import { secondsToDurationString } from '../../../../../../../detections/pages/detection_engine/rules/helpers'; +import { ScheduleItemField } from '../../../../../../rule_creation/components/schedule_item_field'; export const ruleScheduleSchema = { interval: schema.interval, @@ -28,8 +28,8 @@ const componentProps = { export function RuleScheduleEdit(): JSX.Element { return ( <> - - + + ); } diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/new_terms_rule_field_edit.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/new_terms_rule_field_edit.tsx index e2860d431aff..f47607abe384 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/new_terms_rule_field_edit.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/components/rule_details/three_way_diff/final_edit/new_terms_rule_field_edit.tsx @@ -7,9 +7,12 @@ import React from 'react'; import type { UpgradeableNewTermsFields } from '../../../../model/prebuilt_rule_upgrade/fields'; -import { KqlQueryEditForm } from './fields/kql_query'; -import { DataSourceEditForm } from './fields/data_source'; import { AlertSuppressionEditForm } from './fields/alert_suppression'; +import { DataSourceEditForm } from './fields/data_source'; +import { HistoryWindowStartEditForm } from './fields/history_window_start/history_window_start_edit_form'; +import { KqlQueryEditForm } from './fields/kql_query'; +import { NewTermsFieldsEditForm } from './fields/new_terms_fields/new_terms_fields_edit_form'; +import { assertUnreachable } from '../../../../../../../common/utility_types'; interface NewTermsRuleFieldEditProps { fieldName: UpgradeableNewTermsFields; @@ -17,13 +20,17 @@ interface NewTermsRuleFieldEditProps { export function NewTermsRuleFieldEdit({ fieldName }: NewTermsRuleFieldEditProps) { switch (fieldName) { - case 'kql_query': - return ; - case 'data_source': - return ; case 'alert_suppression': return ; + case 'data_source': + return ; + case 'history_window_start': + return ; + case 'kql_query': + return ; + case 'new_terms_fields': + return ; default: - return null; // Will be replaced with `assertUnreachable(fieldName)` once all fields are implemented + return assertUnreachable(fieldName); } } diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.test.tsx index 7354bd306d6e..f1f79e911ec4 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.test.tsx @@ -64,11 +64,11 @@ describe('Component BulkEditRuleErrorsList', () => { ], [ BulkActionsDryRunErrCode.MACHINE_LEARNING_INDEX_PATTERN, - "2 custom machine learning rules (these rules don't have index patterns)", + "2 machine learning rules (these rules don't have index patterns)", ], [ BulkActionsDryRunErrCode.ESQL_INDEX_PATTERN, - "2 custom ES|QL rules (these rules don't have index patterns)", + "2 ES|QL rules (these rules don't have index patterns)", ], [ BulkActionsDryRunErrCode.MACHINE_LEARNING_AUTH, diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.tsx index 72e380a1a7d5..ce6be3edbf14 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/bulk_action_rule_errors_list.tsx @@ -41,7 +41,7 @@ const BulkEditRuleErrorItem = ({
  • @@ -61,7 +61,7 @@ const BulkEditRuleErrorItem = ({
  • diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/forms/schedule_form.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/forms/schedule_form.tsx index 88e1411a5e0b..518c18a59a41 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/forms/schedule_form.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/components/rules_table/bulk_actions/forms/schedule_form.tsx @@ -9,11 +9,11 @@ import { EuiCallOut } from '@elastic/eui'; import React, { useCallback } from 'react'; import type { BulkActionEditPayload } from '../../../../../../../common/api/detection_engine/rule_management'; import { BulkActionEditTypeEnum } from '../../../../../../../common/api/detection_engine/rule_management'; -import { ScheduleItem } from '../../../../../rule_creation/components/schedule_item_form'; import type { FormSchema } from '../../../../../../shared_imports'; import { UseField, useForm } from '../../../../../../shared_imports'; import { bulkSetSchedule as i18n } from '../translations'; import { BulkEditFormWrapper } from './bulk_edit_form_wrapper'; +import { ScheduleItemField } from '../../../../../rule_creation/components/schedule_item_field'; export interface ScheduleFormData { interval: string; @@ -79,7 +79,7 @@ export const ScheduleForm = ({ rulesCount, onClose, onConfirm }: ScheduleFormCom > ({ newTermsFields: ('new_terms_fields' in rule && rule.new_terms_fields) || [], historyWindowSize: 'history_window_start' in rule && rule.history_window_start - ? convertHistoryStartToSize(rule.history_window_start) - : '7d', + ? convertDateMathToDuration(rule.history_window_start) + : DEFAULT_HISTORY_WINDOW_SIZE, shouldLoadQueryDynamically: Boolean(rule.type === 'saved_query' && rule.saved_id), [ALERT_SUPPRESSION_FIELDS_FIELD_NAME]: ('alert_suppression' in rule && @@ -189,14 +191,6 @@ export const getDefineStepsData = (rule: RuleResponse): DefineStepRule => ({ ), }); -export const convertHistoryStartToSize = (relativeTime: string) => { - if (relativeTime.startsWith('now-')) { - return relativeTime.substring(4); - } else { - return relativeTime; - } -}; - export const getScheduleStepsData = (rule: RuleResponse): ScheduleStepRule => { const { interval, from } = rule; const fromHumanizedValue = getHumanizedDuration(from, interval); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts index cb0570855dab..b12355c10987 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/pages/detection_engine/rules/translations.ts @@ -265,13 +265,13 @@ export const BULK_EDIT_CONFIRMATION_REJECTED_TITLE = (rulesCount: number) => } ); -export const BULK_ACTION_CONFIRMATION_PARTLY_TITLE = (customRulesCount: number) => +export const BULK_ACTION_CONFIRMATION_PARTLY_TITLE = (rulesCount: number) => i18n.translate( 'xpack.securitySolution.detectionEngine.rules.allRules.bulkActions.bulkActionConfirmationPartlyTitle', { - values: { customRulesCount }, + values: { rulesCount }, defaultMessage: - 'This action can only be applied to {customRulesCount, plural, =1 {# custom rule} other {# custom rules}}', + 'This action can only be applied to {rulesCount, plural, =1 {# rule} other {# rules}}', } ); @@ -289,32 +289,30 @@ export const BULK_ACTION_CONFIRMATION_CLOSE = i18n.translate( } ); -export const BULK_EDIT_CONFIRMATION_CONFIRM = (customRulesCount: number) => +export const BULK_EDIT_CONFIRMATION_CONFIRM = (rulesCount: number) => i18n.translate( 'xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkEditConfirmation.confirmButtonLabel', { - values: { customRulesCount }, - defaultMessage: 'Edit {customRulesCount, plural, =1 {# custom rule} other {# custom rules}}', + values: { rulesCount }, + defaultMessage: 'Edit {rulesCount, plural, =1 {# rule} other {# rules}}', } ); -export const BULK_EXPORT_CONFIRMATION_CONFIRM = (customRulesCount: number) => +export const BULK_EXPORT_CONFIRMATION_CONFIRM = (rulesCount: number) => i18n.translate( 'xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkExportConfirmation.confirmButtonLabel', { - values: { customRulesCount }, - defaultMessage: - 'Export {customRulesCount, plural, =1 {# custom rule} other {# custom rules}}', + values: { rulesCount }, + defaultMessage: 'Export {rulesCount, plural, =1 {# rule} other {# rules}}', } ); -export const BULK_MANUAL_RULE_RUN_CONFIRMATION_CONFIRM = (customRulesCount: number) => +export const BULK_MANUAL_RULE_RUN_CONFIRMATION_CONFIRM = (rulesCount: number) => i18n.translate( 'xpack.securitySolution.detectionEngine.components.allRules.bulkActions.bulkManualRuleRunConfirmation.confirmButtonLabel', { - values: { customRulesCount }, - defaultMessage: - 'Schedule {customRulesCount, plural, =1 {# custom rule} other {# custom rules}}', + values: { rulesCount }, + defaultMessage: 'Schedule {rulesCount, plural, =1 {# rule} other {# rules}}', } ); diff --git a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs.test.tsx index 6995656db31a..7ff2a6feb958 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs.test.tsx @@ -49,12 +49,6 @@ const riskScore = { }, }; -const mockUseIsExperimentalFeatureEnabled = jest.fn().mockReturnValue(false); - -jest.mock('../../../../../common/hooks/use_experimental_features', () => ({ - useIsExperimentalFeatureEnabled: () => mockUseIsExperimentalFeatureEnabled(), -})); - const riskScoreWithAssetCriticalityContribution = (contribution: number) => { const score = JSON.parse(JSON.stringify(riskScore)); score.user.risk.category_2_score = contribution; @@ -129,8 +123,7 @@ describe('RiskInputsTab', () => { expect(queryByTestId('risk-input-contexts-title')).toBeInTheDocument(); }); - it('it renders alert preview button when feature flag is enable', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('it renders alert preview button', () => { mockUseRiskScore.mockReturnValue({ loading: false, error: false, @@ -151,28 +144,6 @@ describe('RiskInputsTab', () => { expect(getByTestId(EXPAND_ALERT_TEST_ID)).toBeInTheDocument(); }); - it('it does not render alert preview button when feature flag is disable', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); - mockUseRiskScore.mockReturnValue({ - loading: false, - error: false, - data: [riskScore], - }); - mockUseRiskContributingAlerts.mockReturnValue({ - loading: false, - error: false, - data: [alertInputDataMock], - }); - - const { queryByTestId } = render( - - - - ); - - expect(queryByTestId(EXPAND_ALERT_TEST_ID)).not.toBeInTheDocument(); - }); - it('Displays 0.00 for the asset criticality contribution if the contribution value is less than -0.01', () => { mockUseUiSetting.mockReturnValue([true]); diff --git a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs_tab.tsx b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs_tab.tsx index 78010434ee59..72a6af0fe768 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs_tab.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_details_flyout/tabs/risk_inputs/risk_inputs_tab.tsx @@ -14,7 +14,6 @@ import { ALERT_RULE_NAME } from '@kbn/rule-data-utils'; import { get } from 'lodash/fp'; import { AlertPreviewButton } from '../../../../../flyout/shared/components/alert_preview_button'; -import { useIsExperimentalFeatureEnabled } from '../../../../../common/hooks/use_experimental_features'; import { useGlobalTime } from '../../../../../common/containers/use_global_time'; import { useQueryInspector } from '../../../../../common/components/page/manage_query'; import { formatRiskScore } from '../../../../common'; @@ -98,26 +97,20 @@ export const RiskInputsTab = ({ entityType, entityName, scopeId }: RiskInputsTab }), [] ); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); const inputColumns: Array> = useMemo( () => [ - ...(isPreviewEnabled - ? [ - { - render: (data: InputAlert) => ( - - ), - width: '5%', - }, - ] - : []), - + { + render: (data: InputAlert) => ( + + ), + width: '5%', + }, { name: ( describe('CorrelationsDetailsAlertsTable', () => { beforeEach(() => { jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); jest.mocked(usePaginatedAlerts).mockReturnValue({ setPagination: jest.fn(), setSorting: jest.fn(), @@ -88,16 +84,16 @@ describe('CorrelationsDetailsAlertsTable', () => { }); it('renders EuiBasicTable with correct props', () => { - const { getByTestId, queryByTestId, queryAllByRole } = + const { getByTestId, getAllByTestId, queryAllByRole } = renderCorrelationsTable(mockContextValue); expect(getByTestId(`${TEST_ID}InvestigateInTimeline`)).toBeInTheDocument(); expect(getByTestId(`${TEST_ID}Table`)).toBeInTheDocument(); - expect(queryByTestId(`${TEST_ID}AlertPreviewButton`)).not.toBeInTheDocument(); + expect(getAllByTestId(`${TEST_ID}AlertPreviewButton`)).toHaveLength(2); expect(jest.mocked(usePaginatedAlerts)).toHaveBeenCalled(); - expect(queryAllByRole('columnheader').length).toBe(4); + expect(queryAllByRole('columnheader').length).toBe(5); expect(queryAllByRole('row').length).toBe(3); // 1 header row and 2 data rows expect(queryAllByRole('row')[1].textContent).toContain('Jan 1, 2022 @ 00:00:00.000'); expect(queryAllByRole('row')[1].textContent).toContain('Reason1'); @@ -105,8 +101,7 @@ describe('CorrelationsDetailsAlertsTable', () => { expect(queryAllByRole('row')[1].textContent).toContain('Severity1'); }); - it('renders open preview button when feature flag is on', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('renders open preview button', () => { const { getByTestId, getAllByTestId } = renderCorrelationsTable({ ...mockContextValue, isPreviewMode: true, @@ -128,8 +123,7 @@ describe('CorrelationsDetailsAlertsTable', () => { }); }); - it('opens rule preview when feature flag is on and isPreview is false', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('opens rule preview when isPreview is false', () => { const { getAllByTestId } = renderCorrelationsTable(mockContextValue); expect(getAllByTestId(`${TEST_ID}RulePreview`).length).toBe(2); @@ -145,8 +139,7 @@ describe('CorrelationsDetailsAlertsTable', () => { }); }); - it('does not render preview link when feature flag is on and isPreview is true', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('does not render preview link when isPreview is true', () => { const { queryByTestId } = renderCorrelationsTable({ ...mockContextValue, isPreview: true }); expect(queryByTestId(`${TEST_ID}RulePreview`)).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/correlations_details_alerts_table.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/correlations_details_alerts_table.tsx index d8497ca984ea..4d757b46edb2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/correlations_details_alerts_table.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/correlations_details_alerts_table.tsx @@ -14,7 +14,6 @@ import { isRight } from 'fp-ts/lib/Either'; import { ALERT_REASON, ALERT_RULE_NAME } from '@kbn/rule-data-utils'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { CellTooltipWrapper } from '../../shared/components/cell_tooltip_wrapper'; import type { DataProvider } from '../../../../../common/types'; import { SeverityBadge } from '../../../../common/components/severity_badge'; @@ -82,8 +81,6 @@ export const CorrelationsDetailsAlertsTable: FC [ - ...(isPreviewEnabled - ? [ - { - render: (row: Record) => ( - - ), - width: '5%', - }, - ] - : []), + { + render: (row: Record) => ( + + ), + width: '5%', + }, { field: '@timestamp', name: ( @@ -176,20 +169,16 @@ export const CorrelationsDetailsAlertsTable: FC - {isPreviewEnabled ? ( - - {ruleName} - - ) : ( + {ruleName} - )} + ); }, @@ -229,7 +218,7 @@ export const CorrelationsDetailsAlertsTable: FC { const dataView = useGetScopedSourcererDataView({ sourcererScope: SourcererScopeName.default, }); - const { getFieldsData, dataAsNestedObject } = useDocumentDetailsContext(); - const { eventIds, timestamp } = useGraphPreview({ + const { getFieldsData, dataAsNestedObject, dataFormattedForFieldBrowser } = + useDocumentDetailsContext(); + const { + eventIds, + timestamp = new Date().toISOString(), + isAlert, + } = useGraphPreview({ getFieldsData, ecsData: dataAsNestedObject, + dataFormattedForFieldBrowser, }); + const originEventIds = eventIds.map((id) => ({ id, isAlert })); + return (
    { > {dataView && ( }> - + )}
    diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.test.tsx index e08a79466522..86d04a9c94a7 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.test.tsx @@ -17,7 +17,6 @@ import { useMlCapabilities } from '../../../../common/components/ml/hooks/use_ml import { mockAnomalies } from '../../../../common/components/ml/mock'; import { useHostDetails } from '../../../../explore/hosts/containers/hosts/details'; import { useHostRelatedUsers } from '../../../../common/containers/related_entities/related_users'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { RiskSeverity } from '../../../../../common/search_strategy'; import { HOST_DETAILS_TEST_ID, @@ -46,9 +45,6 @@ jest.mock('@kbn/expandable-flyout'); jest.mock('@kbn/cloud-security-posture/src/hooks/use_misconfiguration_preview'); jest.mock('@kbn/cloud-security-posture/src/hooks/use_vulnerabilities_preview'); -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - jest.mock('react-router-dom', () => { const actual = jest.requireActual('react-router-dom'); return { ...actual, useLocation: jest.fn().mockReturnValue({ pathname: '' }) }; @@ -180,20 +176,18 @@ describe('', () => { mockUseHostDetails.mockReturnValue(mockHostDetailsResponse); mockUseRiskScore.mockReturnValue(mockRiskScoreResponse); mockUseHostsRelatedUsers.mockReturnValue(mockRelatedUsersResponse); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); (useMisconfigurationPreview as jest.Mock).mockReturnValue({}); (useVulnerabilitiesPreview as jest.Mock).mockReturnValue({}); (useAlertsByStatus as jest.Mock).mockReturnValue({ isLoading: false, items: {} }); }); it('should render host details correctly', () => { - const { getByTestId, queryByTestId } = renderHostDetails(mockContextValue); + const { getByTestId } = renderHostDetails(mockContextValue); expect(getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(HOST_DETAILS_TEST_ID))).toBeInTheDocument(); - expect(queryByTestId(HOST_DETAILS_LINK_TEST_ID)).not.toBeInTheDocument(); + expect(getByTestId(HOST_DETAILS_LINK_TEST_ID)).toBeInTheDocument(); }); - it('should render host name as clicable link when preview is not disabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should render host name as clicable link', () => { const { getByTestId } = renderHostDetails(mockContextValue); expect(getByTestId(HOST_DETAILS_LINK_TEST_ID)).toBeInTheDocument(); @@ -242,7 +236,7 @@ describe('', () => { describe('Related users', () => { it('should render the related user table with correct dates and indices', () => { - const { getByTestId, queryByTestId } = renderHostDetails(mockContextValue); + const { getByTestId } = renderHostDetails(mockContextValue); expect(mockUseHostsRelatedUsers).toBeCalledWith({ from: timestamp, hostName: 'test host', @@ -250,7 +244,7 @@ describe('', () => { skip: false, }); expect(getByTestId(HOST_DETAILS_RELATED_USERS_TABLE_TEST_ID)).toBeInTheDocument(); - expect(queryByTestId(HOST_DETAILS_RELATED_USERS_LINK_TEST_ID)).not.toBeInTheDocument(); + expect(getByTestId(HOST_DETAILS_RELATED_USERS_LINK_TEST_ID)).toBeInTheDocument(); }); it('should render user risk score column when license and capabilities are valid', () => { @@ -296,8 +290,7 @@ describe('', () => { ); }); - it('should render user name as clicable link when preview is not disabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should render user name as clicable link', () => { const { getAllByTestId } = renderHostDetails(mockContextValue); expect(getAllByTestId(HOST_DETAILS_RELATED_USERS_LINK_TEST_ID).length).toBe(1); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.tsx index e3fd2fef8bc6..9555860a329b 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/host_details.tsx @@ -25,14 +25,12 @@ import type { EuiBasicTableColumn } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { ExpandablePanel } from '../../../shared/components/expandable_panel'; import type { RelatedUser } from '../../../../../common/search_strategy/security_solution/related_entities/related_users'; import type { RiskSeverity } from '../../../../../common/search_strategy'; import { HostOverview } from '../../../../overview/components/host_overview'; import { AnomalyTableProvider } from '../../../../common/components/ml/anomaly/anomaly_table_provider'; import { InspectButton, InspectButtonContainer } from '../../../../common/components/inspect'; -import { NetworkDetailsLink } from '../../../../common/components/links'; import { RiskScoreEntity } from '../../../../../common/search_strategy'; import { RiskScoreLevel } from '../../../../entity_analytics/components/severity/common'; import { DefaultFieldRenderer } from '../../../../timelines/components/field_renderers/default_renderer'; @@ -110,7 +108,6 @@ export const HostDetails: React.FC = ({ hostName, timestamp, s const isEntityAnalyticsAuthorized = isPlatinumOrTrialLicense && hasEntityAnalyticsCapability; const { openPreviewPanel } = useExpandableFlyoutApi(); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); const narrowDateRange = useCallback( (score, interval) => { @@ -176,16 +173,12 @@ export const HostDetails: React.FC = ({ hostName, timestamp, s render: (user: string) => ( - {isPreviewEnabled ? ( - - ) : ( - <>{user} - )} + ), @@ -208,15 +201,13 @@ export const HostDetails: React.FC = ({ hostName, timestamp, s render={(ip) => ip == null ? ( getEmptyTagValue() - ) : isPreviewEnabled ? ( + ) : ( - ) : ( - ) } scopeId={scopeId} @@ -242,7 +233,7 @@ export const HostDetails: React.FC = ({ hostName, timestamp, s ] : []), ], - [isEntityAnalyticsAuthorized, scopeId, isPreviewEnabled] + [isEntityAnalyticsAuthorized, scopeId] ); const relatedUsersCount = useMemo( @@ -273,19 +264,14 @@ export const HostDetails: React.FC = ({ hostName, timestamp, s }; const hostLink = useMemo( - () => - isPreviewEnabled - ? { - callback: openHostPreview, - tooltip: i18n.translate( - 'xpack.securitySolution.flyout.left.insights.entities.host.hostPreviewTitle', - { - defaultMessage: 'Preview host', - } - ), - } - : undefined, - [isPreviewEnabled, openHostPreview] + () => ({ + callback: openHostPreview, + tooltip: i18n.translate( + 'xpack.securitySolution.flyout.left.insights.entities.host.hostPreviewTitle', + { defaultMessage: 'Preview host' } + ), + }), + [openHostPreview] ); return ( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.test.tsx index e8b1b71e9cd0..e0bef746b213 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.test.tsx @@ -24,7 +24,6 @@ import { import { usePrevalence } from '../../shared/hooks/use_prevalence'; import { TestProviders } from '../../../../common/mock'; import { licenseService } from '../../../../common/hooks/use_license'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { mockFlyoutApi } from '../../shared/mocks/mock_flyout_context'; import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; import { HostPreviewPanelKey } from '../../../entity_details/host_right'; @@ -46,9 +45,6 @@ jest.mock('../../../../common/lib/kibana', () => { }; }); -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - jest.mock('../../shared/hooks/use_prevalence'); const mockDispatch = jest.fn(); @@ -138,7 +134,6 @@ describe('PrevalenceDetails', () => { jest.clearAllMocks(); licenseServiceMock.isPlatinumPlus.mockReturnValue(true); jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); }); it('should render the table with all data if license is platinum', () => { @@ -162,13 +157,10 @@ describe('PrevalenceDetails', () => { ).toBeGreaterThan(1); expect(queryByTestId(PREVALENCE_DETAILS_UPSELL_TEST_ID)).not.toBeInTheDocument(); expect(queryByText(NO_DATA_MESSAGE)).not.toBeInTheDocument(); - expect( - queryByTestId(PREVALENCE_DETAILS_TABLE_PREVIEW_LINK_CELL_TEST_ID) - ).not.toBeInTheDocument(); + expect(getAllByTestId(PREVALENCE_DETAILS_TABLE_PREVIEW_LINK_CELL_TEST_ID)).toHaveLength(2); }); - it('should render host and user name as clickable link if preview is enabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should render host and user name as clickable link', () => { (usePrevalence as jest.Mock).mockReturnValue(mockPrevelanceReturnValue); const { getAllByTestId } = renderPrevalenceDetails(); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.tsx index 6491bc9ad274..77ab6eb66df3 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/prevalence_details.tsx @@ -22,7 +22,6 @@ import { useEuiTheme, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { FormattedCount } from '../../../../common/components/formatted_number'; import { useLicense } from '../../../../common/hooks/use_license'; import { InvestigateInTimelineButton } from '../../../../common/components/event_details/investigate_in_timeline_button'; @@ -81,10 +80,6 @@ interface PrevalenceDetailsRow extends PrevalenceData { * License to drive the rendering of the last 2 prevalence columns */ isPlatinumPlus: boolean; - /** - * If enabled, clicking host or user should open an entity preview - */ - isPreviewEnabled: boolean; /** * Scope id to pass to the preview link */ @@ -115,7 +110,7 @@ const columns: Array> = [ render: (data: PrevalenceDetailsRow) => ( {data.values.map((value) => { - if (data.isPreviewEnabled && hasPreview(data.field)) { + if (hasPreview(data.field)) { return ( @@ -331,7 +326,6 @@ export const PrevalenceDetails: React.FC = () => { useDocumentDetailsContext(); const isPlatinumPlus = useLicense().isPlatinumPlus(); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); // these two are used by the usePrevalence hook to fetch the data const [start, setStart] = useState(DEFAULT_FROM); @@ -382,10 +376,9 @@ export const PrevalenceDetails: React.FC = () => { from: absoluteStart, to: absoluteEnd, isPlatinumPlus, - isPreviewEnabled, scopeId, })), - [data, absoluteStart, absoluteEnd, isPlatinumPlus, isPreviewEnabled, scopeId] + [data, absoluteStart, absoluteEnd, isPlatinumPlus, scopeId] ); const upsell = ( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.test.tsx index 5bfb8a7df50d..993e9101ba0f 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.test.tsx @@ -16,7 +16,6 @@ import { useMlCapabilities } from '../../../../common/components/ml/hooks/use_ml import { mockAnomalies } from '../../../../common/components/ml/mock'; import { useObservedUserDetails } from '../../../../explore/users/containers/users/observed_details'; import { useUserRelatedHosts } from '../../../../common/containers/related_entities/related_hosts'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { RiskSeverity } from '../../../../../common/search_strategy'; import { USER_DETAILS_TEST_ID, @@ -43,9 +42,6 @@ import { useAlertsByStatus } from '../../../../overview/components/detection_res jest.mock('@kbn/expandable-flyout'); jest.mock('@kbn/cloud-security-posture/src/hooks/use_misconfiguration_preview'); -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - jest.mock('react-router-dom', () => { const actual = jest.requireActual('react-router-dom'); return { ...actual, useLocation: jest.fn().mockReturnValue({ pathname: '' }) }; @@ -174,19 +170,17 @@ describe('', () => { mockUseObservedUserDetails.mockReturnValue(mockUserDetailsResponse); mockUseRiskScore.mockReturnValue(mockRiskScoreResponse); mockUseUsersRelatedHosts.mockReturnValue(mockRelatedHostsResponse); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); (useMisconfigurationPreview as jest.Mock).mockReturnValue({}); (useAlertsByStatus as jest.Mock).mockReturnValue({ isLoading: false, items: {} }); }); it('should render user details correctly', () => { - const { getByTestId, queryByTestId } = renderUserDetails(mockContextValue); + const { getByTestId } = renderUserDetails(mockContextValue); expect(getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(USER_DETAILS_TEST_ID))).toBeInTheDocument(); - expect(queryByTestId(USER_DETAILS_LINK_TEST_ID)).not.toBeInTheDocument(); + expect(getByTestId(USER_DETAILS_LINK_TEST_ID)).toBeInTheDocument(); }); - it('should render user name as clicable link when feature flag is true', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should render user name as clicable link', () => { const { getByTestId } = renderUserDetails(mockContextValue); expect(getByTestId(USER_DETAILS_LINK_TEST_ID)).toBeInTheDocument(); @@ -233,7 +227,7 @@ describe('', () => { describe('Related hosts', () => { it('should render the related host table with correct dates and indices', () => { - const { getByTestId, queryByTestId } = renderUserDetails(mockContextValue); + const { getByTestId } = renderUserDetails(mockContextValue); expect(mockUseUsersRelatedHosts).toBeCalledWith({ from: timestamp, userName: 'test user', @@ -241,7 +235,7 @@ describe('', () => { skip: false, }); expect(getByTestId(USER_DETAILS_RELATED_HOSTS_TABLE_TEST_ID)).toBeInTheDocument(); - expect(queryByTestId(USER_DETAILS_RELATED_HOSTS_LINK_TEST_ID)).not.toBeInTheDocument(); + expect(getByTestId(USER_DETAILS_RELATED_HOSTS_LINK_TEST_ID)).toBeInTheDocument(); }); it('should render host risk score column when license is valid', () => { @@ -274,8 +268,7 @@ describe('', () => { ); }); - it('should render host name and ip as clicable link when preview is enabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should render host name and ip as clicable link', () => { const { getAllByTestId } = renderUserDetails(mockContextValue); expect(getAllByTestId(USER_DETAILS_RELATED_HOSTS_LINK_TEST_ID).length).toBe(1); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.tsx index e88cbb54f947..00366a367a81 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/components/user_details.tsx @@ -25,14 +25,12 @@ import type { EuiBasicTableColumn } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { ExpandablePanel } from '../../../shared/components/expandable_panel'; import type { RelatedHost } from '../../../../../common/search_strategy/security_solution/related_entities/related_hosts'; import type { RiskSeverity } from '../../../../../common/search_strategy'; import { UserOverview } from '../../../../overview/components/user_overview'; import { AnomalyTableProvider } from '../../../../common/components/ml/anomaly/anomaly_table_provider'; import { InspectButton, InspectButtonContainer } from '../../../../common/components/inspect'; -import { NetworkDetailsLink } from '../../../../common/components/links'; import { RiskScoreEntity } from '../../../../../common/search_strategy'; import { RiskScoreLevel } from '../../../../entity_analytics/components/severity/common'; import { DefaultFieldRenderer } from '../../../../timelines/components/field_renderers/default_renderer'; @@ -109,7 +107,6 @@ export const UserDetails: React.FC = ({ userName, timestamp, s const isEntityAnalyticsAuthorized = isPlatinumOrTrialLicense && hasEntityAnalyticsCapability; const { openPreviewPanel } = useExpandableFlyoutApi(); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); const narrowDateRange = useCallback( (score, interval) => { @@ -175,16 +172,12 @@ export const UserDetails: React.FC = ({ userName, timestamp, s render: (host: string) => ( - {isPreviewEnabled ? ( - - ) : ( - <>{host} - )} + ), @@ -207,15 +200,13 @@ export const UserDetails: React.FC = ({ userName, timestamp, s render={(ip) => ip == null ? ( getEmptyTagValue() - ) : isPreviewEnabled ? ( + ) : ( - ) : ( - ) } scopeId={scopeId} @@ -241,7 +232,7 @@ export const UserDetails: React.FC = ({ userName, timestamp, s ] : []), ], - [isEntityAnalyticsAuthorized, scopeId, isPreviewEnabled] + [isEntityAnalyticsAuthorized, scopeId] ); const relatedHostsCount = useMemo( @@ -272,19 +263,14 @@ export const UserDetails: React.FC = ({ userName, timestamp, s }; const userLink = useMemo( - () => - isPreviewEnabled - ? { - callback: openUserPreview, - tooltip: i18n.translate( - 'xpack.securitySolution.flyout.left.insights.entities.user.userPreviewTitle', - { - defaultMessage: 'Preview user', - } - ), - } - : undefined, - [isPreviewEnabled, openUserPreview] + () => ({ + callback: openUserPreview, + tooltip: i18n.translate( + 'xpack.securitySolution.flyout.left.insights.entities.user.userPreviewTitle', + { defaultMessage: 'Preview user' } + ), + }), + [openUserPreview] ); return ( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/tabs/visualize_tab.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/tabs/visualize_tab.tsx index 89e00e06e3a4..1a8e5906e247 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/tabs/visualize_tab.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/left/tabs/visualize_tab.tsx @@ -88,7 +88,8 @@ const graphVisualizationButton: EuiButtonGroupOptionProps = { * Visualize view displayed in the document details expandable flyout left section */ export const VisualizeTab = memo(() => { - const { scopeId, getFieldsData, dataAsNestedObject } = useDocumentDetailsContext(); + const { scopeId, getFieldsData, dataAsNestedObject, dataFormattedForFieldBrowser } = + useDocumentDetailsContext(); const { openPreviewPanel } = useExpandableFlyoutApi(); const panels = useExpandableFlyoutState(); const [activeVisualizationId, setActiveVisualizationId] = useState( @@ -123,6 +124,7 @@ export const VisualizeTab = memo(() => { const { hasGraphRepresentation } = useGraphPreview({ getFieldsData, ecsData: dataAsNestedObject, + dataFormattedForFieldBrowser, }); const isGraphFeatureEnabled = useIsExperimentalFeatureEnabled( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.test.tsx index c805f2a3c67a..9965c5300e71 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.test.tsx @@ -86,6 +86,7 @@ describe('', () => { timestamp, eventIds: [], hasGraphRepresentation: true, + isAlert: true, }); const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview(); @@ -111,7 +112,109 @@ describe('', () => { expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ req: { query: { - eventIds: [], + originEventIds: [], + start: `${timestamp}||-30m`, + end: `${timestamp}||+30m`, + }, + }, + options: { + enabled: true, + refetchOnWindowFocus: false, + }, + }); + }); + + it('should render component for alert', async () => { + mockUseFetchGraphData.mockReturnValue({ + isLoading: false, + isError: false, + data: { nodes: DEFAULT_NODES, edges: [] }, + }); + + const timestamp = new Date().toISOString(); + + (useGraphPreview as jest.Mock).mockReturnValue({ + timestamp, + eventIds: ['eventId'], + isAlert: true, + hasGraphRepresentation: true, + }); + + const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview(); + + // Using findByTestId to wait for the component to be rendered because it is a lazy loaded component + expect(await findByTestId(GRAPH_PREVIEW_TEST_ID)).toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_HEADER_TITLE_LINK_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + queryByTestId(EXPANDABLE_PANEL_TOGGLE_ICON_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).not.toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_HEADER_TITLE_ICON_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + queryByTestId(EXPANDABLE_PANEL_HEADER_TITLE_TEXT_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).not.toBeInTheDocument(); + expect(mockUseFetchGraphData).toHaveBeenCalled(); + expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ + req: { + query: { + originEventIds: [{ id: 'eventId', isAlert: true }], + start: `${timestamp}||-30m`, + end: `${timestamp}||+30m`, + }, + }, + options: { + enabled: true, + refetchOnWindowFocus: false, + }, + }); + }); + + it('should render component for event', async () => { + mockUseFetchGraphData.mockReturnValue({ + isLoading: false, + isError: false, + data: { nodes: DEFAULT_NODES, edges: [] }, + }); + + const timestamp = new Date().toISOString(); + + (useGraphPreview as jest.Mock).mockReturnValue({ + timestamp, + eventIds: ['eventId'], + isAlert: false, + hasGraphRepresentation: true, + }); + + const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview(); + + // Using findByTestId to wait for the component to be rendered because it is a lazy loaded component + expect(await findByTestId(GRAPH_PREVIEW_TEST_ID)).toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_HEADER_TITLE_LINK_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + queryByTestId(EXPANDABLE_PANEL_TOGGLE_ICON_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).not.toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_HEADER_TITLE_ICON_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).toBeInTheDocument(); + expect( + queryByTestId(EXPANDABLE_PANEL_HEADER_TITLE_TEXT_TEST_ID(GRAPH_PREVIEW_TEST_ID)) + ).not.toBeInTheDocument(); + expect(mockUseFetchGraphData).toHaveBeenCalled(); + expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ + req: { + query: { + originEventIds: [{ id: 'eventId', isAlert: false }], start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, @@ -136,6 +239,7 @@ describe('', () => { timestamp, eventIds: [], hasGraphRepresentation: true, + isAlert: true, }); const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview({ @@ -164,7 +268,7 @@ describe('', () => { expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ req: { query: { - eventIds: [], + originEventIds: [], start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, @@ -189,6 +293,7 @@ describe('', () => { timestamp, eventIds: [], hasGraphRepresentation: true, + isAlert: true, }); const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview({ @@ -217,7 +322,7 @@ describe('', () => { expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ req: { query: { - eventIds: [], + originEventIds: [], start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, @@ -243,6 +348,7 @@ describe('', () => { timestamp, eventIds: [], hasGraphRepresentation: true, + isAlert: true, }); const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview(); @@ -268,7 +374,7 @@ describe('', () => { expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ req: { query: { - eventIds: [], + originEventIds: [], start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, @@ -293,6 +399,7 @@ describe('', () => { timestamp, eventIds: [], hasGraphRepresentation: false, + isAlert: true, }); const { getByTestId, queryByTestId, findByTestId } = renderGraphPreview(); @@ -320,7 +427,7 @@ describe('', () => { expect(mockUseFetchGraphData.mock.calls[0][0]).toEqual({ req: { query: { - eventIds: [], + originEventIds: [], start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.tsx index 90a021877854..b4626f93e823 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/graph_preview_container.tsx @@ -31,6 +31,7 @@ export const GraphPreviewContainer: React.FC = () => { scopeId, isPreview, isPreviewMode, + dataFormattedForFieldBrowser, } = useDocumentDetailsContext(); const [visualizationInFlyoutEnabled] = useUiSetting$( @@ -49,16 +50,18 @@ export const GraphPreviewContainer: React.FC = () => { eventIds, timestamp = new Date().toISOString(), hasGraphRepresentation, + isAlert, } = useGraphPreview({ getFieldsData, ecsData: dataAsNestedObject, + dataFormattedForFieldBrowser, }); // TODO: default start and end might not capture the original event const { isLoading, isError, data } = useFetchGraphData({ req: { query: { - eventIds, + originEventIds: eventIds.map((id) => ({ id, isAlert })), start: `${timestamp}||-30m`, end: `${timestamp}||+30m`, }, diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.test.tsx index ff003813f260..e6f88498b260 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.test.tsx @@ -14,11 +14,7 @@ import { } from './test_ids'; import { HighlightedFieldsCell } from './highlighted_fields_cell'; import { DocumentDetailsContext } from '../../shared/context'; -import { DocumentDetailsLeftPanelKey } from '../../shared/constants/panel_keys'; -import { LeftPanelInsightsTab } from '../../left'; import { TestProviders } from '../../../../common/mock'; -import { ENTITIES_TAB_ID } from '../../left/components/entities_details'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { useGetAgentStatus } from '../../../../management/hooks/agents/use_get_agent_status'; import { mockFlyoutApi } from '../../shared/mocks/mock_flyout_context'; import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; @@ -47,9 +43,6 @@ jest.mock('../../../../common/lib/kibana', () => { const useGetAgentStatusMock = useGetAgentStatus as jest.Mock; -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - const panelContextValue = { eventId: 'event id', indexName: 'indexName', @@ -68,7 +61,6 @@ const renderHighlightedFieldsCell = (values: string[], field: string) => describe('', () => { beforeAll(() => { jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); }); it('should render a basic cell', () => { @@ -83,23 +75,7 @@ describe('', () => { expect(getByTestId(HIGHLIGHTED_FIELDS_BASIC_CELL_TEST_ID)).toBeInTheDocument(); }); - it('should open left panel when clicking on the link within a a link cell when preview is disabled', () => { - const { getByTestId } = renderHighlightedFieldsCell(['value'], 'user.name'); - - getByTestId(HIGHLIGHTED_FIELDS_LINKED_CELL_TEST_ID).click(); - expect(mockFlyoutApi.openLeftPanel).toHaveBeenCalledWith({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: panelContextValue.eventId, - indexName: panelContextValue.indexName, - scopeId: panelContextValue.scopeId, - }, - }); - }); - - it('should open host preview when click on host when preview is not disabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should open host preview when click on host', () => { const { getByTestId } = renderHighlightedFieldsCell(['test host'], 'host.name'); expect(getByTestId(HIGHLIGHTED_FIELDS_LINKED_CELL_TEST_ID)).toBeInTheDocument(); @@ -114,8 +90,7 @@ describe('', () => { }); }); - it('should open user preview when click on user when preview is not disabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should open user preview when click on user', () => { const { getByTestId } = renderHighlightedFieldsCell(['test user'], 'user.name'); expect(getByTestId(HIGHLIGHTED_FIELDS_LINKED_CELL_TEST_ID)).toBeInTheDocument(); @@ -130,8 +105,7 @@ describe('', () => { }); }); - it('should open ip preview when click on ip when preview is not disabled', () => { - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); + it('should open ip preview when click on ip', () => { const { getByTestId } = renderHighlightedFieldsCell(['100:XXX:XXX'], 'source.ip'); expect(getByTestId(HIGHLIGHTED_FIELDS_LINKED_CELL_TEST_ID)).toBeInTheDocument(); @@ -204,6 +178,7 @@ describe('', () => { expect(getByTestId(HIGHLIGHTED_FIELDS_AGENT_STATUS_CELL_TEST_ID)).toBeInTheDocument(); }); + it('should not render if values is null', () => { const { container } = render( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.tsx index e11dee4a74ad..b6fc98653f89 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/highlighted_fields_cell.tsx @@ -5,19 +5,14 @@ * 2.0. */ -import type { VFC } from 'react'; -import React, { useCallback, useMemo } from 'react'; -import { EuiFlexItem, EuiLink } from '@elastic/eui'; -import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; +import type { FC } from 'react'; +import React, { useMemo } from 'react'; +import { EuiFlexItem } from '@elastic/eui'; import { getAgentTypeForAgentIdField } from '../../../../common/lib/endpoint/utils/get_agent_type_for_agent_id_field'; import type { ResponseActionAgentType } from '../../../../../common/endpoint/service/response_actions/constants'; import { AgentStatus } from '../../../../common/components/endpoint/agents/agent_status'; import { useDocumentDetailsContext } from '../../shared/context'; import { AGENT_STATUS_FIELD_NAME } from '../../../../timelines/components/timeline/body/renderers/constants'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; -import { DocumentDetailsLeftPanelKey } from '../../shared/constants/panel_keys'; -import { LeftPanelInsightsTab } from '../../left'; -import { ENTITIES_TAB_ID } from '../../left/components/entities_details'; import { HIGHLIGHTED_FIELDS_AGENT_STATUS_CELL_TEST_ID, HIGHLIGHTED_FIELDS_BASIC_CELL_TEST_ID, @@ -44,26 +39,12 @@ export interface HighlightedFieldsCellProps { /** * Renders a component in the highlighted fields table cell based on the field name */ -export const HighlightedFieldsCell: VFC = ({ +export const HighlightedFieldsCell: FC = ({ values, field, originalField = '', }) => { - const { scopeId, eventId, indexName } = useDocumentDetailsContext(); - const { openLeftPanel } = useExpandableFlyoutApi(); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); - - const goToInsightsEntities = useCallback(() => { - openLeftPanel({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: eventId, - indexName, - scopeId, - }, - }); - }, [eventId, indexName, openLeftPanel, scopeId]); + const { scopeId } = useDocumentDetailsContext(); const agentType: ResponseActionAgentType = useMemo(() => { return getAgentTypeForAgentIdField(originalField); @@ -79,20 +60,13 @@ export const HighlightedFieldsCell: VFC = ({ key={`${i}-${value}`} data-test-subj={`${value}-${HIGHLIGHTED_FIELDS_CELL_TEST_ID}`} > - {isPreviewEnabled && hasPreview(field) ? ( + {hasPreview(field) ? ( - ) : hasPreview(field) ? ( - - {value} - ) : field === AGENT_STATUS_FIELD_NAME ? ( { }; }); -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - const mockUseGlobalTime = jest.fn().mockReturnValue({ from, to }); jest.mock('../../../../common/containers/use_global_time', () => { return { @@ -124,7 +117,6 @@ const renderHostEntityContent = () => describe('', () => { beforeAll(() => { jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); (useMisconfigurationPreview as jest.Mock).mockReturnValue({}); (useVulnerabilitiesPreview as jest.Mock).mockReturnValue({}); (useAlertsByStatus as jest.Mock).mockReturnValue({ isLoading: false, items: {} }); @@ -204,28 +196,9 @@ describe('', () => { expect(getByTestId(ENTITIES_HOST_OVERVIEW_LAST_SEEN_TEST_ID)).toHaveTextContent('—'); }); - it('should navigate to left panel entities tab when clicking on title when feature flag is off', () => { - mockUseHostDetails.mockReturnValue([false, { hostDetails: hostData }]); - mockUseRiskScore.mockReturnValue({ data: riskLevel, isAuthorized: true }); - - const { getByTestId } = renderHostEntityContent(); - - getByTestId(ENTITIES_HOST_OVERVIEW_LINK_TEST_ID).click(); - expect(mockFlyoutApi.openLeftPanel).toHaveBeenCalledWith({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: panelContextValue.eventId, - indexName: panelContextValue.indexName, - scopeId: panelContextValue.scopeId, - }, - }); - }); - - it('should open host preview when clicking on title when feature flag is on', () => { + it('should open host preview when clicking on title', () => { mockUseHostDetails.mockReturnValue([false, { hostDetails: hostData }]); mockUseRiskScore.mockReturnValue({ data: riskLevel, isAuthorized: true }); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); const { getByTestId } = renderHostEntityContent(); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/host_entity_overview.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/host_entity_overview.tsx index 9b60eefbb5f6..eb1ca093fbb0 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/host_entity_overview.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/host_entity_overview.tsx @@ -5,11 +5,10 @@ * 2.0. */ -import React, { useCallback, useMemo } from 'react'; +import React, { useMemo } from 'react'; import { EuiFlexGroup, EuiFlexItem, - EuiLink, EuiText, EuiIcon, useEuiTheme, @@ -19,8 +18,6 @@ import { import { css } from '@emotion/css'; import { getOr } from 'lodash/fp'; import { i18n } from '@kbn/i18n'; -import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { HOST_NAME_FIELD_NAME } from '../../../../timelines/components/timeline/body/renderers/constants'; import { useRiskScore } from '../../../../entity_analytics/api/hooks/use_risk_score'; import { useDocumentDetailsContext } from '../../shared/context'; @@ -44,7 +41,6 @@ import { LAST_SEEN, HOST_RISK_LEVEL, } from '../../../../overview/components/host_overview/translations'; -import { ENTITIES_TAB_ID } from '../../left/components/entities_details'; import { ENTITIES_HOST_OVERVIEW_TEST_ID, ENTITIES_HOST_OVERVIEW_OS_FAMILY_TEST_ID, @@ -56,8 +52,6 @@ import { ENTITIES_HOST_OVERVIEW_MISCONFIGURATIONS_TEST_ID, ENTITIES_HOST_OVERVIEW_VULNERABILITIES_TEST_ID, } from './test_ids'; -import { DocumentDetailsLeftPanelKey } from '../../shared/constants/panel_keys'; -import { LeftPanelInsightsTab } from '../../left'; import { RiskScoreDocTooltip } from '../../../../overview/components/common'; import { PreviewLink } from '../../../shared/components/preview_link'; import { MisconfigurationsInsight } from '../../shared/components/misconfiguration_insight'; @@ -85,21 +79,7 @@ export const HOST_PREVIEW_BANNER = { * Host preview content for the entities preview in right flyout. It contains ip addresses and risk level */ export const HostEntityOverview: React.FC = ({ hostName }) => { - const { eventId, indexName, scopeId } = useDocumentDetailsContext(); - const { openLeftPanel } = useExpandableFlyoutApi(); - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); - - const goToEntitiesTab = useCallback(() => { - openLeftPanel({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: eventId, - indexName, - scopeId, - }, - }); - }, [eventId, openLeftPanel, indexName, scopeId]); + const { scopeId } = useDocumentDetailsContext(); const { from, to } = useGlobalTime(); const { selectedPatterns } = useSourcererDataView(); @@ -212,34 +192,21 @@ export const HostEntityOverview: React.FC = ({ hostName - {isPreviewEnabled ? ( - - - {hostName} - - - ) : ( - + {hostName} - - )} + + diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.test.tsx index eec53dbe3d26..2c7abe5bb1d2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.test.tsx @@ -9,7 +9,6 @@ import { render, screen } from '@testing-library/react'; import React from 'react'; import type { FieldSpec } from '@kbn/data-plugin/common'; import { DocumentDetailsContext } from '../../shared/context'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; import type { EventFieldsData } from '../../../../common/components/event_details/types'; import { TableFieldValueCell } from './table_field_value_cell'; @@ -35,9 +34,6 @@ jest.mock('../../../../common/lib/kibana', () => { }; }); -jest.mock('../../../../common/hooks/use_experimental_features'); -const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock; - const panelContextValue = { eventId: 'event id', indexName: 'indexName', @@ -66,7 +62,6 @@ describe('TableFieldValueCell', () => { beforeAll(() => { jest.clearAllMocks(); jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); }); describe('common behavior', () => { @@ -213,7 +208,7 @@ describe('TableFieldValueCell', () => { }); }); - it('should open preview when preview is not disabled', () => { + it('should open preview', () => { screen.getByTestId(`${FLYOUT_TABLE_PREVIEW_LINK_FIELD_TEST_ID}-0`).click(); expect(mockFlyoutApi.openPreviewPanel).toHaveBeenCalledWith({ diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.tsx index a0095bb8eadf..17ea9980f1ee 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_field_value_cell.tsx @@ -8,7 +8,6 @@ import React, { memo } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; import type { FieldSpec } from '@kbn/data-plugin/common'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { getFieldFormat } from '../utils/get_field_format'; import type { EventFieldsData } from '../../../../common/components/event_details/types'; import { OverflowField } from '../../../../common/components/tables/helpers'; @@ -66,7 +65,6 @@ export const TableFieldValueCell = memo( values, isPreview, }: FieldValueCellProps) => { - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); if (values == null) { return null; } @@ -92,7 +90,7 @@ export const TableFieldValueCell = memo( {data.field === MESSAGE_FIELD_NAME ? ( - ) : isPreviewEnabled && hasPreview(data.field) ? ( + ) : hasPreview(data.field) ? ( { return { @@ -109,7 +102,6 @@ const renderUserEntityOverview = () => describe('', () => { beforeAll(() => { jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(true); (useMisconfigurationPreview as jest.Mock).mockReturnValue({}); (useAlertsByStatus as jest.Mock).mockReturnValue({ isLoading: false, items: {} }); }); @@ -190,34 +182,9 @@ describe('', () => { expect(queryByTestId(ENTITIES_USER_OVERVIEW_DOMAIN_TEST_ID)).not.toBeInTheDocument(); }); - it('should navigate to left panel entities tab when clicking on title when feature flag is off', () => { - mockUseUserDetails.mockReturnValue([false, { userDetails: userData }]); - mockUseRiskScore.mockReturnValue({ data: riskLevel, isAuthorized: true }); - - const { getByTestId } = render( - - - - - - ); - - getByTestId(ENTITIES_USER_OVERVIEW_LINK_TEST_ID).click(); - expect(mockFlyoutApi.openLeftPanel).toHaveBeenCalledWith({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: panelContextValue.eventId, - indexName: panelContextValue.indexName, - scopeId: panelContextValue.scopeId, - }, - }); - }); - - it('should open user preview if feature flag is true', () => { + it('should open user preview', () => { mockUseUserDetails.mockReturnValue([false, { userDetails: userData }]); mockUseRiskScore.mockReturnValue({ data: riskLevel, isAuthorized: true }); - mockUseIsExperimentalFeatureEnabled.mockReturnValue(false); const { getByTestId } = render( diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/user_entity_overview.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/user_entity_overview.tsx index 1008f6139cd6..22f889a61c54 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/user_entity_overview.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/user_entity_overview.tsx @@ -5,13 +5,12 @@ * 2.0. */ -import React, { useCallback, useMemo } from 'react'; +import React, { useMemo } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiText, - EuiLink, useEuiTheme, useEuiFontSize, EuiSkeletonText, @@ -19,11 +18,6 @@ import { import { css } from '@emotion/css'; import { getOr } from 'lodash/fp'; import { i18n } from '@kbn/i18n'; -import { useExpandableFlyoutApi } from '@kbn/expandable-flyout'; -import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; -import { DocumentDetailsLeftPanelKey } from '../../shared/constants/panel_keys'; -import { LeftPanelInsightsTab } from '../../left'; -import { ENTITIES_TAB_ID } from '../../left/components/entities_details'; import { useDocumentDetailsContext } from '../../shared/context'; import type { DescriptionList } from '../../../../../common/utility_types'; import { USER_NAME_FIELD_NAME } from '../../../../timelines/components/timeline/body/renderers/constants'; @@ -83,22 +77,7 @@ export const USER_PREVIEW_BANNER = { * User preview content for the entities preview in right flyout. It contains ip addresses and risk level */ export const UserEntityOverview: React.FC = ({ userName }) => { - const { eventId, indexName, scopeId } = useDocumentDetailsContext(); - const { openLeftPanel } = useExpandableFlyoutApi(); - - const isPreviewEnabled = !useIsExperimentalFeatureEnabled('entityAlertPreviewDisabled'); - - const goToEntitiesTab = useCallback(() => { - openLeftPanel({ - id: DocumentDetailsLeftPanelKey, - path: { tab: LeftPanelInsightsTab, subTab: ENTITIES_TAB_ID }, - params: { - id: eventId, - indexName, - scopeId, - }, - }); - }, [eventId, openLeftPanel, indexName, scopeId]); + const { scopeId } = useDocumentDetailsContext(); const { from, to } = useGlobalTime(); const { selectedPatterns } = useSourcererDataView(); @@ -210,34 +189,21 @@ export const UserEntityOverview: React.FC = ({ userName - {isPreviewEnabled ? ( - - - {userName} - - - ) : ( - + {userName} - - )} + + diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.test.tsx index 6fb4d5d30b89..dc3b1f00e0d5 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.test.tsx @@ -106,6 +106,7 @@ describe('', () => { }); mockUseGraphPreview.mockReturnValue({ hasGraphRepresentation: true, + eventIds: [], }); mockUseFetchGraphData.mockReturnValue({ isLoading: false, diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.tsx index 23bea1f8fecd..467171cd49f2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/visualizations_section.tsx @@ -28,7 +28,8 @@ const KEY = 'visualizations'; */ export const VisualizationsSection = memo(() => { const expanded = useExpandSection({ title: KEY, defaultValue: false }); - const { dataAsNestedObject, getFieldsData } = useDocumentDetailsContext(); + const { dataAsNestedObject, getFieldsData, dataFormattedForFieldBrowser } = + useDocumentDetailsContext(); const [visualizationInFlyoutEnabled] = useUiSetting$( ENABLE_VISUALIZATIONS_IN_FLYOUT_SETTING @@ -42,6 +43,7 @@ export const VisualizationsSection = memo(() => { const { hasGraphRepresentation } = useGraphPreview({ getFieldsData, ecsData: dataAsNestedObject, + dataFormattedForFieldBrowser, }); const shouldShowGraphPreview = diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.test.tsx index 453f897d4e18..cf1ee8207839 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.test.tsx @@ -5,15 +5,18 @@ * 2.0. */ -import type { RenderHookResult } from '@testing-library/react'; +import type { TimelineEventsDetailsItem } from '@kbn/timelines-plugin/common'; import { renderHook } from '@testing-library/react'; -import type { UseGraphPreviewParams, UseGraphPreviewResult } from './use_graph_preview'; +import type { UseGraphPreviewParams } from './use_graph_preview'; import { useGraphPreview } from './use_graph_preview'; import type { GetFieldsData } from './use_get_fields_data'; import { mockFieldData } from '../mocks/mock_get_fields_data'; +import { mockDataFormattedForFieldBrowser } from '../mocks/mock_data_formatted_for_field_browser'; -const mockGetFieldsData: GetFieldsData = (field: string) => { - if (field === 'kibana.alert.original_event.id') { +const alertMockGetFieldsData: GetFieldsData = (field: string) => { + if (field === 'kibana.alert.uuid') { + return 'alertId'; + } else if (field === 'kibana.alert.original_event.id') { return 'eventId'; } else if (field === 'actor.entity.id') { return 'actorId'; @@ -24,18 +27,36 @@ const mockGetFieldsData: GetFieldsData = (field: string) => { return mockFieldData[field]; }; -describe('useGraphPreview', () => { - let hookResult: RenderHookResult; +const alertMockDataFormattedForFieldBrowser = mockDataFormattedForFieldBrowser; + +const eventMockGetFieldsData: GetFieldsData = (field: string) => { + if (field === 'kibana.alert.uuid') { + return; + } else if (field === 'kibana.alert.original_event.id') { + return; + } else if (field === 'event.id') { + return 'eventId'; + } else if (field === 'actor.entity.id') { + return 'actorId'; + } else if (field === 'target.entity.id') { + return 'targetId'; + } + return mockFieldData[field]; +}; + +const eventMockDataFormattedForFieldBrowser: TimelineEventsDetailsItem[] = []; + +describe('useGraphPreview', () => { it(`should return false when missing actor`, () => { const getFieldsData: GetFieldsData = (field: string) => { if (field === 'actor.entity.id') { return; } - return mockGetFieldsData(field); + return alertMockGetFieldsData(field); }; - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { getFieldsData, ecsData: { @@ -44,37 +65,41 @@ describe('useGraphPreview', () => { action: ['action'], }, }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(false); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual(['eventId']); - expect(actorIds).toEqual([]); - expect(targetIds).toEqual(['targetId']); - expect(action).toEqual(['action']); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: false, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['eventId'], + actorIds: [], + action: ['action'], + targetIds: ['targetId'], + isAlert: true, + }); }); it(`should return false when missing event.action`, () => { - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { - getFieldsData: mockGetFieldsData, + getFieldsData: alertMockGetFieldsData, ecsData: { _id: 'id', }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(false); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual(['eventId']); - expect(actorIds).toEqual(['actorId']); - expect(targetIds).toEqual(['targetId']); - expect(action).toEqual(undefined); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: false, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['eventId'], + actorIds: ['actorId'], + action: undefined, + targetIds: ['targetId'], + isAlert: true, + }); }); it(`should return false when missing target`, () => { @@ -82,26 +107,28 @@ describe('useGraphPreview', () => { if (field === 'target.entity.id') { return; } - return mockGetFieldsData(field); + return alertMockGetFieldsData(field); }; - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { getFieldsData, ecsData: { _id: 'id', }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(false); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual(['eventId']); - expect(actorIds).toEqual(['actorId']); - expect(targetIds).toEqual([]); - expect(action).toEqual(undefined); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: false, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['eventId'], + actorIds: ['actorId'], + action: undefined, + targetIds: [], + isAlert: true, + }); }); it(`should return false when missing original_event.id`, () => { @@ -110,10 +137,10 @@ describe('useGraphPreview', () => { return; } - return mockGetFieldsData(field); + return alertMockGetFieldsData(field); }; - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { getFieldsData, ecsData: { @@ -122,17 +149,19 @@ describe('useGraphPreview', () => { action: ['action'], }, }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(false); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual([]); - expect(actorIds).toEqual(['actorId']); - expect(targetIds).toEqual(['targetId']); - expect(action).toEqual(['action']); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: false, + timestamp: mockFieldData['@timestamp'][0], + eventIds: [], + actorIds: ['actorId'], + action: ['action'], + targetIds: ['targetId'], + isAlert: true, + }); }); it(`should return false when timestamp is missing`, () => { @@ -141,10 +170,10 @@ describe('useGraphPreview', () => { return; } - return mockGetFieldsData(field); + return alertMockGetFieldsData(field); }; - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { getFieldsData, ecsData: { @@ -153,45 +182,53 @@ describe('useGraphPreview', () => { action: ['action'], }, }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(false); - expect(timestamp).toEqual(null); - expect(eventIds).toEqual(['eventId']); - expect(actorIds).toEqual(['actorId']); - expect(targetIds).toEqual(['targetId']); - expect(action).toEqual(['action']); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: false, + timestamp: null, + eventIds: ['eventId'], + actorIds: ['actorId'], + action: ['action'], + targetIds: ['targetId'], + isAlert: true, + }); }); - it(`should return true when alert is has graph preview`, () => { - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + it(`should return true when event has graph graph preview`, () => { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { - getFieldsData: mockGetFieldsData, + getFieldsData: eventMockGetFieldsData, ecsData: { _id: 'id', event: { action: ['action'], }, }, + dataFormattedForFieldBrowser: eventMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(true); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual(['eventId']); - expect(actorIds).toEqual(['actorId']); - expect(targetIds).toEqual(['targetId']); - expect(action).toEqual(['action']); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: true, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['eventId'], + actorIds: ['actorId'], + action: ['action'], + targetIds: ['targetId'], + isAlert: false, + }); }); - it(`should return true when alert is has graph preview with multiple values`, () => { + it(`should return true when event has graph preview with multiple values`, () => { const getFieldsData: GetFieldsData = (field: string) => { - if (field === 'kibana.alert.original_event.id') { + if (field === 'kibana.alert.uuid') { + return; + } else if (field === 'kibana.alert.original_event.id') { + return; + } else if (field === 'event.id') { return ['id1', 'id2']; } else if (field === 'actor.entity.id') { return ['actorId1', 'actorId2']; @@ -202,7 +239,7 @@ describe('useGraphPreview', () => { return mockFieldData[field]; }; - hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { initialProps: { getFieldsData, ecsData: { @@ -211,16 +248,82 @@ describe('useGraphPreview', () => { action: ['action1', 'action2'], }, }, + dataFormattedForFieldBrowser: eventMockDataFormattedForFieldBrowser, }, }); - const { hasGraphRepresentation, timestamp, eventIds, actorIds, action, targetIds } = - hookResult.result.current; - expect(hasGraphRepresentation).toEqual(true); - expect(timestamp).toEqual(mockFieldData['@timestamp'][0]); - expect(eventIds).toEqual(['id1', 'id2']); - expect(actorIds).toEqual(['actorId1', 'actorId2']); - expect(action).toEqual(['action1', 'action2']); - expect(targetIds).toEqual(['targetId1', 'targetId2']); + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: true, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['id1', 'id2'], + actorIds: ['actorId1', 'actorId2'], + action: ['action1', 'action2'], + targetIds: ['targetId1', 'targetId2'], + isAlert: false, + }); + }); + + it(`should return true when alert has graph preview`, () => { + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + initialProps: { + getFieldsData: alertMockGetFieldsData, + ecsData: { + _id: 'id', + event: { + action: ['action'], + }, + }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, + }, + }); + + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: true, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['eventId'], + actorIds: ['actorId'], + action: ['action'], + targetIds: ['targetId'], + isAlert: true, + }); + }); + + it(`should return true when alert has graph preview with multiple values`, () => { + const getFieldsData: GetFieldsData = (field: string) => { + if (field === 'kibana.alert.uuid') { + return 'alertId'; + } else if (field === 'kibana.alert.original_event.id') { + return ['id1', 'id2']; + } else if (field === 'actor.entity.id') { + return ['actorId1', 'actorId2']; + } else if (field === 'target.entity.id') { + return ['targetId1', 'targetId2']; + } + + return mockFieldData[field]; + }; + + const hookResult = renderHook((props: UseGraphPreviewParams) => useGraphPreview(props), { + initialProps: { + getFieldsData, + ecsData: { + _id: 'id', + event: { + action: ['action1', 'action2'], + }, + }, + dataFormattedForFieldBrowser: alertMockDataFormattedForFieldBrowser, + }, + }); + + expect(hookResult.result.current).toStrictEqual({ + hasGraphRepresentation: true, + timestamp: mockFieldData['@timestamp'][0], + eventIds: ['id1', 'id2'], + actorIds: ['actorId1', 'actorId2'], + action: ['action1', 'action2'], + targetIds: ['targetId1', 'targetId2'], + isAlert: true, + }); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.ts b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.ts index 48233afab02d..8f05b87844fb 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_graph_preview.ts @@ -5,10 +5,12 @@ * 2.0. */ +import type { TimelineEventsDetailsItem } from '@kbn/timelines-plugin/common'; import type { EcsSecurityExtension as Ecs } from '@kbn/securitysolution-ecs'; import { get } from 'lodash/fp'; import type { GetFieldsData } from './use_get_fields_data'; import { getField, getFieldArray } from '../utils'; +import { useBasicDataFromDetailsData } from './use_basic_data_from_details_data'; export interface UseGraphPreviewParams { /** @@ -20,6 +22,11 @@ export interface UseGraphPreviewParams { * An object with top level fields from the ECS object */ ecsData: Ecs; + + /** + * An array of field objects with category and value + */ + dataFormattedForFieldBrowser: TimelineEventsDetailsItem[]; } /** * Interface for the result of the useGraphPreview hook @@ -54,6 +61,11 @@ export interface UseGraphPreviewResult { * Boolean indicating if the event is has a graph representation (contains event ids, actor ids and action) */ hasGraphRepresentation: boolean; + + /** + * Boolean indicating if the event is an alert or not + */ + isAlert: boolean; } /** @@ -62,6 +74,7 @@ export interface UseGraphPreviewResult { export const useGraphPreview = ({ getFieldsData, ecsData, + dataFormattedForFieldBrowser, }: UseGraphPreviewParams): UseGraphPreviewResult => { const timestamp = getField(getFieldsData('@timestamp')); const originalEventId = getFieldsData('kibana.alert.original_event.id'); @@ -77,6 +90,7 @@ export const useGraphPreview = ({ actorIds.length > 0 && eventIds.length > 0 && targetIds.length > 0; + const { isAlert } = useBasicDataFromDetailsData(dataFormattedForFieldBrowser); - return { timestamp, eventIds, actorIds, action, targetIds, hasGraphRepresentation }; + return { timestamp, eventIds, actorIds, action, targetIds, hasGraphRepresentation, isAlert }; }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/common/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/management/common/translations.ts index 6929452e5d9e..50885a9db6b6 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/common/translations.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/management/common/translations.ts @@ -279,7 +279,7 @@ Command Examples for Running Scripts: 3. Executes a raw script provided entirely within the "--Raw" flag. - runscript --Raw="Get-ChildItem." + runscript --Raw=\`\`\`Get-ChildItem.\`\`\` 4. Executes a script located on the remote host at the specified path with the provided command-line arguments. diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response.tsx index 43ff3ffca5a6..09d1e45f24c4 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response.tsx @@ -10,6 +10,8 @@ import type { ActionDetails, MaybeImmutable, ResponseActionExecuteOutputContent, + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters, ResponseActionsExecuteParameters, } from '../../../../common/endpoint/types'; import { EXECUTE_FILE_LINK_TITLE } from '../endpoint_response_actions_list/translations'; @@ -18,14 +20,18 @@ import { ExecuteActionHostResponseOutput } from './execute_action_host_response_ export interface ExecuteActionHostResponseProps { action: MaybeImmutable< - ActionDetails + | ActionDetails + | ActionDetails >; agentId?: string; canAccessFileDownloadLink: boolean; 'data-test-subj'?: string; textSize?: 'xs' | 's'; + hideFile?: boolean; + hideContext?: boolean; } +// Note: also used for RunScript command export const ExecuteActionHostResponse = memo( ({ action, @@ -33,6 +39,8 @@ export const ExecuteActionHostResponse = memo( canAccessFileDownloadLink, textSize = 's', 'data-test-subj': dataTestSubj, + hideFile, + hideContext, }) => { const outputContent = useMemo( () => @@ -44,21 +52,24 @@ export const ExecuteActionHostResponse = memo( return ( <> - - - - + {!hideFile && ( + + + + + )} {outputContent && ( )} diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response_output.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response_output.tsx index f24f18e14939..4e6161b8767d 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response_output.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_execute_action/execute_action_host_response_output.tsx @@ -98,6 +98,7 @@ interface ShellInfoContentProps { textSize?: 's' | 'xs'; title: string; } + const ShellInfoContent = memo(({ content, textSize, title }) => ( @@ -178,10 +179,12 @@ export interface ExecuteActionHostResponseOutputProps { outputContent: ResponseActionExecuteOutputContent; 'data-test-subj'?: string; textSize?: 's' | 'xs'; + hideContext?: boolean; } +// Note: also used for RunScript command export const ExecuteActionHostResponseOutput = memo( - ({ outputContent, 'data-test-subj': dataTestSubj, textSize = 'xs' }) => { + ({ outputContent, 'data-test-subj': dataTestSubj, textSize = 'xs', hideContext }) => { const contextContent = useMemo( () => ( <> @@ -216,14 +219,16 @@ export const ExecuteActionHostResponseOutput = memo - - - + {!hideContext && ( + + + + )} {outputContent.stderr.length > 0 && ( <> diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/command_render_components/run_script_action.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/command_render_components/run_script_action.tsx new file mode 100644 index 000000000000..e2ed35845502 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/command_render_components/run_script_action.tsx @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo, useMemo } from 'react'; + +import { i18n } from '@kbn/i18n'; +import { ExecuteActionHostResponse } from '../../endpoint_execute_action'; +import { useSendRunScriptEndpoint } from '../../../hooks/response_actions/use_send_run_script_endpoint_request'; +import type { RunScriptActionRequestBody } from '../../../../../common/api/endpoint'; +import { useConsoleActionSubmitter } from '../hooks/use_console_action_submitter'; +import type { + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters, +} from '../../../../../common/endpoint/types'; +import type { ActionRequestComponentProps } from '../types'; + +export const RunScriptActionResult = memo< + ActionRequestComponentProps< + { + Raw?: string; + HostPath?: string; + CloudFile?: string; + CommandLine?: string; + Timeout?: number; + comment?: string; + }, + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters + > +>(({ command, setStore, store, status, setStatus, ResultComponent }) => { + const actionCreator = useSendRunScriptEndpoint(); + const actionRequestBody = useMemo(() => { + const { endpointId, agentType } = command.commandDefinition?.meta ?? {}; + + if (!endpointId) { + return; + } + return { + agent_type: agentType, + endpoint_ids: [endpointId], + parameters: { + raw: command.args.args.Raw?.[0], + hostPath: command.args.args.HostPath?.[0], + cloudFile: command.args.args.CloudFile?.[0], + commandLine: command.args.args.CommandLine?.[0], + timeout: command.args.args.Timeout?.[0], + }, + comment: command.args.args?.comment?.[0], + }; + }, [command]); + + const { result, actionDetails: completedActionDetails } = useConsoleActionSubmitter< + RunScriptActionRequestBody, + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters + >({ + ResultComponent, + setStore, + store, + status, + setStatus, + actionCreator, + actionRequestBody, + dataTestSubj: 'runscript', + }); + + if (!completedActionDetails || !completedActionDetails.wasSuccessful) { + return result; + } + + return ( + + + + ); +}); +RunScriptActionResult.displayName = 'RunScriptActionResult'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/lib/console_commands_definition.ts b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/lib/console_commands_definition.ts index 8c99186f69d9..22d138dea358 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/lib/console_commands_definition.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_responder/lib/console_commands_definition.ts @@ -6,6 +6,7 @@ */ import { i18n } from '@kbn/i18n'; +import { RunScriptActionResult } from '../command_render_components/run_script_action'; import type { CommandArgDefinition } from '../../console/types'; import { isAgentTypeAndActionSupported } from '../../../../common/lib/endpoint'; import { getRbacControl } from '../../../../../common/endpoint/service/response_actions/utils'; @@ -531,14 +532,14 @@ export const getEndpointConsoleCommands = ({ aboutInfo: CROWDSTRIKE_CONSOLE_COMMANDS.runscript.about, isSupported: doesEndpointSupportCommand('runscript'), }), - RenderComponent: () => null, + RenderComponent: RunScriptActionResult, meta: { agentType, endpointId: endpointAgentId, capabilities: endpointCapabilities, privileges: endpointPrivileges, }, - exampleUsage: `runscript --Raw="Get-ChildItem ." --CommandLine=""`, + exampleUsage: `runscript --Raw=\`\`\`Get-ChildItem .\`\`\` --CommandLine=""`, helpUsage: CROWDSTRIKE_CONSOLE_COMMANDS.runscript.helpUsage, exampleInstruction: CROWDSTRIKE_CONSOLE_COMMANDS.runscript.about, validate: capabilitiesAndPrivilegesValidator(agentType), diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/action_log_expanded_tray.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/action_log_expanded_tray.tsx index cba1d0aee41b..53f2c89ac84f 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/action_log_expanded_tray.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/components/action_log_expanded_tray.tsx @@ -23,6 +23,7 @@ import { isExecuteAction, isGetFileAction, isProcessesAction, + isRunScriptAction, isUploadAction, } from '../../../../../common/endpoint/service/response_actions/type_guards'; import { EndpointUploadActionResult } from '../../endpoint_upload_action_result'; @@ -209,6 +210,30 @@ const OutputContent = memo<{ ); } + if (isRunScriptAction(action)) { + return ( + + {action.agents.map((agentId) => ( +
    + {OUTPUT_MESSAGES.wasSuccessful(command)} + +
    + ))} +
    + ); + } + + // CrowdStrike Isolate/Release actions if (action.agentType === 'crowdstrike') { return <>{OUTPUT_MESSAGES.submittedSuccessfully(command)}; } diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.test.ts b/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.test.ts new file mode 100644 index 000000000000..39eb3728162d --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.test.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useMutation as _useMutation } from '@tanstack/react-query'; +import type { AppContextTestRender } from '../../../common/mock/endpoint'; +import type { RenderHookResult } from '@testing-library/react'; +import { createAppRootMockRenderer } from '../../../common/mock/endpoint'; +import { responseActionsHttpMocks } from '../../mocks/response_actions_http_mocks'; +import { RUN_SCRIPT_ROUTE } from '../../../../common/endpoint/constants'; +import type { RunScriptActionRequestBody } from '../../../../common/api/endpoint'; +import type { + RunScriptRequestCustomOptions, + UseSendRunScriptRequestResult, +} from './use_send_run_script_endpoint_request'; +import { useSendRunScriptEndpoint } from './use_send_run_script_endpoint_request'; + +const useMutationMock = _useMutation as jest.Mock; + +jest.mock('@tanstack/react-query', () => { + const actualReactQueryModule = jest.requireActual('@tanstack/react-query'); + + return { + ...actualReactQueryModule, + useMutation: jest.fn((...args) => actualReactQueryModule.useMutation(...args)), + }; +}); + +const runScriptPayload: RunScriptActionRequestBody = { + endpoint_ids: ['test-endpoint-id'], + agent_type: 'crowdstrike', + parameters: { raw: 'ls' }, +}; + +describe('When using the `useSendRunScriptRequest()` hook', () => { + let customOptions: RunScriptRequestCustomOptions; + let http: AppContextTestRender['coreStart']['http']; + let apiMocks: ReturnType; + let renderHook: () => RenderHookResult< + UseSendRunScriptRequestResult, + RunScriptRequestCustomOptions + >; + + beforeEach(() => { + const testContext = createAppRootMockRenderer(); + + http = testContext.coreStart.http; + apiMocks = responseActionsHttpMocks(http); + customOptions = {}; + + renderHook = () => { + return testContext.renderHook(() => useSendRunScriptEndpoint(customOptions)); + }; + }); + + it('should call the `runScript` API with correct payload', async () => { + const { + result: { + current: { mutateAsync }, + }, + } = renderHook(); + await mutateAsync(runScriptPayload); + + expect(apiMocks.responseProvider.runscript).toHaveBeenCalledWith({ + body: JSON.stringify(runScriptPayload), + path: RUN_SCRIPT_ROUTE, + version: '2023-10-31', + }); + }); + + it('should allow custom options to be passed to ReactQuery', async () => { + customOptions.mutationKey = ['pqr-abc']; + customOptions.cacheTime = 10; + renderHook(); + + expect(useMutationMock).toHaveBeenCalledWith(expect.any(Function), customOptions); + }); +}); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.ts b/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.ts new file mode 100644 index 000000000000..f4dd937fe300 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/public/management/hooks/response_actions/use_send_run_script_endpoint_request.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { UseMutationOptions, UseMutationResult } from '@tanstack/react-query'; +import type { IHttpFetchError } from '@kbn/core-http-browser'; +import { useMutation } from '@tanstack/react-query'; +import type { RunScriptActionRequestBody } from '../../../../common/api/endpoint'; +import { KibanaServices } from '../../../common/lib/kibana'; +import { RUN_SCRIPT_ROUTE } from '../../../../common/endpoint/constants'; +import type { ResponseActionApiResponse } from '../../../../common/endpoint/types'; + +export type RunScriptRequestCustomOptions = UseMutationOptions< + ResponseActionApiResponse, + IHttpFetchError, + RunScriptActionRequestBody +>; + +export type UseSendRunScriptRequestResult = UseMutationResult< + ResponseActionApiResponse, + IHttpFetchError, + RunScriptActionRequestBody +>; + +export const useSendRunScriptEndpoint = ( + options?: RunScriptRequestCustomOptions +): UseSendRunScriptRequestResult => { + return useMutation( + (runScriptActionReqBody) => { + return KibanaServices.get().http.post(RUN_SCRIPT_ROUTE, { + body: JSON.stringify(runScriptActionReqBody), + version: '2023-10-31', + }); + }, + options + ); +}; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/mocks/response_actions_http_mocks.ts b/x-pack/solutions/security/plugins/security_solution/public/management/mocks/response_actions_http_mocks.ts index 256484f8d0e9..e8307895c3c4 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/mocks/response_actions_http_mocks.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/management/mocks/response_actions_http_mocks.ts @@ -17,6 +17,7 @@ import { GET_PROCESSES_ROUTE, ISOLATE_HOST_ROUTE_V2, KILL_PROCESS_ROUTE, + RUN_SCRIPT_ROUTE, SCAN_ROUTE, SUSPEND_PROCESS_ROUTE, UNISOLATE_HOST_ROUTE_V2, @@ -42,6 +43,8 @@ import type { ResponseActionScanParameters, ResponseActionUploadOutputContent, ResponseActionUploadParameters, + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters, } from '../../../common/endpoint/types'; export type ResponseActionsHttpMocksInterface = ResponseProvidersInterface<{ @@ -73,6 +76,8 @@ export type ResponseActionsHttpMocksInterface = ResponseProvidersInterface<{ >; scan: () => ActionDetailsApiResponse; + + runscript: () => ActionDetailsApiResponse; }>; export const responseActionsHttpMocks = httpHandlerMockFactory([ @@ -273,6 +278,25 @@ export const responseActionsHttpMocks = httpHandlerMockFactory => { + const generator = new EndpointActionGenerator('seed'); + const response = generator.generateActionDetails< + ResponseActionRunScriptOutputContent, + ResponseActionRunScriptParameters + >({ + command: 'runscript', + }); + return { data: response }; }, }, diff --git a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/esql/translations.ts b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/esql/translations.ts index e97da8b29c65..bffd2db6cd73 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/esql/translations.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/esql/translations.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; export const GET_TIMELINE_DISCOVER_SAVED_SEARCH_TITLE = (title: string) => - i18n.translate('xpack.securitySolution.timelines.discoverInTimeline.savedSearchTitle', { - defaultMessage: 'Saved search for timeline - {title}', + i18n.translate('xpack.securitySolution.timelines.discoverInTimeline.discoverSessionTitle', { + defaultMessage: 'Saved Discover session for timeline - {title}', values: { title }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/response_actions.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/response_actions.ts index 1987a019f888..d54df140b3b4 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/response_actions.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/response_actions.ts @@ -27,6 +27,7 @@ import type { ResponseActionGetFileParameters, EndpointActionResponseDataOutput, ResponseActionScanOutputContent, + ResponseActionRunScriptOutputContent, } from '../../../common/endpoint/types'; import { getFileDownloadId } from '../../../common/endpoint/service/response_actions/get_file_download_id'; import { @@ -138,6 +139,15 @@ export const sendEndpointActionResponse = async ( .content as unknown as ResponseActionExecuteOutputContent ).stderr = 'execute command timed out'; } + if ( + endpointResponse.EndpointActions.data.command === 'runscript' && + endpointResponse.EndpointActions.data.output + ) { + ( + endpointResponse.EndpointActions.data.output + .content as unknown as ResponseActionRunScriptOutputContent + ).stderr = 'runscript command timed out'; + } } await esClient.index({ diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts index 0c505b12c129..25fcb30be494 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts @@ -11,8 +11,13 @@ import { CROWDSTRIKE_CONNECTOR_ID, } from '@kbn/stack-connectors-plugin/common/crowdstrike/constants'; import type { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; -import type { CrowdstrikeBaseApiResponse } from '@kbn/stack-connectors-plugin/common/crowdstrike/types'; +import type { + CrowdstrikeBaseApiResponse, + CrowdStrikeExecuteRTRResponse, +} from '@kbn/stack-connectors-plugin/common/crowdstrike/types'; import { v4 as uuidv4 } from 'uuid'; + +import { mapParametersToCrowdStrikeArguments } from './utils'; import type { CrowdstrikeActionRequestCommonMeta } from '../../../../../../common/endpoint/types/crowdstrike'; import type { CommonResponseActionMethodOptions, @@ -305,15 +310,99 @@ export class CrowdstrikeActionsClient extends ResponseActionsClientImpl { ): Promise< ActionDetails > { - // TODO: just a placeholder for now - return Promise.resolve({ output: 'runscript', code: 200 }) as never as ActionDetails< - ResponseActionRunScriptOutputContent, - ResponseActionRunScriptParameters - >; + const reqIndexOptions: ResponseActionsClientWriteActionRequestToEndpointIndexOptions = { + ...actionRequest, + ...this.getMethodOptions(options), + command: 'runscript', + }; + + let actionResponse: ActionTypeExecutorResult | undefined; + if (!reqIndexOptions.error) { + let error = (await this.validateRequest(reqIndexOptions)).error; + if (!error) { + if (!reqIndexOptions.actionId) { + reqIndexOptions.actionId = uuidv4(); + } + + try { + actionResponse = (await this.sendAction(SUB_ACTION.EXECUTE_ADMIN_RTR, { + actionParameters: { comment: this.buildExternalComment(reqIndexOptions) }, + command: mapParametersToCrowdStrikeArguments('runscript', actionRequest.parameters), + endpoint_ids: actionRequest.endpoint_ids, + })) as ActionTypeExecutorResult; + } catch (err) { + error = err; + } + } + + reqIndexOptions.error = error?.message; + + if (!this.options.isAutomated && error) { + throw error; + } + } + + const actionRequestDoc = await this.writeActionRequestToEndpointIndex(reqIndexOptions); + + // Ensure actionResponse is assigned before using it + if (actionResponse) { + await this.completeCrowdstrikeBatchAction(actionResponse, actionRequestDoc); + } + + await this.updateCases({ + command: reqIndexOptions.command, + caseIds: reqIndexOptions.case_ids, + alertIds: reqIndexOptions.alert_ids, + actionId: actionRequestDoc.EndpointActions.action_id, + hosts: actionRequest.endpoint_ids.map((agentId) => { + return { + hostId: agentId, + hostname: actionRequestDoc.EndpointActions.data.hosts?.[agentId].name ?? '', + }; + }), + comment: reqIndexOptions.comment, + }); + + return this.fetchActionDetails(actionRequestDoc.EndpointActions.action_id); + } + + private async completeCrowdstrikeBatchAction( + actionResponse: ActionTypeExecutorResult, + doc: LogsEndpointAction + ): Promise { + const agentId = doc.agent.id as string; + const stdout = actionResponse.data?.combined.resources[agentId].stdout || ''; + const stderr = actionResponse.data?.combined.resources[agentId].stderr || ''; + const error = actionResponse.data?.combined.resources[agentId].errors?.[0]; + const options = { + actionId: doc.EndpointActions.action_id, + agentId, + data: { + ...doc.EndpointActions.data, + output: { + content: { + stdout, + stderr, + code: '200', + }, + type: 'text' as const, + }, + }, + ...(error + ? { + error: { + code: error.code, + message: `Crowdstrike action failed: ${error.message}`, + }, + } + : {}), + }; + + await this.writeActionResponseToEndpointIndex(options); } private async completeCrowdstrikeAction( - actionResponse: ActionTypeExecutorResult | undefined, + actionResponse: ActionTypeExecutorResult, doc: LogsEndpointAction ): Promise { const options = { diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.test.ts new file mode 100644 index 000000000000..f961c7a3d1d6 --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.test.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { mapParametersToCrowdStrikeArguments } from './utils'; + +describe('mapParametersToCrowdStrikeArguments', () => { + it('returns command with single word parameter as is', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', { raw: 'echo Hello' }); + expect(result).toBe('runscript --Raw=```echo Hello```'); + }); + + it('wraps multi-word parameter in triple backticks', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', { + commandLine: 'echo Hello World', + }); + expect(result).toBe('runscript --CommandLine=```echo Hello World```'); + }); + + it('leaves parameter already wrapped in triple backticks unchanged', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', { + commandLine: '```echo Hello World```', + }); + expect(result).toBe('runscript --CommandLine=```echo Hello World```'); + }); + + it('trims spaces from parameter values', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', { raw: ' echo Hello ' }); + expect(result).toBe('runscript --Raw=```echo Hello```'); + }); + + it('handles multiple parameters correctly', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', { + raw: 'echo Hello', + commandLine: 'echo Hello World', + hostPath: '/home/user', + cloudFile: 'file.txt', + }); + expect(result).toBe( + 'runscript --Raw=```echo Hello``` --CommandLine=```echo Hello World``` --HostPath=/home/user --CloudFile=file.txt' + ); + }); + + it('returns command with no parameters correctly', () => { + const result = mapParametersToCrowdStrikeArguments('runscript', {}); + expect(result).toBe('runscript '); + }); +}); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.ts new file mode 100644 index 000000000000..2ec2ec2bb0cf --- /dev/null +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/utils.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { upperFirst } from 'lodash'; +import type { RunScriptActionRequestBody } from '../../../../../../common/api/endpoint'; + +export const mapParametersToCrowdStrikeArguments = ( + commandName: string, + parameters: RunScriptActionRequestBody['parameters'] +): string => { + // Map each parameter to the required syntax and join them with spaces + // In short: this function has to transform the parameters object into a string that can be used as a CS command + // One word commands eg. 'ls' can go as it is, but if there are more elements eg. 'ls -l', they have to be wrapped in triple backticks + const commandParts = Object.entries(parameters).map(([key, value]) => { + // Check and process the parameter value + let sanitizedValue; + if (typeof value === 'string') { + if (/^```.*```$/.test(value)) { + // If already wrapped in triple backticks, leave unchanged + sanitizedValue = value; + } else { + const strippedValue = value.trim(); // Remove spaces at the beginning and end + if (strippedValue.split(/\s+/).length === 1) { + // If it's a single element (no spaces), use it as-is + sanitizedValue = strippedValue; + } else { + // If it contains multiple elements (spaces), wrap in ``` + sanitizedValue = `\`\`\`${strippedValue}\`\`\``; + } + } + } else { + sanitizedValue = value; + } + return `--${upperFirst(key)}=${sanitizedValue}`; + }); + + // Combine the base command with the constructed parameters + return `${commandName} ${commandParts.join(' ')}`; +}; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts index 6360ceba71ce..00b4774d9489 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts @@ -248,7 +248,7 @@ const createRunScriptOptionsMock = ( const options: RunScriptActionRequestBody = { ...createNoParamsResponseActionOptionsMock(), parameters: { - Raw: 'ls', + raw: 'ls', }, }; return merge(options, overrides); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/README.md b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/README.md index f159a2c5b248..b60033b73177 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/README.md +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/README.md @@ -172,5 +172,5 @@ To test out the functionality of large lists with rules, the user will need to i * First, set the appropriate env var in order to enable exceptions features`export ELASTIC_XPACK_SECURITY_SOLUTION_LISTS_FEATURE=true` and `export ELASTIC_XPACK_SECURITY_SOLUTION_EXCEPTIONS_LISTS=true` and start kibana * Second, import a list of ips from a file called `ci-badguys.txt`. The command should look like this: -`cd $HOME/kibana/x-pack/plugins/lists/server/scripts && ./import_list_items_by_filename.sh ip ~/ci-badguys.txt` +`cd $HOME/kibana/x-pack/solutions/security/plugins/lists/server/scripts && ./import_list_items_by_filename.sh ip ~/ci-badguys.txt` * Then, from the detection engine scripts folder (`cd kibana/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/scripts`) run `./post_rule.sh rules/queries/lists/query_with_list_plugin.json` diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.test.ts index 86ac7d136d22..b7cacea3c375 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.test.ts @@ -17,6 +17,18 @@ import type { DataViewsService } from '@kbn/data-views-plugin/common'; import type { AppClient } from '../../..'; import type { EntityStoreConfig } from './types'; import { mockGlobalState } from '../../../../public/common/mock'; +import type { EntityDefinition } from '@kbn/entities-schema'; +import { getUnitedEntityDefinition } from './united_entity_definitions'; + +const unitedDefinition = getUnitedEntityDefinition({ + entityType: 'host', + namespace: 'test', + fieldHistoryLength: 10, + indexPatterns: [], + syncDelay: '1m', + frequency: '1m', +}); +const definition: EntityDefinition = unitedDefinition.entityManagerDefinition; describe('EntityStoreDataClient', () => { const mockSavedObjectClient = savedObjectsClientMock.create(); @@ -182,4 +194,137 @@ describe('EntityStoreDataClient', () => { expect(response.records[0]).toEqual(fakeEntityRecord); }); }); + + describe('getComponentFromEntityDefinition', () => { + it('returns installed false if no definition is provided', () => { + const result = dataClient.getComponentFromEntityDefinition('security_host_test', undefined); + expect(result).toEqual([ + { + id: 'security_host_test', + installed: false, + resource: 'entity_definition', + }, + ]); + }); + + it('returns correct components for EntityDefinitionWithState', () => { + const definitionWithState = { + ...definition, + state: { + installed: true, + running: true, + components: { + transforms: [ + { + id: 'transforms_id', + installed: true, + running: true, + }, + ], + ingestPipelines: [ + { + id: 'pipeline-1', + installed: true, + }, + ], + indexTemplates: [ + { + id: 'indexTemplates_id', + installed: true, + }, + ], + }, + }, + }; + + const result = dataClient.getComponentFromEntityDefinition( + 'security_host_test', + definitionWithState + ); + expect(result).toEqual([ + { + id: 'security_host_test', + installed: true, + resource: 'entity_definition', + }, + { + id: 'security_host_test', + resource: 'transform', + installed: true, + health: 'unknown', + errors: undefined, + }, + { + resource: 'ingest_pipeline', + id: 'pipeline-1', + installed: true, + }, + { + id: 'security_host_test', + installed: true, + resource: 'index_template', + }, + ]); + }); + + it('returns empty array for EntityDefinition without state', () => { + const result = dataClient.getComponentFromEntityDefinition('security_host_test', definition); + expect(result).toEqual([]); + }); + + it('handles transform health issues correctly', () => { + const definitionWithState = { + ...definition, + state: { + installed: true, + components: { + transforms: [ + { + installed: true, + stats: { + health: { + status: 'yellow', + issues: [ + { + type: 'issue-type', + issue: 'issue-message', + details: 'issue-details', + count: 1, + }, + ], + }, + }, + }, + ], + ingestPipelines: [], + indexTemplates: [], + }, + }, + }; + + const result = dataClient.getComponentFromEntityDefinition( + 'security_host_test', + definitionWithState + ); + expect(result).toEqual([ + { + id: 'security_host_test', + installed: true, + resource: 'entity_definition', + }, + { + id: 'security_host_test', + resource: 'transform', + installed: true, + health: 'yellow', + errors: [ + { + title: 'issue-message', + message: 'issue-details', + }, + ], + }, + ]); + }); + }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.ts index c18dc1863a8d..faf2edc15419 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/entity_store_data_client.ts @@ -15,7 +15,7 @@ import type { AnalyticsServiceSetup, } from '@kbn/core/server'; import { EntityClient } from '@kbn/entityManager-plugin/server/lib/entity_client'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; +import type { HealthStatus, SortOrder } from '@elastic/elasticsearch/lib/api/types'; import type { TaskManagerStartContract } from '@kbn/task-manager-plugin/server'; import type { DataViewsService } from '@kbn/data-views-plugin/common'; import { isEqual } from 'lodash/fp'; @@ -465,7 +465,7 @@ export class EntityStoreDataClient { public getComponentFromEntityDefinition( id: string, - definition: EntityDefinitionWithState | EntityDefinition + definition: EntityDefinitionWithState | EntityDefinition | undefined ): EngineComponentStatus[] { if (!definition) { return [ @@ -478,16 +478,22 @@ export class EntityStoreDataClient { } if ('state' in definition) { + const transformHealthToComponentHealth = ( + health: HealthStatus | undefined + ): EngineComponentStatus['health'] => + health ? (health.toLowerCase() as Lowercase) : 'unknown'; + return [ { id: definition.id, installed: definition.state.installed, resource: EngineComponentResourceEnum.entity_definition, }, - ...definition.state.components.transforms.map(({ installed, running, stats }) => ({ + ...definition.state.components.transforms.map(({ installed, stats }) => ({ id, resource: EngineComponentResourceEnum.transform, installed, + health: transformHealthToComponentHealth(stats?.health?.status), errors: (stats?.health as TransformHealth)?.issues?.map(({ issue, details }) => ({ title: issue, message: details, diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering.ts index 1a5fb8e64a26..08d5b0d088aa 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering.ts +++ b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering.ts @@ -7,11 +7,10 @@ import type { Logger } from '@kbn/core/server'; import { ProductLine } from '../../common/product'; import { getCloudSecurityUsageRecord } from './cloud_security_metering_task'; -import { CLOUD_DEFEND, CNVM, CSPM, KSPM } from './constants'; +import { CNVM, CSPM, KSPM } from './constants'; import type { CloudSecuritySolutions } from './types'; import type { MeteringCallBackResponse, MeteringCallbackInput, Tier, UsageRecord } from '../types'; import type { ServerlessSecurityConfig } from '../config'; -import { getCloudDefendUsageRecords } from './defend_for_containers_metering'; export const cloudSecurityMetringCallback = async ({ esClient, @@ -35,24 +34,11 @@ export const cloudSecurityMetringCallback = async ({ const tier: Tier = getCloudProductTier(config, logger); try { - const cloudSecuritySolutions: CloudSecuritySolutions[] = [CSPM, KSPM, CNVM, CLOUD_DEFEND]; + const cloudSecuritySolutions: CloudSecuritySolutions[] = [CSPM, KSPM, CNVM]; const promiseResults = await Promise.allSettled( cloudSecuritySolutions.map((cloudSecuritySolution) => { - if (cloudSecuritySolution !== CLOUD_DEFEND) { - return getCloudSecurityUsageRecord({ - esClient, - projectId, - logger, - taskId, - lastSuccessfulReport, - cloudSecuritySolution, - tier, - }); - } - - // since lastSuccessfulReport is not used by getCloudSecurityUsageRecord, we want to verify if it is used by getCloudDefendUsageRecords before getCloudSecurityUsageRecord. - return getCloudDefendUsageRecords({ + return getCloudSecurityUsageRecord({ esClient, projectId, logger, diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.test.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.test.ts index 6d55e5246928..423b26b5f7e9 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.test.ts +++ b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.test.ts @@ -16,15 +16,7 @@ import { import type { ServerlessSecurityConfig } from '../config'; import type { ProductTier } from '../../common/product'; -import { - CLOUD_SECURITY_TASK_TYPE, - CSPM, - KSPM, - CNVM, - CLOUD_DEFEND, - BILLABLE_ASSETS_CONFIG, -} from './constants'; -import { getCloudDefendUsageRecords } from './defend_for_containers_metering'; +import { CLOUD_SECURITY_TASK_TYPE, CSPM, KSPM, CNVM, BILLABLE_ASSETS_CONFIG } from './constants'; const mockEsClient = elasticsearchServiceMock.createStart().client.asInternalUser; const logger: ReturnType = loggingSystemMock.createLogger(); @@ -336,173 +328,3 @@ describe('should return the relevant product tier', () => { expect(tier).toBe('none'); }); }); - -describe('cloud defend metering', () => { - it('should return usageRecords with correct values', async () => { - const cloudSecuritySolution = 'cloud_defend'; - const agentId1 = chance.guid(); - const eventIngestedStr = '2024-05-28T12:10:51Z'; - const eventIngestedTimestamp = new Date(eventIngestedStr); - - // @ts-ignore - mockEsClient.search.mockResolvedValueOnce({ - hits: { - hits: [ - { - _id: 'someRecord', - _index: 'mockIndex', - _source: { - 'cloud_defend.block_action_enabled': true, - 'agent.id': agentId1, - event: { - ingested: eventIngestedStr, - }, - }, - }, - ], - }, - }); - - const projectId = chance.guid(); - const taskId = chance.guid(); - - const tier = 'essentials' as ProductTier; - - const result = await getCloudDefendUsageRecords({ - esClient: mockEsClient, - projectId, - taskId, - lastSuccessfulReport: new Date(), - cloudSecuritySolution, - logger, - tier, - }); - - const roundedIngestedTimestamp = eventIngestedTimestamp; - roundedIngestedTimestamp.setMinutes(0); - roundedIngestedTimestamp.setSeconds(0); - roundedIngestedTimestamp.setMilliseconds(0); - - expect(result).toEqual([ - { - id: expect.stringContaining( - `${projectId}_${agentId1}_${roundedIngestedTimestamp.toISOString()}` - ), - usage_timestamp: eventIngestedStr, - creation_timestamp: expect.any(String), - usage: { - type: CLOUD_SECURITY_TASK_TYPE, - sub_type: CLOUD_DEFEND, - quantity: 1, - period_seconds: 3600, - }, - source: { - id: taskId, - instance_group_id: projectId, - metadata: { - tier: 'essentials', - }, - }, - }, - ]); - }); - - it('should return an empty array when Elasticsearch returns an empty response', async () => { - // @ts-ignore - mockEsClient.search.mockResolvedValueOnce({ - hits: { - hits: [], - }, - }); - const tier = 'essentials' as ProductTier; - // Call the function with mock parameters - const result = await getCloudDefendUsageRecords({ - esClient: mockEsClient, - projectId: chance.guid(), - taskId: chance.guid(), - lastSuccessfulReport: new Date(), - cloudSecuritySolution: 'cloud_defend', - logger, - tier, - }); - - // Assert that the result is an empty array - expect(result).toEqual([]); - }); - - it('should handle errors from Elasticsearch', async () => { - // Mock Elasticsearch client's search method to throw an error - mockEsClient.search.mockRejectedValueOnce(new Error('Elasticsearch query failed')); - - const tier = 'essentials' as ProductTier; - - // Call the function with mock parameters - await getCloudDefendUsageRecords({ - esClient: mockEsClient, - projectId: chance.guid(), - taskId: chance.guid(), - lastSuccessfulReport: new Date(), - cloudSecuritySolution: 'cloud_defend', - logger, - tier, - }); - - // Assert that the logger's error method was called with the correct error message - expect(logger.error).toHaveBeenCalledWith( - 'Failed to fetch cloud_defend metering data Error: Elasticsearch query failed' - ); - }); - - it('should return usageRecords when Elasticsearch returns multiple records', async () => { - // Mock Elasticsearch response with multiple records - const agentId1 = chance.guid(); - const agentId2 = chance.guid(); - const eventIngestedStr1 = '2024-05-28T12:10:51Z'; - const eventIngestedStr2 = '2024-05-28T13:10:51Z'; - - // @ts-ignore - mockEsClient.search.mockResolvedValueOnce({ - hits: { - hits: [ - { - _id: 'record1', - _index: 'mockIndex', - _source: { - 'cloud_defend.block_action_enabled': true, - 'agent.id': agentId1, - event: { - ingested: eventIngestedStr1, - }, - }, - }, - { - _id: 'record2', - _index: 'mockIndex', - _source: { - 'cloud_defend.block_action_enabled': true, - 'agent.id': agentId2, - event: { - ingested: eventIngestedStr2, - }, - }, - }, - ], - }, - }); - const tier = 'essentials' as ProductTier; - - // Call the function with mock parameters - const result = await getCloudDefendUsageRecords({ - esClient: mockEsClient, - projectId: chance.guid(), - taskId: chance.guid(), - lastSuccessfulReport: new Date(), - cloudSecuritySolution: 'cloud_defend', - logger, - tier, - }); - - // Assert that the result contains usage records for both records - expect(result).toHaveLength(2); - }); -}); diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/constants.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/constants.ts index fa98707e5ebe..774f7e7fd2ae 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/constants.ts +++ b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/constants.ts @@ -12,9 +12,7 @@ import { CDR_LATEST_NATIVE_VULNERABILITIES_INDEX_PATTERN, } from '@kbn/cloud-security-posture-common'; import { CNVM_POLICY_TEMPLATE } from '@kbn/cloud-security-posture-plugin/common/constants'; -import { INTEGRATION_PACKAGE_NAME } from '@kbn/cloud-defend-plugin/common/constants'; -export const CLOUD_DEFEND_HEARTBEAT_INDEX = 'metrics-cloud_defend.heartbeat-*'; export const CLOUD_SECURITY_TASK_TYPE = 'cloud_security'; export const AGGREGATION_PRECISION_THRESHOLD = 40000; export const ASSETS_SAMPLE_GRANULARITY = '24h'; @@ -23,7 +21,6 @@ export const THRESHOLD_MINUTES = 30; export const CSPM = CSPM_POLICY_TEMPLATE; export const KSPM = KSPM_POLICY_TEMPLATE; export const CNVM = CNVM_POLICY_TEMPLATE; -export const CLOUD_DEFEND = INTEGRATION_PACKAGE_NAME; export const METERING_CONFIGS = { [CSPM]: { @@ -38,10 +35,6 @@ export const METERING_CONFIGS = { index: CDR_LATEST_NATIVE_VULNERABILITIES_INDEX_PATTERN, assets_identifier: 'cloud.instance.id', }, - [CLOUD_DEFEND]: { - index: CLOUD_DEFEND_HEARTBEAT_INDEX, - assets_identifier: 'agent.id', - }, }; // see https://github.com/elastic/security-team/issues/8970 for billable asset definition diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/defend_for_containers_metering.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/defend_for_containers_metering.ts deleted file mode 100644 index 61240df94f9b..000000000000 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/defend_for_containers_metering.ts +++ /dev/null @@ -1,148 +0,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 type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; -import type { - AggregationsAggregate, - SearchResponse, - SortResults, -} from '@elastic/elasticsearch/lib/api/types'; -import type { Tier, UsageRecord } from '../types'; -import type { CloudSecurityMeteringCallbackInput } from './types'; -import { CLOUD_DEFEND, CLOUD_SECURITY_TASK_TYPE, CLOUD_DEFEND_HEARTBEAT_INDEX } from './constants'; - -const BATCH_SIZE = 1000; -const SAMPLE_WEIGHT_SECONDS = 3600; // 1 Hour - -export interface CloudDefendHeartbeat { - '@timestamp': string; - 'agent.id': string; - event: { - ingested: string; - }; -} - -const buildMeteringRecord = ( - agentId: string, - timestampStr: string, - taskId: string, - tier: Tier, - projectId: string -): UsageRecord => { - const timestamp = new Date(timestampStr); - timestamp.setMinutes(0); - timestamp.setSeconds(0); - timestamp.setMilliseconds(0); - const creationTimestamp = new Date(); - const usageRecord = { - id: `${projectId}_${agentId}_${timestamp.toISOString()}`, - usage_timestamp: timestampStr, - creation_timestamp: creationTimestamp.toISOString(), - usage: { - type: CLOUD_SECURITY_TASK_TYPE, - sub_type: CLOUD_DEFEND, - period_seconds: SAMPLE_WEIGHT_SECONDS, - quantity: 1, - }, - source: { - id: taskId, - instance_group_id: projectId, - metadata: { - tier, - }, - }, - }; - - return usageRecord; -}; -export const getUsageRecords = async ( - esClient: ElasticsearchClient, - searchFrom: Date, - searchAfter?: SortResults -): Promise>> => { - return esClient.search( - { - index: CLOUD_DEFEND_HEARTBEAT_INDEX, - size: BATCH_SIZE, - sort: [{ 'event.ingested': 'asc' }, { 'agent.id': 'asc' }], - search_after: searchAfter, - query: { - bool: { - must: [ - { - range: { - 'event.ingested': { - // gt: searchFrom.toISOString(), Tech debt: https://github.com/elastic/security-team/issues/9895 - gte: `now-30m`, - }, - }, - }, - { - term: { - 'cloud_defend.block_action_enabled': true, - }, - }, - ], - }, - }, - }, - { ignore: [404] } - ); -}; - -export const getCloudDefendUsageRecords = async ({ - esClient, - projectId, - taskId, - lastSuccessfulReport, - cloudSecuritySolution, - tier, - logger, -}: CloudSecurityMeteringCallbackInput): Promise => { - try { - let allRecords: UsageRecord[] = []; - let searchAfter: SortResults | undefined; - let fetchMore = true; - - while (fetchMore) { - const usageRecords = await getUsageRecords(esClient, lastSuccessfulReport, searchAfter); - - if (!usageRecords?.hits?.hits?.length) { - break; - } - - const records = usageRecords.hits.hits.reduce((acc, { _source }) => { - if (!_source) { - return acc; - } - - const { event } = _source; - const record = buildMeteringRecord( - _source['agent.id'], - event.ingested, - taskId, - tier, - projectId - ); - - return [...acc, record]; - }, [] as UsageRecord[]); - - allRecords = [...allRecords, ...records]; - - if (usageRecords.hits.hits.length < BATCH_SIZE) { - fetchMore = false; - } else { - searchAfter = usageRecords.hits.hits[usageRecords.hits.hits.length - 1].sort; - } - } - - return allRecords; - } catch (err) { - logger.error(`Failed to fetch ${cloudSecuritySolution} metering data ${err}`); - } -}; diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/types.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/types.ts index 0ca9a7b5b943..c8149e75b720 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/types.ts +++ b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { CSPM, KSPM, CNVM, CLOUD_DEFEND } from './constants'; +import type { CSPM, KSPM, CNVM } from './constants'; import type { MeteringCallbackInput, Tier } from '../types'; export interface CloudDefendAssetCountAggregation { @@ -39,7 +39,7 @@ export interface MinTimestamp { value_as_string: string; } -export type CloudSecuritySolutions = typeof CSPM | typeof KSPM | typeof CNVM | typeof CLOUD_DEFEND; +export type CloudSecuritySolutions = typeof CSPM | typeof KSPM | typeof CNVM; export interface CloudSecurityMeteringCallbackInput extends Omit { diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/tsconfig.json b/x-pack/solutions/security/plugins/security_solution_serverless/tsconfig.json index 7b9a77199aee..6b082dea68d8 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/tsconfig.json +++ b/x-pack/solutions/security/plugins/security_solution_serverless/tsconfig.json @@ -38,7 +38,6 @@ "@kbn/fleet-plugin", "@kbn/serverless-security-settings", "@kbn/core-elasticsearch-server", - "@kbn/cloud-defend-plugin", "@kbn/core-logging-server-mocks", "@kbn/stack-connectors-plugin", "@kbn/actions-plugin", diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts index 1da03fbbcc54..b2753cb17245 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts @@ -18,6 +18,7 @@ export default function alertingTests({ loadTestFile, getService }: FtrProviderC loadTestFile(require.resolve('./builtin_alert_types')); loadTestFile(require.resolve('./mustache_templates.ts')); loadTestFile(require.resolve('./notify_when')); + loadTestFile(require.resolve('./muted_alerts')); loadTestFile(require.resolve('./event_log_alerts')); loadTestFile(require.resolve('./snooze')); loadTestFile(require.resolve('./unsnooze')); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts new file mode 100644 index 000000000000..475a36872e8c --- /dev/null +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { ES_TEST_INDEX_NAME } from '@kbn/alerting-api-integration-helpers'; +import { ALERT_INSTANCE_ID, ALERT_RULE_UUID, ALERT_STATUS } from '@kbn/rule-data-utils'; +import { nodeBuilder } from '@kbn/es-query'; +import { Spaces } from '../../../scenarios'; +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; +import { getUrlPrefix, getTestRuleData, ObjectRemover } from '../../../../common/lib'; + +const alertAsDataIndex = '.internal.alerts-observability.test.alerts.alerts-default-000001'; + +// eslint-disable-next-line import/no-default-export +export default function createDisableRuleTests({ getService }: FtrProviderContext) { + const es = getService('es'); + const retry = getService('retry'); + const supertest = getService('supertest'); + + describe('mutedAlerts', () => { + const objectRemover = new ObjectRemover(supertest); + + const createRule = async () => { + const { body: createdRule } = await supertest + .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send( + getTestRuleData({ + rule_type_id: 'test.always-firing-alert-as-data', + schedule: { interval: '24h' }, + throttle: undefined, + notify_when: undefined, + params: { + index: ES_TEST_INDEX_NAME, + reference: 'test', + }, + }) + ) + .expect(200); + + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); + return createdRule.id; + }; + + const getAlerts = async () => { + const { + hits: { hits: alerts }, + } = await es.search({ + index: alertAsDataIndex, + body: { query: { match_all: {} } }, + }); + + return alerts; + }; + + afterEach(async () => { + await es.deleteByQuery({ + index: alertAsDataIndex, + query: { + match_all: {}, + }, + conflicts: 'proceed', + ignore_unavailable: true, + }); + await objectRemover.removeAll(); + }); + + it('should reflect muted alert instance ids in rule', async () => { + const createdRule1 = await createRule(); + const createdRule2 = await createRule(); + + let alerts: any[] = []; + + await retry.try(async () => { + alerts = await getAlerts(); + + expect(alerts.length).greaterThan(2); + alerts.forEach((activeAlert: any) => { + expect(activeAlert._source[ALERT_STATUS]).eql('active'); + }); + }); + + const alertFromRule1 = alerts.find( + (alert: any) => + alert._source[ALERT_STATUS] === 'active' && + alert._source[ALERT_RULE_UUID] === createdRule1 + ); + + await supertest + .post( + `${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule/${encodeURIComponent( + createdRule1 + )}/alert/${encodeURIComponent(alertFromRule1._source['kibana.alert.instance.id'])}/_mute` + ) + .set('kbn-xsrf', 'foo') + .expect(204); + + const ruleUuids = [createdRule1, createdRule2]; + + const filterNode = nodeBuilder.or( + ruleUuids.map((id) => nodeBuilder.is('alert.id', `alert:${id}`)) + ); + const { body: rules } = await supertest + .post(`${getUrlPrefix(Spaces.space1.id)}/internal/alerting/rules/_find`) + .set('kbn-xsrf', 'foo') + .send({ + filter: JSON.stringify(filterNode), + fields: ['id', 'mutedInstanceIds'], + page: 1, + per_page: ruleUuids.length, + }); + + expect(rules.data.length).to.be(2); + const mutedRule = rules.data.find((rule: { id: string }) => rule.id === createdRule1); + expect(mutedRule.muted_alert_ids).to.contain(alertFromRule1._source[ALERT_INSTANCE_ID]); + }); + }); +} diff --git a/x-pack/test/api_integration/apis/cloud_security_posture/graph.ts b/x-pack/test/api_integration/apis/cloud_security_posture/graph.ts index 4ff483bff343..4823c500a358 100644 --- a/x-pack/test/api_integration/apis/cloud_security_posture/graph.ts +++ b/x-pack/test/api_integration/apis/cloud_security_posture/graph.ts @@ -40,7 +40,7 @@ export default function (providerContext: FtrProviderContext) { it('should return 404 when feature flag is not toggled', async () => { await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', }, diff --git a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts index fb57f0813d84..e325f4bbfa58 100644 --- a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts +++ b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts @@ -10,13 +10,11 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { componentTemplatesApi } from './lib/component_templates.api'; import { componentTemplateHelpers } from './lib/component_template.helpers'; -import { API_BASE_PATH } from './constants'; const CACHE_TEMPLATES = true; export default function ({ getService }: FtrProviderContext) { const log = getService('log'); - const supertest = getService('supertest'); const { createComponentTemplate, @@ -395,21 +393,6 @@ export default function ({ getService }: FtrProviderContext) { }); }); - describe('Privileges', () => { - it('should return privileges result', async () => { - const uri = `${API_BASE_PATH}/component_templates/privileges`; - - const { body } = await supertest.get(uri).set('kbn-xsrf', 'xxx').expect(200); - - expect(body).to.eql({ - hasAllPrivileges: true, - missingPrivileges: { - cluster: [], - }, - }); - }); - }); - describe('Get datastreams', () => { const COMPONENT_NAME = 'test_get_component_template_datastreams'; const COMPONENT = { diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts b/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts index 59077c9ac216..ec2454fdea14 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts @@ -18,7 +18,7 @@ const CHARS_POOL = 'abcdefghijklmnopqrstuvwxyz'; const getRandomString = () => `${chance.string({ pool: CHARS_POOL })}-${Date.now()}`; const deprecationMock = { - 'event.dataset': 'deprecation.elasticsearch', + 'event.dataset': 'elasticsearch.deprecation', '@timestamp': '2021-12-06T16:28:11,104Z', 'log.level': 'CRITICAL', 'log.logger': @@ -30,7 +30,7 @@ const deprecationMock = { message: '[types removal] Specifying include_type_name in get index template requests is deprecated.', 'data_stream.type': 'logs', - 'data_stream.dataset': 'deprecation.elasticsearch', + 'data_stream.dataset': 'elasticsearch.deprecation', 'data_stream.namespace': 'default', 'ecs.version': '1.7', 'elasticsearch.event.category': 'types', diff --git a/x-pack/test/cloud_security_posture_api/config.ts b/x-pack/test/cloud_security_posture_api/config.ts index 4e0ecd1f26e4..212abc50fc9a 100644 --- a/x-pack/test/cloud_security_posture_api/config.ts +++ b/x-pack/test/cloud_security_posture_api/config.ts @@ -5,7 +5,7 @@ * 2.0. */ import { resolve } from 'path'; -import type { FtrConfigProviderContext } from '@kbn/test'; +import { getKibanaCliLoggers, type FtrConfigProviderContext } from '@kbn/test'; import { CLOUD_SECURITY_PLUGIN_VERSION } from '@kbn/cloud-security-posture-plugin/common/constants'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { @@ -21,6 +21,14 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { ...xPackAPITestsConfig.get('kbnTestServer'), serverArgs: [ ...xPackAPITestsConfig.get('kbnTestServer.serverArgs'), + `--logging.loggers=${JSON.stringify([ + ...getKibanaCliLoggers(xPackAPITestsConfig.get('kbnTestServer.serverArgs')), + { + name: 'plugins.cloudSecurityPosture', + level: 'all', + appenders: ['default'], + }, + ])}`, /** * Package version is fixed (not latest) so FTR won't suddenly break when package is changed. * diff --git a/x-pack/test/cloud_security_posture_api/routes/graph.ts b/x-pack/test/cloud_security_posture_api/routes/graph.ts index 08adf73839ea..e2be81a7d40e 100644 --- a/x-pack/test/cloud_security_posture_api/routes/graph.ts +++ b/x-pack/test/cloud_security_posture_api/routes/graph.ts @@ -48,7 +48,7 @@ export default function (providerContext: FtrProviderContext) { supertestWithoutAuth, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', }, @@ -88,7 +88,7 @@ export default function (providerContext: FtrProviderContext) { it('should return 400 when missing `esQuery` field is not of type bool', async () => { await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', esQuery: { @@ -102,7 +102,7 @@ export default function (providerContext: FtrProviderContext) { it('should return 400 with unsupported `esQuery`', async () => { await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', esQuery: { @@ -122,7 +122,7 @@ export default function (providerContext: FtrProviderContext) { it('should return an empty graph / should return 200 when missing `esQuery` field', async () => { const response = await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', }, @@ -136,7 +136,7 @@ export default function (providerContext: FtrProviderContext) { it('should return a graph with nodes and edges by actor', async () => { const response = await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -177,7 +177,7 @@ export default function (providerContext: FtrProviderContext) { it('should return a graph with nodes and edges by alert', async () => { const response = await postGraph(supertest, { query: { - eventIds: ['kabcd1234efgh5678'], + originEventIds: [{ id: 'kabcd1234efgh5678', isAlert: true }], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', }, @@ -204,10 +204,40 @@ export default function (providerContext: FtrProviderContext) { }); }); + it('should return a graph with nodes and edges by origin event', async () => { + const response = await postGraph(supertest, { + query: { + originEventIds: [{ id: 'kabcd1234efgh5678', isAlert: false }], + start: '2024-09-01T00:00:00Z', + end: '2024-09-02T00:00:00Z', + }, + }).expect(result(200)); + + expect(response.body).to.have.property('nodes').length(3); + expect(response.body).to.have.property('edges').length(2); + expect(response.body).not.to.have.property('messages'); + + response.body.nodes.forEach((node: any) => { + expect(node).to.have.property('color'); + expect(node.color).equal( + 'primary', + `node color mismatched [node: ${node.id}] [actual: ${node.color}]` + ); + }); + + response.body.edges.forEach((edge: any) => { + expect(edge).to.have.property('color'); + expect(edge.color).equal( + 'primary', + `edge color mismatched [edge: ${edge.id}] [actual: ${edge.color}]` + ); + }); + }); + it('color of alert of failed event should be danger', async () => { const response = await postGraph(supertest, { query: { - eventIds: ['failed-event'], + originEventIds: [{ id: 'failed-event', isAlert: true }], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', }, @@ -237,7 +267,7 @@ export default function (providerContext: FtrProviderContext) { it('color of event of failed event should be warning', async () => { const response = await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -279,7 +309,7 @@ export default function (providerContext: FtrProviderContext) { it('2 grouped events, 1 failed, 1 success', async () => { const response = await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -327,7 +357,10 @@ export default function (providerContext: FtrProviderContext) { it('should support more than 1 eventIds', async () => { const response = await postGraph(supertest, { query: { - eventIds: ['kabcd1234efgh5678', 'failed-event'], + originEventIds: [ + { id: 'kabcd1234efgh5678', isAlert: true }, + { id: 'failed-event', isAlert: true }, + ], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', }, @@ -357,7 +390,7 @@ export default function (providerContext: FtrProviderContext) { it('should return a graph with nodes and edges by alert and actor', async () => { const response = await postGraph(supertest, { query: { - eventIds: ['kabcd1234efgh5678'], + originEventIds: [{ id: 'kabcd1234efgh5678', isAlert: true }], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -402,7 +435,7 @@ export default function (providerContext: FtrProviderContext) { it('should filter unknown targets', async () => { const response = await postGraph(supertest, { query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -428,7 +461,7 @@ export default function (providerContext: FtrProviderContext) { const response = await postGraph(supertest, { showUnknownTarget: true, query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -454,7 +487,7 @@ export default function (providerContext: FtrProviderContext) { const response = await postGraph(supertest, { nodesLimit: 1, query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { @@ -480,7 +513,7 @@ export default function (providerContext: FtrProviderContext) { it('should support date math', async () => { const response = await postGraph(supertest, { query: { - eventIds: ['kabcd1234efgh5678'], + originEventIds: [{ id: 'kabcd1234efgh5678', isAlert: true }], start: '2024-09-01T12:30:00.000Z||-30m', end: '2024-09-01T12:30:00.000Z||+30m', }, diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts index d04237195118..11333741acf4 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts @@ -281,9 +281,10 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.setScatterplotMatrixRandomizeQueryCheckState(true); await ml.testExecution.logTestStep('displays the scatterplot matrix'); - await ml.dataFrameAnalyticsCreation.assertScatterplotMatrix( - testData.expected.scatterplotMatrixColorStats - ); + // TODO Revisit after Borealis update is fully done + // await ml.dataFrameAnalyticsCreation.assertScatterplotMatrix( + // testData.expected.scatterplotMatrixColorStats + // ); await ml.testExecution.logTestStep('continues to the additional options step'); await ml.dataFrameAnalyticsCreation.continueToAdditionalOptionsStep(); @@ -464,16 +465,17 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsResults.assertResultsTableNotEmpty(); await ml.testExecution.logTestStep('displays the ROC curve chart'); - await ml.commonUI.assertColorsInCanvasElement( - 'mlDFAnalyticsClassificationExplorationRocCurveChart', - testData.expected.rocCurveColorState, - ['#000000'], - undefined, - undefined, - // increased tolerance for ROC curve chart up from 10 to 20 - // since the returned colors vary quite a bit on each run. - 20 - ); + // TODO Revisit after Borealis update is fully done + // await ml.commonUI.assertColorsInCanvasElement( + // 'mlDFAnalyticsClassificationExplorationRocCurveChart', + // testData.expected.rocCurveColorState, + // ['#000000'], + // undefined, + // undefined, + // // increased tolerance for ROC curve chart up from 10 to 20 + // // since the returned colors vary quite a bit on each run. + // 20 + // ); await ml.testExecution.logTestStep( 'sets the sample size to 10000 for the scatterplot matrix' @@ -486,9 +488,10 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsResults.setScatterplotMatrixRandomizeQueryCheckState(true); await ml.testExecution.logTestStep('displays the scatterplot matrix'); - await ml.dataFrameAnalyticsResults.assertScatterplotMatrix( - testData.expected.scatterplotMatrixColorStats - ); + // TODO Revisit after Borealis update is fully done + // await ml.dataFrameAnalyticsResults.assertScatterplotMatrix( + // testData.expected.scatterplotMatrixColorStats + // ); await ml.commonUI.resetAntiAliasing(); }); diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts index b06cb628d21f..52d81d2663cc 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts @@ -272,9 +272,10 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.setScatterplotMatrixRandomizeQueryCheckState(true); await ml.testExecution.logTestStep('displays the scatterplot matrix'); - await ml.dataFrameAnalyticsCreation.assertScatterplotMatrix( - testData.expected.scatterplotMatrixColorsWizard - ); + // TODO Revisit after Borealis update is fully done + // await ml.dataFrameAnalyticsCreation.assertScatterplotMatrix( + // testData.expected.scatterplotMatrixColorsWizard + // ); await ml.testExecution.logTestStep('continues to the additional options step'); await ml.dataFrameAnalyticsCreation.continueToAdditionalOptionsStep(); @@ -459,9 +460,10 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsResults.setScatterplotMatrixRandomizeQueryCheckState(true); await ml.testExecution.logTestStep('displays the scatterplot matrix'); - await ml.dataFrameAnalyticsResults.assertScatterplotMatrix( - testData.expected.scatterplotMatrixColorStatsResults - ); + // TODO Revisit after Borealis update is fully done + // await ml.dataFrameAnalyticsResults.assertScatterplotMatrix( + // testData.expected.scatterplotMatrixColorStatsResults + // ); await ml.commonUI.resetAntiAliasing(); }); diff --git a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts index 4292480c9c61..034c3e4aefd3 100644 --- a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts +++ b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts @@ -422,11 +422,12 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( async assertScatterplotMatrix(expectedValue: CanvasElementColorStats) { await this.assertScatterplotMatrixLoaded(); await this.scrollScatterplotMatrixIntoView(); - await mlCommonUI.assertColorsInCanvasElement( - 'mlAnalyticsCreateJobWizardScatterplotMatrixPanel', - expectedValue, - ['#000000'] - ); + // TODO Revisit after Borealis update is fully done + // await mlCommonUI.assertColorsInCanvasElement( + // 'mlAnalyticsCreateJobWizardScatterplotMatrixPanel', + // expectedValue, + // ['#000000'] + // ); }, async setScatterplotMatrixSampleSizeSelectValue(selectValue: string) { diff --git a/x-pack/test/functional/services/ml/data_frame_analytics_results.ts b/x-pack/test/functional/services/ml/data_frame_analytics_results.ts index 7773a5b9186f..2270f535ee54 100644 --- a/x-pack/test/functional/services/ml/data_frame_analytics_results.ts +++ b/x-pack/test/functional/services/ml/data_frame_analytics_results.ts @@ -284,16 +284,17 @@ export function MachineLearningDataFrameAnalyticsResultsProvider( async assertScatterplotMatrix(expectedValue: CanvasElementColorStats) { await this.assertScatterplotMatrixLoaded(); await this.scrollScatterplotMatrixIntoView(); - await mlCommonUI.assertColorsInCanvasElement( - 'mlDFExpandableSection-splom', - expectedValue, - ['#000000'], - undefined, - undefined, - // increased tolerance up from 10 to 20 - // since the returned randomized colors vary quite a bit on each run. - 20 - ); + // TODO Revisit after Borealis update is fully done + // await mlCommonUI.assertColorsInCanvasElement( + // 'mlDFExpandableSection-splom', + // expectedValue, + // ['#000000'], + // undefined, + // undefined, + // // increased tolerance up from 10 to 20 + // // since the returned randomized colors vary quite a bit on each run. + // 20 + // ); }, async assertFeatureImportanceDecisionPathChartElementsExists() { diff --git a/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/bulk_actions/bulk_edit_rules.cy.ts b/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/bulk_actions/bulk_edit_rules.cy.ts index 5583842ca944..dcc0cebc32ca 100644 --- a/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/bulk_actions/bulk_edit_rules.cy.ts +++ b/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/bulk_actions/bulk_edit_rules.cy.ts @@ -240,7 +240,7 @@ describe( // user can proceed with custom rule editing cy.get(MODAL_CONFIRMATION_BTN) - .should('have.text', `Edit ${existedRulesRows.length} custom rules`) + .should('have.text', `Edit ${existedRulesRows.length} rules`) .click(); // action should finish diff --git a/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/import_export/export_rule.cy.ts b/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/import_export/export_rule.cy.ts index 855c4e17afe0..7f313793866a 100644 --- a/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/import_export/export_rule.cy.ts +++ b/x-pack/test/security_solution_cypress/cypress/e2e/detection_response/rule_management/rule_actions/import_export/export_rule.cy.ts @@ -127,7 +127,7 @@ describe('Export rules', { tags: ['@ess', '@serverless', '@skipInServerlessMKI'] // proceed with exporting only custom rules cy.get(MODAL_CONFIRMATION_BTN) - .should('have.text', `Export ${expectedNumberCustomRulesToBeExported} custom rule`) + .should('have.text', `Export ${expectedNumberCustomRulesToBeExported} rule`) .click(); getAvailablePrebuiltRulesCount().then((availablePrebuiltRulesCount) => { @@ -175,7 +175,7 @@ describe('Export rules', { tags: ['@ess', '@serverless', '@skipInServerlessMKI'] // should display correct number of custom rules when one of them has exceptions cy.get(MODAL_CONFIRMATION_BTN) - .should('have.text', `Export ${expectedNumberCustomRulesToBeExported} custom rules`) + .should('have.text', `Export ${expectedNumberCustomRulesToBeExported} rules`) .click(); cy.get(TOASTER_BODY).should( diff --git a/x-pack/test/security_solution_cypress/cypress/screens/create_new_rule.ts b/x-pack/test/security_solution_cypress/cypress/screens/create_new_rule.ts index 903b463d6f58..483cbf06b625 100644 --- a/x-pack/test/security_solution_cypress/cypress/screens/create_new_rule.ts +++ b/x-pack/test/security_solution_cypress/cypress/screens/create_new_rule.ts @@ -275,10 +275,10 @@ export const ESQL_QUERY_BAR = '[data-test-subj="ruleEsqlQueryBar"]'; export const NEW_TERMS_INPUT_AREA = '[data-test-subj="newTermsInput"]'; export const NEW_TERMS_HISTORY_SIZE = - '[data-test-subj="detectionEngineStepDefineRuleHistoryWindowSize"] [data-test-subj="interval"]'; + '[data-test-subj="historyWindowSize"] [data-test-subj="interval"]'; export const NEW_TERMS_HISTORY_TIME_TYPE = - '[data-test-subj="detectionEngineStepDefineRuleHistoryWindowSize"] [data-test-subj="timeType"]'; + '[data-test-subj="historyWindowSize"] [data-test-subj="timeType"]'; export const LOAD_QUERY_DYNAMICALLY_CHECKBOX = '[data-test-subj="detectionEngineStepDefineRuleShouldLoadQueryDynamically"] input'; diff --git a/x-pack/test/security_solution_cypress/cypress/tasks/rules_bulk_actions.ts b/x-pack/test/security_solution_cypress/cypress/tasks/rules_bulk_actions.ts index c551054fbc6c..501989f6c5b6 100644 --- a/x-pack/test/security_solution_cypress/cypress/tasks/rules_bulk_actions.ts +++ b/x-pack/test/security_solution_cypress/cypress/tasks/rules_bulk_actions.ts @@ -417,20 +417,20 @@ export const checkPrebuiltRulesCannotBeModified = (rulesCount: number) => { export const checkMachineLearningRulesCannotBeModified = (rulesCount: number) => { cy.get(MODAL_CONFIRMATION_BODY).contains( - `${rulesCount} custom machine learning rule (these rules don't have index patterns)` + `${rulesCount} machine learning rule (these rules don't have index patterns)` ); }; export const checkEsqlRulesCannotBeModified = (rulesCount: number) => { cy.get(MODAL_CONFIRMATION_BODY).contains( - `${rulesCount} custom ES|QL rule (these rules don't have index patterns)` + `${rulesCount} ES|QL rule (these rules don't have index patterns)` ); }; -export const waitForMixedRulesBulkEditModal = (customRulesCount: number) => { +export const waitForMixedRulesBulkEditModal = (rulesCount: number) => { cy.get(MODAL_CONFIRMATION_TITLE).should( 'have.text', - `This action can only be applied to ${customRulesCount} custom rules` + `This action can only be applied to ${rulesCount} rules` ); }; @@ -445,7 +445,7 @@ export const scheduleManualRuleRunForSelectedRules = ( if (disabledCount > 0) { cy.get(BULK_MANUAL_RULE_RUN_WARNING_MODAL).should( 'have.text', - `This action can only be applied to ${enabledCount} custom rulesThis action can't be applied to the following rules in your selection:${disabledCount} rules (Cannot schedule manual rule run for disabled rules)CancelSchedule ${enabledCount} custom rules` + `This action can only be applied to ${enabledCount} rulesThis action can't be applied to the following rules in your selection:${disabledCount} rules (Cannot schedule manual rule run for disabled rules)CancelSchedule ${enabledCount} rules` ); cy.get(CONFIRM_MANUAL_RULE_RUN_WARNING_BTN).click(); } diff --git a/x-pack/test_serverless/api_integration/test_suites/observability/ai_assistant/tests/complete/functions/summarize.spec.ts b/x-pack/test_serverless/api_integration/test_suites/observability/ai_assistant/tests/complete/functions/summarize.spec.ts index f949268aa730..823dd15f46b6 100644 --- a/x-pack/test_serverless/api_integration/test_suites/observability/ai_assistant/tests/complete/functions/summarize.spec.ts +++ b/x-pack/test_serverless/api_integration/test_suites/observability/ai_assistant/tests/complete/functions/summarize.spec.ts @@ -11,6 +11,13 @@ import { LlmProxy, createLlmProxy, } from '@kbn/test-suites-xpack/observability_ai_assistant_api_integration/common/create_llm_proxy'; +import { + clearKnowledgeBase, + createKnowledgeBaseModel, + deleteInferenceEndpoint, + deleteKnowledgeBaseModel, + TINY_ELSER, +} from '@kbn/test-suites-xpack/observability_ai_assistant_api_integration/tests/knowledge_base/helpers'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; import { invokeChatCompleteWithFunctionRequest } from './helpers'; import { @@ -22,12 +29,15 @@ import type { InternalRequestHeader, RoleCredentials } from '../../../../../../. export default function ApiTest({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const log = getService('log'); + const ml = getService('ml'); + const es = getService('es'); const observabilityAIAssistantAPIClient = getService('observabilityAIAssistantAPIClient'); const svlUserManager = getService('svlUserManager'); const svlCommonApi = getService('svlCommonApi'); - // Skipped until Elser is available in tests - describe.skip('when calling summarize function', () => { + describe('when calling summarize function', function () { + // TODO: https://github.com/elastic/kibana/issues/192751 + this.tags(['skipMKI']); let roleAuthc: RoleCredentials; let internalReqHeader: InternalRequestHeader; let proxy: LlmProxy; @@ -36,6 +46,19 @@ export default function ApiTest({ getService }: FtrProviderContext) { before(async () => { roleAuthc = await svlUserManager.createM2mApiKeyWithRoleScope('editor'); internalReqHeader = svlCommonApi.getInternalRequestHeader(); + + await createKnowledgeBaseModel(ml); + await observabilityAIAssistantAPIClient + .slsAdmin({ + endpoint: 'POST /internal/observability_ai_assistant/kb/setup', + params: { + query: { + model_id: TINY_ELSER.id, + }, + }, + }) + .expect(200); + proxy = await createLlmProxy(log); connectorId = await createProxyActionConnector({ supertest, @@ -57,10 +80,10 @@ export default function ApiTest({ getService }: FtrProviderContext) { name: 'summarize', trigger: MessageRole.User, arguments: JSON.stringify({ - id: 'my-id', + title: 'My Title', text: 'Hello world', is_correction: false, - confidence: 1, + confidence: 'high', public: false, }), }, @@ -72,6 +95,9 @@ export default function ApiTest({ getService }: FtrProviderContext) { after(async () => { proxy.close(); await deleteActionConnector({ supertest, connectorId, log, roleAuthc, internalReqHeader }); + await deleteKnowledgeBaseModel(ml); + await clearKnowledgeBase(es); + await deleteInferenceEndpoint({ es }); }); it('persists entry in knowledge base', async () => { @@ -80,12 +106,20 @@ export default function ApiTest({ getService }: FtrProviderContext) { params: { query: { query: '', - sortBy: 'doc_id', + sortBy: 'title', sortDirection: 'asc', }, }, }); + const { role, public: isPublic, text, type, user, title } = res.body.entries[0]; + + expect(role).to.eql('assistant_summarization'); + expect(isPublic).to.eql(false); + expect(text).to.eql('Hello world'); + expect(type).to.eql('contextual'); + expect(user?.name).to.eql('elastic_editor'); // "editor" in stateful + expect(title).to.eql('My Title'); expect(res.body.entries).to.have.length(1); }); }); diff --git a/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/graph.ts b/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/graph.ts index aaccdd0e9a41..2cbe40e94549 100644 --- a/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/graph.ts +++ b/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/graph.ts @@ -49,7 +49,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return an empty graph', async () => { const response = await postGraph(supertestViewer, { query: { - eventIds: [], + originEventIds: [], start: 'now-1d/d', end: 'now/d', }, @@ -63,7 +63,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return a graph with nodes and edges by actor', async () => { const response = await postGraph(supertestViewer, { query: { - eventIds: [], + originEventIds: [], start: '2024-09-01T00:00:00Z', end: '2024-09-02T00:00:00Z', esQuery: { diff --git a/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/serverless_metering/cloud_security_metering.ts b/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/serverless_metering/cloud_security_metering.ts index b57dace68c4d..13ac5f96347c 100644 --- a/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/serverless_metering/cloud_security_metering.ts +++ b/x-pack/test_serverless/api_integration/test_suites/security/cloud_security_posture/serverless_metering/cloud_security_metering.ts @@ -9,18 +9,13 @@ import expect from '@kbn/expect'; import { CDR_LATEST_NATIVE_VULNERABILITIES_INDEX_PATTERN } from '@kbn/cloud-security-posture-common'; import { LATEST_FINDINGS_INDEX_DEFAULT_NS } from '@kbn/cloud-security-posture-plugin/common/constants'; import * as http from 'http'; -import { - createPackagePolicy, - createCloudDefendPackagePolicy, -} from '@kbn/test-suites-xpack/api_integration/apis/cloud_security_posture/helper'; +import { createPackagePolicy } from '@kbn/test-suites-xpack/api_integration/apis/cloud_security_posture/helper'; import { EsIndexDataProvider } from '@kbn/test-suites-xpack/cloud_security_posture_api/utils'; import { RoleCredentials } from '../../../../../shared/services'; -import { getMockFindings, getMockDefendForContainersHeartbeats } from './mock_data'; +import { getMockFindings } from './mock_data'; import type { FtrProviderContext } from '../../../../ftr_provider_context'; import { UsageRecord, getInterceptedRequestPayload, setupMockServer } from './mock_usage_server'; -const CLOUD_DEFEND_HEARTBEAT_INDEX_DEFAULT_NS = 'metrics-cloud_defend.heartbeat-default'; - export default function (providerContext: FtrProviderContext) { const mockUsageApiApp = setupMockServer(); const { getService } = providerContext; @@ -32,7 +27,6 @@ export default function (providerContext: FtrProviderContext) { const svlUserManager = getService('svlUserManager'); const supertestWithoutAuth = getService('supertestWithoutAuth'); const findingsIndex = new EsIndexDataProvider(es, LATEST_FINDINGS_INDEX_DEFAULT_NS); - const cloudDefinedIndex = new EsIndexDataProvider(es, CLOUD_DEFEND_HEARTBEAT_INDEX_DEFAULT_NS); const vulnerabilitiesIndex = new EsIndexDataProvider( es, CDR_LATEST_NATIVE_VULNERABILITIES_INDEX_PATTERN @@ -74,7 +68,6 @@ export default function (providerContext: FtrProviderContext) { await findingsIndex.deleteAll(); await vulnerabilitiesIndex.deleteAll(); - await cloudDefinedIndex.deleteAll(); }); afterEach(async () => { @@ -82,7 +75,6 @@ export default function (providerContext: FtrProviderContext) { await esArchiver.unload('x-pack/test/functional/es_archives/fleet/empty_fleet_server'); await findingsIndex.deleteAll(); await vulnerabilitiesIndex.deleteAll(); - await cloudDefinedIndex.deleteAll(); }); after(async () => { await svlUserManager.invalidateM2mApiKeyWithRoleScope(roleAuthc); @@ -202,43 +194,6 @@ export default function (providerContext: FtrProviderContext) { }); }); - it('Should intercept usage API request for Defend for Containers', async () => { - await createCloudDefendPackagePolicy( - supertestWithoutAuth, - agentPolicyId, - roleAuthc, - internalRequestHeader - ); - - const blockActionEnabledHeartbeats = getMockDefendForContainersHeartbeats({ - isBlockActionEnables: true, - numberOfHearbeats: 2, - }); - - const blockActionDisabledHeartbeats = getMockDefendForContainersHeartbeats({ - isBlockActionEnables: false, - numberOfHearbeats: 2, - }); - - await cloudDefinedIndex.addBulk([ - ...blockActionEnabledHeartbeats, - ...blockActionDisabledHeartbeats, - ]); - - let interceptedRequestBody: UsageRecord[] = []; - - await retry.try(async () => { - interceptedRequestBody = getInterceptedRequestPayload(); - expect(interceptedRequestBody.length).to.greaterThan(0); - if (interceptedRequestBody.length > 0) { - const usageSubTypes = interceptedRequestBody.map((record) => record.usage.sub_type); - expect(usageSubTypes).to.contain('cloud_defend'); - expect(interceptedRequestBody.length).to.be(blockActionEnabledHeartbeats.length); - expect(interceptedRequestBody[0].usage.type).to.be('cloud_security'); - } - }); - }); - it('Should intercept usage API request with all integrations usage records', async () => { // Create one package policy - it takes care forCSPM, KSMP and CNVM await createPackagePolicy( @@ -253,13 +208,6 @@ export default function (providerContext: FtrProviderContext) { internalRequestHeader ); - // Create Defend for Containers package policy - await createCloudDefendPackagePolicy( - supertestWithoutAuth, - agentPolicyId, - roleAuthc, - internalRequestHeader - ); const billableFindingsCSPM = getMockFindings({ postureType: 'cspm', isBillableAsset: true, @@ -289,16 +237,6 @@ export default function (providerContext: FtrProviderContext) { numberOfFindings: 11, }); - const blockActionEnabledHeartbeats = getMockDefendForContainersHeartbeats({ - isBlockActionEnables: true, - numberOfHearbeats: 2, - }); - - const blockActionDisabledHeartbeats = getMockDefendForContainersHeartbeats({ - isBlockActionEnables: false, - numberOfHearbeats: 2, - }); - await Promise.all([ findingsIndex.addBulk([ ...billableFindingsCSPM, @@ -307,10 +245,6 @@ export default function (providerContext: FtrProviderContext) { ...notBillableFindingsKSPM, ]), vulnerabilitiesIndex.addBulk([...billableFindingsCNVM]), - cloudDefinedIndex.addBulk([ - ...blockActionEnabledHeartbeats, - ...blockActionDisabledHeartbeats, - ]), ]); // Intercept and verify usage API request @@ -323,16 +257,12 @@ export default function (providerContext: FtrProviderContext) { expect(usageSubTypes).to.contain('cspm'); expect(usageSubTypes).to.contain('kspm'); expect(usageSubTypes).to.contain('cnvm'); - expect(usageSubTypes).to.contain('cloud_defend'); const totalUsageQuantity = interceptedRequestBody.reduce( (acc, record) => acc + record.usage.quantity, 0 ); expect(totalUsageQuantity).to.be( - billableFindingsCSPM.length + - billableFindingsKSPM.length + - billableFindingsCNVM.length + - blockActionEnabledHeartbeats.length + billableFindingsCSPM.length + billableFindingsKSPM.length + billableFindingsCNVM.length ); }); }); diff --git a/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts b/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts index d72aadd9dbb1..66a0a0f33d54 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts @@ -13,94 +13,125 @@ import { FtrProviderContext } from '../../../../ftr_provider_context'; export default ({ getPageObjects, getService }: FtrProviderContext) => { const pageObjects = getPageObjects(['svlCommonPage', 'common', 'indexManagement', 'header']); const browser = getService('browser'); - const security = getService('security'); + const samlAuth = getService('samlAuth'); const testSubjects = getService('testSubjects'); const es = getService('es'); const TEST_COMPONENT_TEMPLATE = '.a_test_component_template'; describe('Index component templates', function () { - before(async () => { - await security.testUser.setRoles(['index_management_user']); - await pageObjects.svlCommonPage.loginAsAdmin(); - }); + describe('with access', () => { + before(async () => { + await pageObjects.svlCommonPage.loginAsAdmin(); + }); - beforeEach(async () => { - await pageObjects.common.navigateToApp('indexManagement'); - // Navigate to the index templates tab - await pageObjects.indexManagement.changeTabs('component_templatesTab'); - await pageObjects.header.waitUntilLoadingHasFinished(); - }); + beforeEach(async () => { + await pageObjects.common.navigateToApp('indexManagement'); + // Navigate to the index templates tab + await pageObjects.indexManagement.changeTabs('component_templatesTab'); + await pageObjects.header.waitUntilLoadingHasFinished(); + }); - it('renders the component templates tab', async () => { - const url = await browser.getCurrentUrl(); - expect(url).to.contain(`/component_templates`); - }); + it('renders the component templates tab', async () => { + const url = await browser.getCurrentUrl(); + expect(url).to.contain(`/component_templates`); + }); - describe('Component templates list', () => { - before(async () => { - await es.cluster.putComponentTemplate({ - name: TEST_COMPONENT_TEMPLATE, - body: { - template: { - settings: { - index: { - number_of_shards: 1, + describe('Component templates list', () => { + before(async () => { + await es.cluster.putComponentTemplate({ + name: TEST_COMPONENT_TEMPLATE, + body: { + template: { + settings: { + index: { + number_of_shards: 1, + }, }, }, }, - }, + }); }); - }); - after(async () => { - await es.cluster.deleteComponentTemplate( - { name: TEST_COMPONENT_TEMPLATE }, - { ignore: [404] } - ); + after(async () => { + await es.cluster.deleteComponentTemplate( + { name: TEST_COMPONENT_TEMPLATE }, + { ignore: [404] } + ); + }); + + it('Displays the test component template in the list', async () => { + const templates = await testSubjects.findAll('componentTemplateTableRow'); + + const getTemplateName = async (template: WebElementWrapper) => { + const templateNameElement = await template.findByTestSubject('templateDetailsLink'); + return await templateNameElement.getVisibleText(); + }; + + const componentTemplateList = await Promise.all( + templates.map((template) => getTemplateName(template)) + ); + + const newComponentTemplateExists = Boolean( + componentTemplateList.find((templateName) => templateName === TEST_COMPONENT_TEMPLATE) + ); + + expect(newComponentTemplateExists).to.be(true); + }); }); - it('Displays the test component template in the list', async () => { - const templates = await testSubjects.findAll('componentTemplateTableRow'); + describe('Create component template', () => { + after(async () => { + await es.cluster.deleteComponentTemplate( + { name: TEST_COMPONENT_TEMPLATE }, + { ignore: [404] } + ); + }); - const getTemplateName = async (template: WebElementWrapper) => { - const templateNameElement = await template.findByTestSubject('templateDetailsLink'); - return await templateNameElement.getVisibleText(); - }; + it('Creates component template', async () => { + await testSubjects.click('createPipelineButton'); - const componentTemplateList = await Promise.all( - templates.map((template) => getTemplateName(template)) - ); + await testSubjects.setValue('nameField', TEST_COMPONENT_TEMPLATE); - const newComponentTemplateExists = Boolean( - componentTemplateList.find((templateName) => templateName === TEST_COMPONENT_TEMPLATE) - ); + // Finish wizard flow + await testSubjects.click('nextButton'); + await testSubjects.click('nextButton'); + await testSubjects.click('nextButton'); + await testSubjects.click('nextButton'); + await testSubjects.click('nextButton'); - expect(newComponentTemplateExists).to.be(true); + expect(await testSubjects.getVisibleText('title')).to.contain(TEST_COMPONENT_TEMPLATE); + }); }); }); - describe('Create component template', () => { - after(async () => { - await es.cluster.deleteComponentTemplate( - { name: TEST_COMPONENT_TEMPLATE }, - { ignore: [404] } - ); + describe('no access', () => { + this.tags(['skipSvlOblt', 'skipMKI']); + before(async () => { + await samlAuth.setCustomRole({ + elasticsearch: { + cluster: ['monitor'], + indices: [{ names: ['*'], privileges: ['all'] }], + }, + kibana: [ + { + base: ['all'], + feature: {}, + spaces: ['*'], + }, + ], + }); + await pageObjects.svlCommonPage.loginWithCustomRole(); + await pageObjects.common.navigateToApp('indexManagement'); + await pageObjects.header.waitUntilLoadingHasFinished(); }); - it('Creates component template', async () => { - await testSubjects.click('createPipelineButton'); - - await testSubjects.setValue('nameField', TEST_COMPONENT_TEMPLATE); - - // Finish wizard flow - await testSubjects.click('nextButton'); - await testSubjects.click('nextButton'); - await testSubjects.click('nextButton'); - await testSubjects.click('nextButton'); - await testSubjects.click('nextButton'); + after(async () => { + await samlAuth.deleteCustomRole(); + }); - expect(await testSubjects.getVisibleText('title')).to.contain(TEST_COMPONENT_TEMPLATE); + it('hides the component templates tab', async () => { + await testSubjects.missingOrFail('component_templatesTab'); }); }); }); diff --git a/yarn.lock b/yarn.lock index 561c7c92280e..839171e5f713 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6137,7 +6137,7 @@ version "0.0.0" uid "" -"@kbn/lists-plugin@link:x-pack/plugins/lists": +"@kbn/lists-plugin@link:x-pack/solutions/security/plugins/lists": version "0.0.0" uid "" @@ -6545,7 +6545,7 @@ version "0.0.0" uid "" -"@kbn/openapi-common@link:packages/kbn-openapi-common": +"@kbn/openapi-common@link:src/platform/packages/shared/kbn-openapi-common": version "0.0.0" uid "" @@ -6953,7 +6953,7 @@ version "0.0.0" uid "" -"@kbn/screenshotting-plugin@link:x-pack/plugins/screenshotting": +"@kbn/screenshotting-plugin@link:x-pack/platform/plugins/shared/screenshotting": version "0.0.0" uid "" @@ -7129,7 +7129,7 @@ version "0.0.0" uid "" -"@kbn/securitysolution-autocomplete@link:packages/kbn-securitysolution-autocomplete": +"@kbn/securitysolution-autocomplete@link:x-pack/solutions/security/packages/kbn-securitysolution-autocomplete": version "0.0.0" uid "" @@ -7141,71 +7141,71 @@ version "0.0.0" uid "" -"@kbn/securitysolution-endpoint-exceptions-common@link:packages/kbn-securitysolution-endpoint-exceptions-common": +"@kbn/securitysolution-endpoint-exceptions-common@link:x-pack/solutions/security/packages/kbn-securitysolution-endpoint-exceptions-common": version "0.0.0" uid "" -"@kbn/securitysolution-es-utils@link:packages/kbn-securitysolution-es-utils": +"@kbn/securitysolution-es-utils@link:src/platform/packages/shared/kbn-securitysolution-es-utils": version "0.0.0" uid "" -"@kbn/securitysolution-exception-list-components@link:packages/kbn-securitysolution-exception-list-components": +"@kbn/securitysolution-exception-list-components@link:x-pack/solutions/security/packages/kbn-securitysolution-exception-list-components": version "0.0.0" uid "" -"@kbn/securitysolution-exceptions-common@link:packages/kbn-securitysolution-exceptions-common": +"@kbn/securitysolution-exceptions-common@link:x-pack/solutions/security/packages/kbn-securitysolution-exceptions-common": version "0.0.0" uid "" -"@kbn/securitysolution-hook-utils@link:packages/kbn-securitysolution-hook-utils": +"@kbn/securitysolution-hook-utils@link:x-pack/solutions/security/packages/kbn-securitysolution-hook-utils": version "0.0.0" uid "" -"@kbn/securitysolution-io-ts-alerting-types@link:packages/kbn-securitysolution-io-ts-alerting-types": +"@kbn/securitysolution-io-ts-alerting-types@link:x-pack/solutions/security/packages/kbn-securitysolution-io-ts-alerting-types": version "0.0.0" uid "" -"@kbn/securitysolution-io-ts-list-types@link:packages/kbn-securitysolution-io-ts-list-types": +"@kbn/securitysolution-io-ts-list-types@link:x-pack/solutions/security/packages/kbn-securitysolution-io-ts-list-types": version "0.0.0" uid "" -"@kbn/securitysolution-io-ts-types@link:packages/kbn-securitysolution-io-ts-types": +"@kbn/securitysolution-io-ts-types@link:src/platform/packages/shared/kbn-securitysolution-io-ts-types": version "0.0.0" uid "" -"@kbn/securitysolution-io-ts-utils@link:packages/kbn-securitysolution-io-ts-utils": +"@kbn/securitysolution-io-ts-utils@link:src/platform/packages/shared/kbn-securitysolution-io-ts-utils": version "0.0.0" uid "" -"@kbn/securitysolution-list-api@link:packages/kbn-securitysolution-list-api": +"@kbn/securitysolution-list-api@link:x-pack/solutions/security/packages/kbn-securitysolution-list-api": version "0.0.0" uid "" -"@kbn/securitysolution-list-constants@link:packages/kbn-securitysolution-list-constants": +"@kbn/securitysolution-list-constants@link:x-pack/solutions/security/packages/kbn-securitysolution-list-constants": version "0.0.0" uid "" -"@kbn/securitysolution-list-hooks@link:packages/kbn-securitysolution-list-hooks": +"@kbn/securitysolution-list-hooks@link:x-pack/solutions/security/packages/kbn-securitysolution-list-hooks": version "0.0.0" uid "" -"@kbn/securitysolution-list-utils@link:packages/kbn-securitysolution-list-utils": +"@kbn/securitysolution-list-utils@link:x-pack/solutions/security/packages/kbn-securitysolution-list-utils": version "0.0.0" uid "" -"@kbn/securitysolution-lists-common@link:packages/kbn-securitysolution-lists-common": +"@kbn/securitysolution-lists-common@link:x-pack/solutions/security/packages/kbn-securitysolution-lists-common": version "0.0.0" uid "" -"@kbn/securitysolution-rules@link:packages/kbn-securitysolution-rules": +"@kbn/securitysolution-rules@link:src/platform/packages/shared/kbn-securitysolution-rules": version "0.0.0" uid "" -"@kbn/securitysolution-t-grid@link:packages/kbn-securitysolution-t-grid": +"@kbn/securitysolution-t-grid@link:x-pack/solutions/security/packages/kbn-securitysolution-t-grid": version "0.0.0" uid "" -"@kbn/securitysolution-utils@link:packages/kbn-securitysolution-utils": +"@kbn/securitysolution-utils@link:x-pack/solutions/security/packages/kbn-securitysolution-utils": version "0.0.0" uid "" @@ -7965,7 +7965,7 @@ version "0.0.0" uid "" -"@kbn/zod-helpers@link:packages/kbn-zod-helpers": +"@kbn/zod-helpers@link:src/platform/packages/shared/kbn-zod-helpers": version "0.0.0" uid ""