From bb2af81d5a84b9bd218917a35056cfadf65ac242 Mon Sep 17 00:00:00 2001 From: Yuliia Naumenko Date: Wed, 21 Jul 2021 13:41:52 +0300 Subject: [PATCH 1/4] [Alerting] Renamed Alerting framework AlertsClient to RulesClient according to the new terminology. --- api_docs/alerting.json | 32 +++---- api_docs/deprecations.mdx | 4 +- api_docs/security.json | 4 +- x-pack/plugins/alerting/README.md | 2 +- x-pack/plugins/alerting/server/index.ts | 6 +- .../invalidate_pending_api_keys/task.ts | 2 +- x-pack/plugins/alerting/server/mocks.ts | 6 +- x-pack/plugins/alerting/server/plugin.test.ts | 6 +- x-pack/plugins/alerting/server/plugin.ts | 30 +++---- .../server/routes/_mock_handler_arguments.ts | 10 +-- .../server/routes/aggregate_rules.test.ts | 16 ++-- .../alerting/server/routes/aggregate_rules.ts | 6 +- .../server/routes/create_rule.test.ts | 34 ++++---- .../alerting/server/routes/create_rule.ts | 6 +- .../server/routes/delete_rule.test.ts | 20 ++--- .../alerting/server/routes/delete_rule.ts | 4 +- .../server/routes/disable_rule.test.ts | 16 ++-- .../alerting/server/routes/disable_rule.ts | 4 +- .../server/routes/enable_rule.test.ts | 16 ++-- .../alerting/server/routes/enable_rule.ts | 4 +- .../alerting/server/routes/find_rules.test.ts | 16 ++-- .../alerting/server/routes/find_rules.ts | 6 +- .../alerting/server/routes/get_rule.test.ts | 20 ++--- .../alerting/server/routes/get_rule.ts | 4 +- .../routes/get_rule_alert_summary.test.ts | 16 ++-- .../server/routes/get_rule_alert_summary.ts | 8 +- .../server/routes/get_rule_state.test.ts | 28 +++--- .../alerting/server/routes/get_rule_state.ts | 4 +- .../alerting/server/routes/health.test.ts | 18 ++-- .../server/routes/legacy/aggregate.test.ts | 16 ++-- .../server/routes/legacy/aggregate.ts | 6 +- .../server/routes/legacy/create.test.ts | 32 +++---- .../alerting/server/routes/legacy/create.ts | 4 +- .../server/routes/legacy/delete.test.ts | 20 ++--- .../alerting/server/routes/legacy/delete.ts | 4 +- .../server/routes/legacy/disable.test.ts | 16 ++-- .../alerting/server/routes/legacy/disable.ts | 4 +- .../server/routes/legacy/enable.test.ts | 16 ++-- .../alerting/server/routes/legacy/enable.ts | 4 +- .../server/routes/legacy/find.test.ts | 16 ++-- .../alerting/server/routes/legacy/find.ts | 6 +- .../alerting/server/routes/legacy/get.test.ts | 20 ++--- .../alerting/server/routes/legacy/get.ts | 4 +- .../legacy/get_alert_instance_summary.test.ts | 16 ++-- .../legacy/get_alert_instance_summary.ts | 4 +- .../routes/legacy/get_alert_state.test.ts | 28 +++--- .../server/routes/legacy/get_alert_state.ts | 4 +- .../server/routes/legacy/health.test.ts | 16 ++-- .../routes/legacy/list_alert_types.test.ts | 18 ++-- .../server/routes/legacy/list_alert_types.ts | 2 +- .../server/routes/legacy/mute_all.test.ts | 16 ++-- .../alerting/server/routes/legacy/mute_all.ts | 4 +- .../routes/legacy/mute_instance.test.ts | 16 ++-- .../server/routes/legacy/mute_instance.ts | 6 +- .../server/routes/legacy/unmute_all.test.ts | 16 ++-- .../server/routes/legacy/unmute_all.ts | 4 +- .../routes/legacy/unmute_instance.test.ts | 16 ++-- .../server/routes/legacy/unmute_instance.ts | 4 +- .../server/routes/legacy/update.test.ts | 24 +++--- .../alerting/server/routes/legacy/update.ts | 4 +- .../routes/legacy/update_api_key.test.ts | 16 ++-- .../server/routes/legacy/update_api_key.ts | 4 +- .../alerting/server/routes/mute_alert.test.ts | 16 ++-- .../alerting/server/routes/mute_alert.ts | 6 +- .../server/routes/mute_all_rule.test.ts | 16 ++-- .../alerting/server/routes/mute_all_rule.ts | 4 +- .../alerting/server/routes/rule_types.test.ts | 18 ++-- .../alerting/server/routes/rule_types.ts | 2 +- .../server/routes/unmute_alert.test.ts | 16 ++-- .../alerting/server/routes/unmute_alert.ts | 6 +- .../server/routes/unmute_all_rule.test.ts | 16 ++-- .../alerting/server/routes/unmute_all_rule.ts | 4 +- .../server/routes/update_rule.test.ts | 26 +++--- .../alerting/server/routes/update_rule.ts | 6 +- .../server/routes/update_rule_api_key.test.ts | 16 ++-- .../server/routes/update_rule_api_key.ts | 4 +- ...ts_client.mock.ts => rules_client.mock.ts} | 16 ++-- .../audit_events.test.ts | 0 .../audit_events.ts | 0 .../{alerts_client => rules_client}/index.ts | 2 +- .../lib/index.ts | 0 .../lib/map_sort_field.test.ts | 0 .../lib/map_sort_field.ts | 0 .../rules_client.ts} | 28 +++--- .../tests/aggregate.test.ts | 14 +-- .../tests/create.test.ts | 74 ++++++++-------- .../tests/delete.test.ts | 40 ++++----- .../tests/disable.test.ts | 38 ++++---- .../tests/enable.test.ts | 72 ++++++++-------- .../tests/find.test.ts | 38 ++++---- .../tests/get.test.ts | 30 +++---- .../tests/get_alert_instance_summary.test.ts | 24 +++--- .../tests/get_alert_state.test.ts | 22 ++--- .../tests/lib.ts | 12 +-- .../tests/list_alert_types.test.ts | 14 +-- .../tests/mute_all.test.ts | 26 +++--- .../tests/mute_instance.test.ts | 34 ++++---- .../tests/unmute_all.test.ts | 26 +++--- .../tests/unmute_instance.test.ts | 34 ++++---- .../tests/update.test.ts | 66 +++++++------- .../tests/update_api_key.test.ts | 40 ++++----- ... => rules_client_conflict_retries.test.ts} | 44 +++++----- ...y.test.ts => rules_client_factory.test.ts} | 86 +++++++++---------- ...ent_factory.ts => rules_client_factory.ts} | 14 +-- .../server/task_runner/task_runner.test.ts | 70 +++++++-------- .../server/task_runner/task_runner.ts | 12 +-- .../task_runner/task_runner_factory.test.ts | 6 +- .../server/task_runner/task_runner_factory.ts | 4 +- x-pack/plugins/alerting/server/types.ts | 4 +- .../ml/server/models/job_service/index.ts | 6 +- .../ml/server/models/job_service/jobs.ts | 8 +- .../plugins/ml/server/routes/job_service.ts | 4 +- .../server/alerts/alerts_factory.test.ts | 12 +-- .../server/alerts/alerts_factory.ts | 8 +- .../server/alerts/base_alert.test.ts | 20 ++--- .../monitoring/server/alerts/base_alert.ts | 12 +-- .../server/lib/alerts/fetch_status.test.ts | 28 +++--- .../server/lib/alerts/fetch_status.ts | 8 +- .../lib/cluster/get_clusters_from_request.js | 6 +- x-pack/plugins/monitoring/server/plugin.ts | 4 +- .../server/routes/api/v1/alerts/enable.ts | 6 +- .../server/routes/api/v1/alerts/status.ts | 6 +- x-pack/plugins/monitoring/server/types.ts | 2 +- .../handlers/install_prepackaged_rules.ts | 2 +- .../create_notifications.test.ts | 18 ++-- .../notifications/create_notifications.ts | 4 +- .../delete_notifications.test.ts | 38 ++++---- .../notifications/delete_notifications.ts | 8 +- .../notifications/find_notifications.ts | 4 +- .../notifications/read_notifications.test.ts | 66 +++++++------- .../notifications/read_notifications.ts | 6 +- .../detection_engine/notifications/types.ts | 8 +- .../update_notifications.test.ts | 24 +++--- .../notifications/update_notifications.ts | 10 +-- .../routes/__mocks__/request_context.ts | 6 +- .../rules/add_prepackaged_rules_route.test.ts | 10 +-- .../rules/add_prepackaged_rules_route.ts | 18 ++-- .../rules/create_rules_bulk_route.test.ts | 10 +-- .../routes/rules/create_rules_bulk_route.ts | 10 +-- .../routes/rules/create_rules_route.test.ts | 10 +-- .../routes/rules/create_rules_route.ts | 10 +-- .../rules/delete_rules_bulk_route.test.ts | 10 +-- .../routes/rules/delete_rules_bulk_route.ts | 8 +- .../routes/rules/delete_rules_route.test.ts | 10 +-- .../routes/rules/delete_rules_route.ts | 8 +- .../routes/rules/export_rules_route.ts | 10 +-- .../routes/rules/find_rules_route.test.ts | 8 +- .../routes/rules/find_rules_route.ts | 6 +- .../rules/find_rules_status_route.test.ts | 8 +- .../routes/rules/find_rules_status_route.ts | 6 +- ...get_prepackaged_rules_status_route.test.ts | 14 +-- .../get_prepackaged_rules_status_route.ts | 8 +- .../routes/rules/import_rules_route.test.ts | 12 +-- .../routes/rules/import_rules_route.ts | 10 +-- .../rules/patch_rules_bulk_route.test.ts | 10 +-- .../routes/rules/patch_rules_bulk_route.ts | 10 +-- .../routes/rules/patch_rules_route.test.ts | 16 ++-- .../routes/rules/patch_rules_route.ts | 10 +-- .../rules/perform_bulk_action_route.test.ts | 10 +-- .../routes/rules/perform_bulk_action_route.ts | 18 ++-- .../routes/rules/read_rules_route.test.ts | 10 +-- .../routes/rules/read_rules_route.ts | 6 +- .../rules/update_rules_bulk_route.test.ts | 10 +-- .../routes/rules/update_rules_bulk_route.ts | 8 +- .../routes/rules/update_rules_route.test.ts | 14 +-- .../routes/rules/update_rules_route.ts | 8 +- .../routes/tags/read_tags_route.ts | 6 +- .../lib/detection_engine/routes/utils.test.ts | 20 ++--- .../lib/detection_engine/routes/utils.ts | 8 +- .../rules/create_rules.mock.ts | 6 +- .../rules/create_rules.test.ts | 8 +- .../detection_engine/rules/create_rules.ts | 4 +- .../rules/delete_rules.test.ts | 12 +-- .../detection_engine/rules/delete_rules.ts | 6 +- .../lib/detection_engine/rules/enable_rule.ts | 10 +-- .../lib/detection_engine/rules/find_rules.ts | 4 +- .../get_existing_prepackaged_rules.test.ts | 64 +++++++------- .../rules/get_existing_prepackaged_rules.ts | 34 ++++---- .../rules/get_export_all.test.ts | 14 +-- .../detection_engine/rules/get_export_all.ts | 6 +- .../rules/get_export_by_object_ids.test.ts | 38 ++++---- .../rules/get_export_by_object_ids.ts | 10 +-- .../rules/install_prepacked_rules.ts | 6 +- .../rules/patch_rules.mock.ts | 6 +- .../rules/patch_rules.test.ts | 20 ++--- .../lib/detection_engine/rules/patch_rules.ts | 8 +- .../detection_engine/rules/read_rules.test.ts | 66 +++++++------- .../lib/detection_engine/rules/read_rules.ts | 8 +- .../lib/detection_engine/rules/types.ts | 16 ++-- .../rules/update_prepacked_rules.test.ts | 10 +-- .../rules/update_prepacked_rules.ts | 16 ++-- .../rules/update_rules.mock.ts | 6 +- .../rules/update_rules.test.ts | 20 ++--- .../detection_engine/rules/update_rules.ts | 10 +-- .../rules/update_rules_notifications.ts | 8 +- .../detection_engine/tags/read_tags.test.ts | 74 ++++++++-------- .../lib/detection_engine/tags/read_tags.ts | 16 ++-- .../helpers.test.ts | 2 +- .../translations/translations/ja-JP.json | 4 +- .../translations/translations/zh-CN.json | 4 +- .../lib/requests/get_monitor_details.ts | 12 +-- .../rest_api/monitors/monitors_details.ts | 4 +- 202 files changed, 1490 insertions(+), 1496 deletions(-) rename x-pack/plugins/alerting/server/{alerts_client.mock.ts => rules_client.mock.ts} (70%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/audit_events.test.ts (100%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/audit_events.ts (100%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/index.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/lib/index.ts (100%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/lib/map_sort_field.test.ts (100%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/lib/map_sort_field.ts (100%) rename x-pack/plugins/alerting/server/{alerts_client/alerts_client.ts => rules_client/rules_client.ts} (98%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/aggregate.test.ts (91%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/create.test.ts (94%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/delete.test.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/disable.test.ts (90%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/enable.test.ts (85%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/find.test.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/get.test.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/get_alert_instance_summary.test.ts (92%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/get_alert_state.test.ts (90%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/lib.ts (87%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/list_alert_types.test.ts (92%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/mute_all.test.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/mute_instance.test.ts (85%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/unmute_all.test.ts (88%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/unmute_instance.test.ts (85%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/update.test.ts (96%) rename x-pack/plugins/alerting/server/{alerts_client => rules_client}/tests/update_api_key.test.ts (89%) rename x-pack/plugins/alerting/server/{alerts_client_conflict_retries.test.ts => rules_client_conflict_retries.test.ts} (88%) rename x-pack/plugins/alerting/server/{alerts_client_factory.test.ts => rules_client_factory.test.ts} (74%) rename x-pack/plugins/alerting/server/{alerts_client_factory.ts => rules_client_factory.ts} (94%) diff --git a/api_docs/alerting.json b/api_docs/alerting.json index ec784dc8fc991..7c860a5c19e34 100644 --- a/api_docs/alerting.json +++ b/api_docs/alerting.json @@ -669,10 +669,10 @@ "children": [ { "parentPluginId": "alerting", - "id": "def-server.AlertingApiRequestHandlerContext.getAlertsClient", + "id": "def-server.AlertingApiRequestHandlerContext.getRulesClient", "type": "Function", "tags": [], - "label": "getAlertsClient", + "label": "getRulesClient", "description": [], "signature": [ "() => ", @@ -680,8 +680,8 @@ "pluginId": "alerting", "scope": "server", "docId": "kibAlertingPluginApi", - "section": "def-server.AlertsClient", - "text": "AlertsClient" + "section": "def-server.RulesClient", + "text": "RulesClient" } ], "source": { @@ -1170,7 +1170,7 @@ "" ], "source": { - "path": "x-pack/plugins/alerting/server/alerts_client/alerts_client.ts", + "path": "x-pack/plugins/alerting/server/rules_client/rules_client.ts", "lineNumber": 140 }, "deprecated": false, @@ -1183,7 +1183,7 @@ "label": "page", "description": [], "source": { - "path": "x-pack/plugins/alerting/server/alerts_client/alerts_client.ts", + "path": "x-pack/plugins/alerting/server/rules_client/rules_client.ts", "lineNumber": 141 }, "deprecated": false @@ -1196,7 +1196,7 @@ "label": "perPage", "description": [], "source": { - "path": "x-pack/plugins/alerting/server/alerts_client/alerts_client.ts", + "path": "x-pack/plugins/alerting/server/rules_client/rules_client.ts", "lineNumber": 142 }, "deprecated": false @@ -1209,7 +1209,7 @@ "label": "total", "description": [], "source": { - "path": "x-pack/plugins/alerting/server/alerts_client/alerts_client.ts", + "path": "x-pack/plugins/alerting/server/rules_client/rules_client.ts", "lineNumber": 143 }, "deprecated": false @@ -1233,7 +1233,7 @@ ", \"enabled\" | \"id\" | \"name\" | \"params\" | \"actions\" | \"tags\" | \"alertTypeId\" | \"consumer\" | \"schedule\" | \"scheduledTaskId\" | \"createdBy\" | \"updatedBy\" | \"createdAt\" | \"updatedAt\" | \"apiKeyOwner\" | \"throttle\" | \"notifyWhen\" | \"muteAll\" | \"mutedInstanceIds\" | \"executionStatus\">[]" ], "source": { - "path": "x-pack/plugins/alerting/server/alerts_client/alerts_client.ts", + "path": "x-pack/plugins/alerting/server/rules_client/rules_client.ts", "lineNumber": 144 }, "deprecated": false @@ -1343,10 +1343,10 @@ }, { "parentPluginId": "alerting", - "id": "def-server.PluginStartContract.getAlertsClientWithRequest", + "id": "def-server.PluginStartContract.getRulesClientWithRequest", "type": "Function", "tags": [], - "label": "getAlertsClientWithRequest", + "label": "getRulesClientWithRequest", "description": [], "signature": [ "(request: ", @@ -1362,8 +1362,8 @@ "pluginId": "alerting", "scope": "server", "docId": "kibAlertingPluginApi", - "section": "def-server.AlertsClient", - "text": "AlertsClient" + "section": "def-server.RulesClient", + "text": "RulesClient" }, ", \"get\" | \"delete\" | \"create\" | \"find\" | \"update\" | \"aggregate\" | \"enable\" | \"disable\" | \"muteAll\" | \"getAlertState\" | \"getAlertInstanceSummary\" | \"updateApiKey\" | \"unmuteAll\" | \"muteInstance\" | \"unmuteInstance\" | \"listAlertTypes\">" ], @@ -1375,7 +1375,7 @@ "children": [ { "parentPluginId": "alerting", - "id": "def-server.PluginStartContract.getAlertsClientWithRequest.$1", + "id": "def-server.PluginStartContract.getRulesClientWithRequest.$1", "type": "Object", "tags": [], "label": "request", @@ -1571,10 +1571,10 @@ }, { "parentPluginId": "alerting", - "id": "def-server.AlertsClient", + "id": "def-server.RulesClient", "type": "Type", "tags": [], - "label": "AlertsClient", + "label": "RulesClient", "description": [], "signature": [ "{ get: = never>({ id, }: { id: string; }) => Promise | [audit_logger.ts#L8](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/authorization/audit_logger.ts#L8) | - | | | [audit_logger.ts#L21](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/authorization/audit_logger.ts#L21) | - | | | [audit_logger.ts#L23](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/authorization/audit_logger.ts#L23) | - | -| | [alerts_client_factory.test.ts#L23](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/alerts_client_factory.test.ts#L23) | - | -| | [alerts_client_factory.test.ts#L98](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/alerts_client_factory.test.ts#L98) | - | +| | [rules_client_factory.test.ts#L23](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/rules_client_factory.test.ts#L23) | - | +| | [rules_client_factory.test.ts#L98](https://github.com/elastic/kibana/tree/master/x-pack/plugins/alerting/server/rules_client_factory.test.ts#L98) | - | diff --git a/api_docs/security.json b/api_docs/security.json index ac0982be3f19e..a02e4cebc5fbf 100644 --- a/api_docs/security.json +++ b/api_docs/security.json @@ -1739,14 +1739,14 @@ { "plugin": "alerting", "link": { - "path": "x-pack/plugins/alerting/server/alerts_client_factory.test.ts", + "path": "x-pack/plugins/alerting/server/rules_client_factory.test.ts", "lineNumber": 23 } }, { "plugin": "alerting", "link": { - "path": "x-pack/plugins/alerting/server/alerts_client_factory.test.ts", + "path": "x-pack/plugins/alerting/server/rules_client_factory.test.ts", "lineNumber": 98 } } diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 62d2f2b57b8e8..02021e666f57f 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -592,7 +592,7 @@ Finally, all users, whether they're granted any role or not, are privileged to c - `listAlertTypes`, but the output is limited to displaying the rule types the user is privileged to `get`. -Attempting to execute any operation the user isn't privileged to execute will result in an Authorization error thrown by the AlertsClient. +Attempting to execute any operation the user isn't privileged to execute will result in an Authorization error thrown by the RulesClient. ## Alert Navigation diff --git a/x-pack/plugins/alerting/server/index.ts b/x-pack/plugins/alerting/server/index.ts index 957bd89f52f36..d3521276ca0a9 100644 --- a/x-pack/plugins/alerting/server/index.ts +++ b/x-pack/plugins/alerting/server/index.ts @@ -6,13 +6,13 @@ */ import type { PublicMethodsOf } from '@kbn/utility-types'; -import { AlertsClient as AlertsClientClass } from './alerts_client'; +import { RulesClient as RulesClientClass } from './rules_client'; import { PluginConfigDescriptor, PluginInitializerContext } from '../../../../src/core/server'; import { AlertingPlugin } from './plugin'; import { configSchema } from './config'; import { AlertsConfigType } from './types'; -export type AlertsClient = PublicMethodsOf; +export type RulesClient = PublicMethodsOf; export type { AlertType, @@ -30,7 +30,7 @@ export type { AlertingApiRequestHandlerContext, } from './types'; export { PluginSetupContract, PluginStartContract } from './plugin'; -export { FindResult } from './alerts_client'; +export { FindResult } from './rules_client'; export { PublicAlertInstance as AlertInstance } from './alert_instance'; export { parseDuration } from './lib'; export { getEsErrorMessage } from './lib/errors'; diff --git a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts index e9c0ed9ef4cab..4ef0e8d25c574 100644 --- a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts +++ b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts @@ -19,7 +19,7 @@ import { TaskManagerSetupContract, TaskManagerStartContract, } from '../../../task_manager/server'; -import { InvalidateAPIKeyResult } from '../alerts_client'; +import { InvalidateAPIKeyResult } from '../rules_client'; import { AlertsConfig } from '../config'; import { timePeriodBeforeDate } from '../lib/get_cadence'; import { AlertingPluginsStart } from '../plugin'; diff --git a/x-pack/plugins/alerting/server/mocks.ts b/x-pack/plugins/alerting/server/mocks.ts index b87e6c8ca8f7c..e9f2b564734db 100644 --- a/x-pack/plugins/alerting/server/mocks.ts +++ b/x-pack/plugins/alerting/server/mocks.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { alertsClientMock } from './alerts_client.mock'; +import { rulesClientMock } from './rules_client.mock'; import { PluginSetupContract, PluginStartContract } from './plugin'; import { AlertInstance } from './alert_instance'; import { @@ -14,7 +14,7 @@ import { } from '../../../../src/core/server/mocks'; import { AlertInstanceContext, AlertInstanceState } from './types'; -export { alertsClientMock }; +export { rulesClientMock }; const createSetupMock = () => { const mock: jest.Mocked = { @@ -27,7 +27,7 @@ const createStartMock = () => { const mock: jest.Mocked = { listTypes: jest.fn(), getAlertingAuthorizationWithRequest: jest.fn(), - getAlertsClientWithRequest: jest.fn().mockResolvedValue(alertsClientMock.create()), + getRulesClientWithRequest: jest.fn().mockResolvedValue(rulesClientMock.create()), getFrameworkHealth: jest.fn(), }; return mock; diff --git a/x-pack/plugins/alerting/server/plugin.test.ts b/x-pack/plugins/alerting/server/plugin.test.ts index 9adc3cc9d6569..43d3f35d770b0 100644 --- a/x-pack/plugins/alerting/server/plugin.test.ts +++ b/x-pack/plugins/alerting/server/plugin.test.ts @@ -112,7 +112,7 @@ describe('Alerting Plugin', () => { }); describe('start()', () => { - describe('getAlertsClientWithRequest()', () => { + describe('getRulesClientWithRequest()', () => { it('throws error when encryptedSavedObjects plugin is missing encryption key', async () => { const context = coreMock.createPluginInitializerContext({ healthCheck: { @@ -146,7 +146,7 @@ describe('Alerting Plugin', () => { expect(encryptedSavedObjectsSetup.canEncrypt).toEqual(false); expect(() => - startContract.getAlertsClientWithRequest({} as KibanaRequest) + startContract.getRulesClientWithRequest({} as KibanaRequest) ).toThrowErrorMatchingInlineSnapshot( `"Unable to create alerts client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command."` ); @@ -201,7 +201,7 @@ describe('Alerting Plugin', () => { }, getSavedObjectsClient: jest.fn(), } as unknown) as KibanaRequest; - startContract.getAlertsClientWithRequest(fakeRequest); + startContract.getRulesClientWithRequest(fakeRequest); }); }); diff --git a/x-pack/plugins/alerting/server/plugin.ts b/x-pack/plugins/alerting/server/plugin.ts index b906983017ff6..b1e42b315f119 100644 --- a/x-pack/plugins/alerting/server/plugin.ts +++ b/x-pack/plugins/alerting/server/plugin.ts @@ -17,10 +17,10 @@ import { } from '../../encrypted_saved_objects/server'; import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_manager/server'; import { SpacesPluginStart } from '../../spaces/server'; -import { AlertsClient } from './alerts_client'; +import { RulesClient } from './rules_client'; import { AlertTypeRegistry } from './alert_type_registry'; import { TaskRunnerFactory } from './task_runner'; -import { AlertsClientFactory } from './alerts_client_factory'; +import { RulesClientFactory } from './rules_client_factory'; import { ILicenseState, LicenseState } from './lib/license_state'; import { KibanaRequest, @@ -106,7 +106,7 @@ export interface PluginSetupContract { export interface PluginStartContract { listTypes: AlertTypeRegistry['list']; - getAlertsClientWithRequest(request: KibanaRequest): PublicMethodsOf; + getRulesClientWithRequest(request: KibanaRequest): PublicMethodsOf; getAlertingAuthorizationWithRequest( request: KibanaRequest ): PublicMethodsOf; @@ -142,7 +142,7 @@ export class AlertingPlugin { private licenseState: ILicenseState | null = null; private isESOCanEncrypt?: boolean; private security?: SecurityPluginSetup; - private readonly alertsClientFactory: AlertsClientFactory; + private readonly rulesClientFactory: RulesClientFactory; private readonly alertingAuthorizationClientFactory: AlertingAuthorizationClientFactory; private readonly telemetryLogger: Logger; private readonly kibanaVersion: PluginInitializerContext['env']['packageInfo']['version']; @@ -155,7 +155,7 @@ export class AlertingPlugin { this.config = initializerContext.config.create().pipe(first()).toPromise(); this.logger = initializerContext.logger.get(); this.taskRunnerFactory = new TaskRunnerFactory(); - this.alertsClientFactory = new AlertsClientFactory(); + this.rulesClientFactory = new RulesClientFactory(); this.alertingAuthorizationClientFactory = new AlertingAuthorizationClientFactory(); this.telemetryLogger = initializerContext.logger.get('usage'); this.kibanaIndexConfig = initializerContext.config.legacy.globalConfig$; @@ -306,7 +306,7 @@ export class AlertingPlugin { logger, taskRunnerFactory, alertTypeRegistry, - alertsClientFactory, + rulesClientFactory, alertingAuthorizationClientFactory, security, licenseState, @@ -334,7 +334,7 @@ export class AlertingPlugin { features: plugins.features, }); - alertsClientFactory.initialize({ + rulesClientFactory.initialize({ alertTypeRegistry: alertTypeRegistry!, logger, taskManager: plugins.taskManager, @@ -351,13 +351,13 @@ export class AlertingPlugin { authorization: alertingAuthorizationClientFactory, }); - const getAlertsClientWithRequest = (request: KibanaRequest) => { + const getRulesClientWithRequest = (request: KibanaRequest) => { if (isESOCanEncrypt !== true) { throw new Error( `Unable to create alerts client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.` ); } - return alertsClientFactory!.create(request, core.savedObjects); + return rulesClientFactory!.create(request, core.savedObjects); }; const getAlertingAuthorizationWithRequest = (request: KibanaRequest) => { @@ -367,7 +367,7 @@ export class AlertingPlugin { taskRunnerFactory.initialize({ logger, getServices: this.getServicesFactory(core.savedObjects, core.elasticsearch), - getAlertsClientWithRequest, + getRulesClientWithRequest, spaceIdToNamespace, actionsPlugin: plugins.actions, encryptedSavedObjectsClient, @@ -379,7 +379,7 @@ export class AlertingPlugin { }); this.eventLogService!.registerSavedObjectProvider('alert', (request) => { - const client = getAlertsClientWithRequest(request); + const client = getRulesClientWithRequest(request); return (objects?: SavedObjectsBulkGetObject[]) => objects ? Promise.all(objects.map(async (objectItem) => await client.get({ id: objectItem.id }))) @@ -394,7 +394,7 @@ export class AlertingPlugin { return { listTypes: alertTypeRegistry!.list.bind(this.alertTypeRegistry!), getAlertingAuthorizationWithRequest, - getAlertsClientWithRequest, + getRulesClientWithRequest, getFrameworkHealth: async () => await getHealth(core.savedObjects.createInternalRepository(['alert'])), }; @@ -403,12 +403,12 @@ export class AlertingPlugin { private createRouteHandlerContext = ( core: CoreSetup ): IContextProvider => { - const { alertTypeRegistry, alertsClientFactory } = this; + const { alertTypeRegistry, rulesClientFactory } = this; return async function alertsRouteHandlerContext(context, request) { const [{ savedObjects }] = await core.getStartServices(); return { - getAlertsClient: () => { - return alertsClientFactory!.create(request, savedObjects); + getRulesClient: () => { + return rulesClientFactory!.create(request, savedObjects); }, listTypes: alertTypeRegistry!.list.bind(alertTypeRegistry!), getFrameworkHealth: async () => diff --git a/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts index 7bab31fa4c89a..de1d0d1326710 100644 --- a/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts @@ -9,18 +9,18 @@ import { KibanaRequest, KibanaResponseFactory } from 'kibana/server'; import { identity } from 'lodash'; import type { MethodKeysOf } from '@kbn/utility-types'; import { httpServerMock } from '../../../../../src/core/server/mocks'; -import { alertsClientMock, AlertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock, RulesClientMock } from '../rules_client.mock'; import { AlertsHealth, AlertType } from '../../common'; import type { AlertingRequestHandlerContext } from '../types'; export function mockHandlerArguments( { - alertsClient = alertsClientMock.create(), + rulesClient = rulesClientMock.create(), listTypes: listTypesRes = [], getFrameworkHealth, areApiKeysEnabled, }: { - alertsClient?: AlertsClientMock; + rulesClient?: RulesClientMock; listTypes?: AlertType[]; getFrameworkHealth?: jest.MockInstance, []> & (() => Promise); @@ -38,8 +38,8 @@ export function mockHandlerArguments( ({ alerting: { listTypes, - getAlertsClient() { - return alertsClient || alertsClientMock.create(); + getRulesClient() { + return rulesClient || rulesClientMock.create(); }, getFrameworkHealth, areApiKeysEnabled: areApiKeysEnabled ? areApiKeysEnabled : () => Promise.resolve(true), diff --git a/x-pack/plugins/alerting/server/routes/aggregate_rules.test.ts b/x-pack/plugins/alerting/server/routes/aggregate_rules.test.ts index 26c06eae33d0a..233e605cf7f5b 100644 --- a/x-pack/plugins/alerting/server/routes/aggregate_rules.test.ts +++ b/x-pack/plugins/alerting/server/routes/aggregate_rules.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -42,10 +42,10 @@ describe('aggregateRulesRoute', () => { unknown: 0, }, }; - alertsClient.aggregate.mockResolvedValueOnce(aggregateResult); + rulesClient.aggregate.mockResolvedValueOnce(aggregateResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { default_search_operator: 'AND', @@ -68,8 +68,8 @@ describe('aggregateRulesRoute', () => { } `); - expect(alertsClient.aggregate).toHaveBeenCalledTimes(1); - expect(alertsClient.aggregate.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.aggregate).toHaveBeenCalledTimes(1); + expect(rulesClient.aggregate.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "options": Object { @@ -100,7 +100,7 @@ describe('aggregateRulesRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.aggregate.mockResolvedValueOnce({ + rulesClient.aggregate.mockResolvedValueOnce({ alertExecutionStatus: { ok: 15, error: 2, @@ -111,7 +111,7 @@ describe('aggregateRulesRoute', () => { }); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { default_search_operator: 'OR', diff --git a/x-pack/plugins/alerting/server/routes/aggregate_rules.ts b/x-pack/plugins/alerting/server/routes/aggregate_rules.ts index ecebd7851af6b..f91231f9ac48a 100644 --- a/x-pack/plugins/alerting/server/routes/aggregate_rules.ts +++ b/x-pack/plugins/alerting/server/routes/aggregate_rules.ts @@ -8,7 +8,7 @@ import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ILicenseState } from '../lib'; -import { AggregateResult, AggregateOptions } from '../alerts_client'; +import { AggregateResult, AggregateOptions } from '../rules_client'; import { RewriteResponseCase, RewriteRequestCase, verifyAccessAndContext } from './lib'; import { AlertingRequestHandlerContext, INTERNAL_BASE_ALERTING_API_PATH } from '../types'; @@ -64,12 +64,12 @@ export const aggregateRulesRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const options = rewriteQueryReq({ ...req.query, has_reference: req.query.has_reference || undefined, }); - const aggregateResult = await alertsClient.aggregate({ options }); + const aggregateResult = await rulesClient.aggregate({ options }); return res.ok({ body: rewriteBodyRes(aggregateResult), }); diff --git a/x-pack/plugins/alerting/server/routes/create_rule.test.ts b/x-pack/plugins/alerting/server/routes/create_rule.test.ts index 5dbc5014ef6ba..72c67b392be56 100644 --- a/x-pack/plugins/alerting/server/routes/create_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/create_rule.test.ts @@ -11,13 +11,13 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { CreateOptions } from '../alerts_client'; -import { alertsClientMock } from '../alerts_client.mock'; +import { CreateOptions } from '../rules_client'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib'; import { AsApiContract } from './lib'; import { SanitizedAlert } from '../types'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -112,10 +112,10 @@ describe('createRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id?}"`); - alertsClient.create.mockResolvedValueOnce(mockedAlert); + rulesClient.create.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { body: ruleToCreate, }, @@ -124,8 +124,8 @@ describe('createRuleRoute', () => { expect(await handler(context, req, res)).toEqual({ body: createResult }); - expect(alertsClient.create).toHaveBeenCalledTimes(1); - expect(alertsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.create).toHaveBeenCalledTimes(1); + expect(rulesClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -180,13 +180,13 @@ describe('createRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id?}"`); - alertsClient.create.mockResolvedValueOnce({ + rulesClient.create.mockResolvedValueOnce({ ...mockedAlert, id: 'custom-id', }); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: 'custom-id' }, body: ruleToCreate, @@ -196,8 +196,8 @@ describe('createRuleRoute', () => { expect(await handler(context, req, res)).toEqual({ body: expectedResult }); - expect(alertsClient.create).toHaveBeenCalledTimes(1); - expect(alertsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.create).toHaveBeenCalledTimes(1); + expect(rulesClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -246,9 +246,9 @@ describe('createRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockResolvedValueOnce(mockedAlert); + rulesClient.create.mockResolvedValueOnce(mockedAlert); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { body: ruleToCreate }); + const [context, req, res] = mockHandlerArguments({ rulesClient }, { body: ruleToCreate }); await handler(context, req, res); @@ -267,9 +267,9 @@ describe('createRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockResolvedValueOnce(mockedAlert); + rulesClient.create.mockResolvedValueOnce(mockedAlert); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}); expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); @@ -284,9 +284,9 @@ describe('createRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.create.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { body: ruleToCreate }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { body: ruleToCreate }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/create_rule.ts b/x-pack/plugins/alerting/server/routes/create_rule.ts index 4e31db970ccc6..eb5e0afe9fa9a 100644 --- a/x-pack/plugins/alerting/server/routes/create_rule.ts +++ b/x-pack/plugins/alerting/server/routes/create_rule.ts @@ -8,7 +8,7 @@ import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { validateDurationSchema, ILicenseState, AlertTypeDisabledError } from '../lib'; -import { CreateOptions } from '../alerts_client'; +import { CreateOptions } from '../rules_client'; import { RewriteRequestCase, RewriteResponseCase, @@ -112,11 +112,11 @@ export const createRuleRoute = ( handleDisabledApiKeysError( router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const rule = req.body; const params = req.params; try { - const createdRule: SanitizedAlert = await alertsClient.create( + const createdRule: SanitizedAlert = await rulesClient.create( { data: rewriteBodyReq({ ...rule, diff --git a/x-pack/plugins/alerting/server/routes/delete_rule.test.ts b/x-pack/plugins/alerting/server/routes/delete_rule.test.ts index 16d344548fc25..b7d1a2c9c7fc6 100644 --- a/x-pack/plugins/alerting/server/routes/delete_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/delete_rule.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('deleteRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}"`); - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('deleteRuleRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.delete).toHaveBeenCalledTimes(1); - expect(alertsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.delete).toHaveBeenCalledTimes(1); + expect(rulesClient.delete.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,10 +67,10 @@ describe('deleteRuleRoute', () => { const [, handler] = router.delete.mock.calls[0]; - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, } @@ -93,10 +93,10 @@ describe('deleteRuleRoute', () => { const [, handler] = router.delete.mock.calls[0]; - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { id: '1', } diff --git a/x-pack/plugins/alerting/server/routes/delete_rule.ts b/x-pack/plugins/alerting/server/routes/delete_rule.ts index 724eb5352ed23..27da50b180fe5 100644 --- a/x-pack/plugins/alerting/server/routes/delete_rule.ts +++ b/x-pack/plugins/alerting/server/routes/delete_rule.ts @@ -28,9 +28,9 @@ export const deleteRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - await alertsClient.delete({ id }); + await rulesClient.delete({ id }); return res.noContent(); }) ) diff --git a/x-pack/plugins/alerting/server/routes/disable_rule.test.ts b/x-pack/plugins/alerting/server/routes/disable_rule.test.ts index a77a8443a97fb..173f1df7e1e73 100644 --- a/x-pack/plugins/alerting/server/routes/disable_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/disable_rule.test.ts @@ -9,10 +9,10 @@ import { disableRuleRoute } from './disable_rule'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('disableRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}/_disable"`); - alertsClient.disable.mockResolvedValueOnce(); + rulesClient.disable.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('disableRuleRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.disable).toHaveBeenCalledTimes(1); - expect(alertsClient.disable.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.disable).toHaveBeenCalledTimes(1); + expect(rulesClient.disable.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,9 +67,9 @@ describe('disableRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.disable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.disable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/disable_rule.ts b/x-pack/plugins/alerting/server/routes/disable_rule.ts index 2a2f0f4aa25fc..81f77cb130d50 100644 --- a/x-pack/plugins/alerting/server/routes/disable_rule.ts +++ b/x-pack/plugins/alerting/server/routes/disable_rule.ts @@ -28,10 +28,10 @@ export const disableRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.disable({ id }); + await rulesClient.disable({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/enable_rule.test.ts b/x-pack/plugins/alerting/server/routes/enable_rule.test.ts index 71889d153ce5f..4c0bae2587924 100644 --- a/x-pack/plugins/alerting/server/routes/enable_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/enable_rule.test.ts @@ -9,10 +9,10 @@ import { enableRuleRoute } from './enable_rule'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('enableRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}/_enable"`); - alertsClient.enable.mockResolvedValueOnce(); + rulesClient.enable.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('enableRuleRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.enable).toHaveBeenCalledTimes(1); - expect(alertsClient.enable.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.enable).toHaveBeenCalledTimes(1); + expect(rulesClient.enable.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,9 +67,9 @@ describe('enableRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.enable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.enable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/enable_rule.ts b/x-pack/plugins/alerting/server/routes/enable_rule.ts index 9c7526630d0a3..5d77e375cfce6 100644 --- a/x-pack/plugins/alerting/server/routes/enable_rule.ts +++ b/x-pack/plugins/alerting/server/routes/enable_rule.ts @@ -28,10 +28,10 @@ export const enableRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.enable({ id }); + await rulesClient.enable({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/find_rules.test.ts b/x-pack/plugins/alerting/server/routes/find_rules.test.ts index 98bb3c77daecc..e0da7b0645748 100644 --- a/x-pack/plugins/alerting/server/routes/find_rules.test.ts +++ b/x-pack/plugins/alerting/server/routes/find_rules.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -39,10 +39,10 @@ describe('findRulesRoute', () => { total: 0, data: [], }; - alertsClient.find.mockResolvedValueOnce(findResult); + rulesClient.find.mockResolvedValueOnce(findResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { per_page: 1, @@ -64,8 +64,8 @@ describe('findRulesRoute', () => { } `); - expect(alertsClient.find).toHaveBeenCalledTimes(1); - expect(alertsClient.find.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.find).toHaveBeenCalledTimes(1); + expect(rulesClient.find.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "options": Object { @@ -95,7 +95,7 @@ describe('findRulesRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.find.mockResolvedValueOnce({ + rulesClient.find.mockResolvedValueOnce({ page: 1, perPage: 1, total: 0, @@ -103,7 +103,7 @@ describe('findRulesRoute', () => { }); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { per_page: 1, diff --git a/x-pack/plugins/alerting/server/routes/find_rules.ts b/x-pack/plugins/alerting/server/routes/find_rules.ts index 06b7960b67297..ef62341290228 100644 --- a/x-pack/plugins/alerting/server/routes/find_rules.ts +++ b/x-pack/plugins/alerting/server/routes/find_rules.ts @@ -9,7 +9,7 @@ import { omit } from 'lodash'; import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ILicenseState } from '../lib'; -import { FindOptions, FindResult } from '../alerts_client'; +import { FindOptions, FindResult } from '../rules_client'; import { RewriteRequestCase, RewriteResponseCase, verifyAccessAndContext } from './lib'; import { AlertTypeParams, AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../types'; @@ -118,7 +118,7 @@ export const findRulesRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const options = rewriteQueryReq({ ...req.query, @@ -126,7 +126,7 @@ export const findRulesRoute = ( search_fields: searchFieldsAsArray(req.query.search_fields), }); - const findResult = await alertsClient.find({ options }); + const findResult = await rulesClient.find({ options }); return res.ok({ body: rewriteBodyRes(findResult), }); diff --git a/x-pack/plugins/alerting/server/routes/get_rule.test.ts b/x-pack/plugins/alerting/server/routes/get_rule.test.ts index fc900797cdc89..47503374394f8 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule.test.ts @@ -11,11 +11,11 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { SanitizedAlert } from '../types'; import { AsApiContract } from './lib'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -98,10 +98,10 @@ describe('getRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}"`); - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -109,8 +109,8 @@ describe('getRuleRoute', () => { ); await handler(context, req, res); - expect(alertsClient.get).toHaveBeenCalledTimes(1); - expect(alertsClient.get.mock.calls[0][0].id).toEqual('1'); + expect(rulesClient.get).toHaveBeenCalledTimes(1); + expect(rulesClient.get.mock.calls[0][0].id).toEqual('1'); expect(res.ok).toHaveBeenCalledWith({ body: getResult, @@ -125,10 +125,10 @@ describe('getRuleRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -152,10 +152,10 @@ describe('getRuleRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/alerting/server/routes/get_rule.ts b/x-pack/plugins/alerting/server/routes/get_rule.ts index fd03f32047e74..c860ae725a253 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule.ts @@ -72,9 +72,9 @@ export const getRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - const rule = await alertsClient.get({ id }); + const rule = await rulesClient.get({ id }); return res.ok({ body: rewriteBodyRes(rule), }); diff --git a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts index fab6d46219a37..f0f34ae5756b4 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts @@ -10,10 +10,10 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from 'src/core/server'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertInstanceSummary } from '../types'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -50,10 +50,10 @@ describe('getRuleAlertSummaryRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/_alert_summary"`); - alertsClient.getAlertInstanceSummary.mockResolvedValueOnce(mockedAlertInstanceSummary); + rulesClient.getAlertInstanceSummary.mockResolvedValueOnce(mockedAlertInstanceSummary); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -65,8 +65,8 @@ describe('getRuleAlertSummaryRoute', () => { await handler(context, req, res); - expect(alertsClient.getAlertInstanceSummary).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertInstanceSummary.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertInstanceSummary).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertInstanceSummary.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "dateStart": undefined, @@ -86,12 +86,12 @@ describe('getRuleAlertSummaryRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.getAlertInstanceSummary = jest + rulesClient.getAlertInstanceSummary = jest .fn() .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', diff --git a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts index 7a3679851d53f..5bb8c5efd0d79 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts @@ -8,7 +8,7 @@ import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ILicenseState } from '../lib'; -import { GetAlertInstanceSummaryParams } from '../alerts_client'; +import { GetAlertInstanceSummaryParams } from '../rules_client'; import { RewriteRequestCase, RewriteResponseCase, verifyAccessAndContext } from './lib'; import { AlertingRequestHandlerContext, @@ -65,11 +65,9 @@ export const getRuleAlertSummaryRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - const summary = await alertsClient.getAlertInstanceSummary( - rewriteReq({ id, ...req.query }) - ); + const summary = await rulesClient.getAlertInstanceSummary(rewriteReq({ id, ...req.query })); return res.ok({ body: rewriteBodyRes(summary) }); }) ) diff --git a/x-pack/plugins/alerting/server/routes/get_rule_state.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_state.test.ts index 71e06b60d1026..36f1e6c5f8f42 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_state.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_state.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from 'src/core/server'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -50,10 +50,10 @@ describe('getRuleStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/state"`); - alertsClient.getAlertState.mockResolvedValueOnce(mockedAlertState); + rulesClient.getAlertState.mockResolvedValueOnce(mockedAlertState); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -64,8 +64,8 @@ describe('getRuleStateRoute', () => { await handler(context, req, res); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -86,10 +86,10 @@ describe('getRuleStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/state"`); - alertsClient.getAlertState.mockResolvedValueOnce(undefined); + rulesClient.getAlertState.mockResolvedValueOnce(undefined); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -100,8 +100,8 @@ describe('getRuleStateRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -122,12 +122,12 @@ describe('getRuleStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/state"`); - alertsClient.getAlertState = jest + rulesClient.getAlertState = jest .fn() .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -138,8 +138,8 @@ describe('getRuleStateRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", diff --git a/x-pack/plugins/alerting/server/routes/get_rule_state.ts b/x-pack/plugins/alerting/server/routes/get_rule_state.ts index 08087d1ece8af..6337bed39f150 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_state.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_state.ts @@ -44,9 +44,9 @@ export const getRuleStateRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - const state = await alertsClient.getAlertState({ id }); + const state = await rulesClient.getAlertState({ id }); return state ? res.ok({ body: rewriteBodyRes(state) }) : res.noContent(); }) ) diff --git a/x-pack/plugins/alerting/server/routes/health.test.ts b/x-pack/plugins/alerting/server/routes/health.test.ts index 40ad2721e816e..7c00b04ae7ef3 100644 --- a/x-pack/plugins/alerting/server/routes/health.test.ts +++ b/x-pack/plugins/alerting/server/routes/health.test.ts @@ -11,10 +11,10 @@ import { mockHandlerArguments } from './_mock_handler_arguments'; import { verifyApiAccess } from '../lib/license_api_access'; import { licenseStateMock } from '../lib/license_state.mock'; import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/server/mocks'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { HealthStatus } from '../types'; import { alertsMock } from '../mocks'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -62,7 +62,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}, ['ok']); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}, ['ok']); await handler(context, req, res); @@ -78,7 +78,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -114,7 +114,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -150,7 +150,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -187,7 +187,7 @@ describe('healthRoute', () => { const [context, req, res] = mockHandlerArguments( { - alertsClient, + rulesClient, getFrameworkHealth: alerting.getFrameworkHealth, areApiKeysEnabled: () => Promise.resolve(false), }, @@ -227,7 +227,7 @@ describe('healthRoute', () => { const [context, req, res] = mockHandlerArguments( { - alertsClient, + rulesClient, getFrameworkHealth: alerting.getFrameworkHealth, areApiKeysEnabled: () => Promise.resolve(false), }, @@ -266,7 +266,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/aggregate.test.ts b/x-pack/plugins/alerting/server/routes/legacy/aggregate.test.ts index 94331902d9ace..22d7d5c4bc94f 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/aggregate.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/aggregate.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -42,10 +42,10 @@ describe('aggregateAlertRoute', () => { unknown: 0, }, }; - alertsClient.aggregate.mockResolvedValueOnce(aggregateResult); + rulesClient.aggregate.mockResolvedValueOnce(aggregateResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { default_search_operator: 'AND', @@ -68,8 +68,8 @@ describe('aggregateAlertRoute', () => { } `); - expect(alertsClient.aggregate).toHaveBeenCalledTimes(1); - expect(alertsClient.aggregate.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.aggregate).toHaveBeenCalledTimes(1); + expect(rulesClient.aggregate.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "options": Object { @@ -92,7 +92,7 @@ describe('aggregateAlertRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.aggregate.mockResolvedValueOnce({ + rulesClient.aggregate.mockResolvedValueOnce({ alertExecutionStatus: { ok: 15, error: 2, @@ -103,7 +103,7 @@ describe('aggregateAlertRoute', () => { }); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { default_search_operator: 'OR', diff --git a/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts b/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts index 91189fdf3d0a6..099b088abdf39 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts @@ -11,7 +11,7 @@ import { ILicenseState } from '../../lib/license_state'; import { verifyApiAccess } from '../../lib/license_api_access'; import { LEGACY_BASE_ALERT_API_PATH } from '../../../common'; import { renameKeys } from './../lib/rename_keys'; -import { FindOptions } from '../../alerts_client'; +import { FindOptions } from '../../rules_client'; // config definition const querySchema = schema.object({ @@ -46,7 +46,7 @@ export const aggregateAlertRoute = (router: AlertingRouter, licenseState: ILicen if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const query = req.query; const renameMap = { @@ -64,7 +64,7 @@ export const aggregateAlertRoute = (router: AlertingRouter, licenseState: ILicen : [query.search_fields]; } - const aggregateResult = await alertsClient.aggregate({ options }); + const aggregateResult = await rulesClient.aggregate({ options }); return res.ok({ body: aggregateResult, }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/create.test.ts b/x-pack/plugins/alerting/server/routes/legacy/create.test.ts index fd3252d2fca77..70bc786a00d82 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/create.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/create.test.ts @@ -10,11 +10,11 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { Alert } from '../../../common/alert'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -85,10 +85,10 @@ describe('createAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id?}"`); - alertsClient.create.mockResolvedValueOnce(createResult); + rulesClient.create.mockResolvedValueOnce(createResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { body: mockedAlert, }, @@ -97,8 +97,8 @@ describe('createAlertRoute', () => { expect(await handler(context, req, res)).toEqual({ body: createResult }); - expect(alertsClient.create).toHaveBeenCalledTimes(1); - expect(alertsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.create).toHaveBeenCalledTimes(1); + expect(rulesClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -152,10 +152,10 @@ describe('createAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id?}"`); - alertsClient.create.mockResolvedValueOnce(expectedResult); + rulesClient.create.mockResolvedValueOnce(expectedResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: 'custom-id' }, body: mockedAlert, @@ -165,8 +165,8 @@ describe('createAlertRoute', () => { expect(await handler(context, req, res)).toEqual({ body: expectedResult }); - expect(alertsClient.create).toHaveBeenCalledTimes(1); - expect(alertsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.create).toHaveBeenCalledTimes(1); + expect(rulesClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -214,9 +214,9 @@ describe('createAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockResolvedValueOnce(createResult); + rulesClient.create.mockResolvedValueOnce(createResult); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}); await handler(context, req, res); @@ -235,9 +235,9 @@ describe('createAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockResolvedValueOnce(createResult); + rulesClient.create.mockResolvedValueOnce(createResult); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}); expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); @@ -252,9 +252,9 @@ describe('createAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.create.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.create.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}, ['ok', 'forbidden']); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}, ['ok', 'forbidden']); await handler(context, req, res); diff --git a/x-pack/plugins/alerting/server/routes/legacy/create.ts b/x-pack/plugins/alerting/server/routes/legacy/create.ts index fca2b67118527..040112b8d9526 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/create.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/create.ts @@ -63,12 +63,12 @@ export const createAlertRoute = (router: AlertingRouter, licenseState: ILicenseS if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const alert = req.body; const params = req.params; const notifyWhen = alert?.notifyWhen ? (alert.notifyWhen as AlertNotifyWhenType) : null; try { - const alertRes: SanitizedAlert = await alertsClient.create( + const alertRes: SanitizedAlert = await rulesClient.create( { data: { ...alert, notifyWhen }, options: { id: params?.id }, diff --git a/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts b/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts index e71b2788b98c7..a016205b78906 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('deleteAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('deleteAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.delete).toHaveBeenCalledTimes(1); - expect(alertsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.delete).toHaveBeenCalledTimes(1); + expect(rulesClient.delete.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,10 +67,10 @@ describe('deleteAlertRoute', () => { const [, handler] = router.delete.mock.calls[0]; - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, } @@ -93,10 +93,10 @@ describe('deleteAlertRoute', () => { const [, handler] = router.delete.mock.calls[0]; - alertsClient.delete.mockResolvedValueOnce({}); + rulesClient.delete.mockResolvedValueOnce({}); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { id: '1', } diff --git a/x-pack/plugins/alerting/server/routes/legacy/delete.ts b/x-pack/plugins/alerting/server/routes/legacy/delete.ts index 650126be4499d..b8800114ebe97 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/delete.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/delete.ts @@ -28,9 +28,9 @@ export const deleteAlertRoute = (router: AlertingRouter, licenseState: ILicenseS if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - await alertsClient.delete({ id }); + await rulesClient.delete({ id }); return res.noContent(); }) ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/disable.test.ts b/x-pack/plugins/alerting/server/routes/legacy/disable.test.ts index 34c0af711a338..3cabf6368b3a3 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/disable.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/disable.test.ts @@ -9,10 +9,10 @@ import { disableAlertRoute } from './disable'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('disableAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_disable"`); - alertsClient.disable.mockResolvedValueOnce(); + rulesClient.disable.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('disableAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.disable).toHaveBeenCalledTimes(1); - expect(alertsClient.disable.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.disable).toHaveBeenCalledTimes(1); + expect(rulesClient.disable.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,9 +67,9 @@ describe('disableAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.disable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.disable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/disable.ts b/x-pack/plugins/alerting/server/routes/legacy/disable.ts index 140e0492fbaab..0ac64395235c1 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/disable.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/disable.ts @@ -29,10 +29,10 @@ export const disableAlertRoute = (router: AlertingRouter, licenseState: ILicense if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.disable({ id }); + await rulesClient.disable({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/enable.test.ts b/x-pack/plugins/alerting/server/routes/legacy/enable.test.ts index 88229472a2936..67a94ef2c1345 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/enable.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/enable.test.ts @@ -9,10 +9,10 @@ import { enableAlertRoute } from './enable'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -33,10 +33,10 @@ describe('enableAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_enable"`); - alertsClient.enable.mockResolvedValueOnce(); + rulesClient.enable.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -47,8 +47,8 @@ describe('enableAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.enable).toHaveBeenCalledTimes(1); - expect(alertsClient.enable.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.enable).toHaveBeenCalledTimes(1); + expect(rulesClient.enable.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -67,9 +67,9 @@ describe('enableAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.enable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.enable.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/enable.ts b/x-pack/plugins/alerting/server/routes/legacy/enable.ts index fcf9ceb8a058b..5a4763f00bd71 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/enable.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/enable.ts @@ -31,10 +31,10 @@ export const enableAlertRoute = (router: AlertingRouter, licenseState: ILicenseS if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.enable({ id }); + await rulesClient.enable({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/find.test.ts b/x-pack/plugins/alerting/server/routes/legacy/find.test.ts index 640451afcca97..d6a74027e13d0 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/find.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/find.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -39,10 +39,10 @@ describe('findAlertRoute', () => { total: 0, data: [], }; - alertsClient.find.mockResolvedValueOnce(findResult); + rulesClient.find.mockResolvedValueOnce(findResult); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { per_page: 1, @@ -64,8 +64,8 @@ describe('findAlertRoute', () => { } `); - expect(alertsClient.find).toHaveBeenCalledTimes(1); - expect(alertsClient.find.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.find).toHaveBeenCalledTimes(1); + expect(rulesClient.find.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "options": Object { @@ -90,7 +90,7 @@ describe('findAlertRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.find.mockResolvedValueOnce({ + rulesClient.find.mockResolvedValueOnce({ page: 1, perPage: 1, total: 0, @@ -98,7 +98,7 @@ describe('findAlertRoute', () => { }); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { query: { per_page: 1, diff --git a/x-pack/plugins/alerting/server/routes/legacy/find.ts b/x-pack/plugins/alerting/server/routes/legacy/find.ts index 1d54df53d883a..c12ef8b349e24 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/find.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/find.ts @@ -12,7 +12,7 @@ import { ILicenseState } from '../../lib/license_state'; import { verifyApiAccess } from '../../lib/license_api_access'; import { LEGACY_BASE_ALERT_API_PATH } from '../../../common'; import { renameKeys } from './../lib/rename_keys'; -import { FindOptions } from '../../alerts_client'; +import { FindOptions } from '../../rules_client'; // config definition const querySchema = schema.object({ @@ -52,7 +52,7 @@ export const findAlertRoute = (router: AlertingRouter, licenseState: ILicenseSta if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const query = req.query; const renameMap = { @@ -75,7 +75,7 @@ export const findAlertRoute = (router: AlertingRouter, licenseState: ILicenseSta : [query.search_fields]; } - const findResult = await alertsClient.find({ options }); + const findResult = await rulesClient.find({ options }); return res.ok({ body: findResult, }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/get.test.ts b/x-pack/plugins/alerting/server/routes/legacy/get.test.ts index b2704cdd234f1..84d21ca6ea950 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get.test.ts @@ -10,10 +10,10 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { Alert } from '../../../common'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -71,10 +71,10 @@ describe('getAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -82,8 +82,8 @@ describe('getAlertRoute', () => { ); await handler(context, req, res); - expect(alertsClient.get).toHaveBeenCalledTimes(1); - expect(alertsClient.get.mock.calls[0][0].id).toEqual('1'); + expect(rulesClient.get).toHaveBeenCalledTimes(1); + expect(rulesClient.get.mock.calls[0][0].id).toEqual('1'); expect(res.ok).toHaveBeenCalledWith({ body: mockedAlert, @@ -98,10 +98,10 @@ describe('getAlertRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -125,10 +125,10 @@ describe('getAlertRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.get.mockResolvedValueOnce(mockedAlert); + rulesClient.get.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/alerting/server/routes/legacy/get.ts b/x-pack/plugins/alerting/server/routes/legacy/get.ts index cf63a4387a93e..08d1308439aa8 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get.ts @@ -28,10 +28,10 @@ export const getAlertRoute = (router: AlertingRouter, licenseState: ILicenseStat if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; return res.ok({ - body: await alertsClient.get({ id }), + body: await rulesClient.get({ id }), }); }) ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.test.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.test.ts index 0162ef91f55e7..f3e7349ba55b9 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.test.ts @@ -10,10 +10,10 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from 'src/core/server'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertInstanceSummary } from '../../types'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -50,10 +50,10 @@ describe('getAlertInstanceSummaryRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_instance_summary"`); - alertsClient.getAlertInstanceSummary.mockResolvedValueOnce(mockedAlertInstanceSummary); + rulesClient.getAlertInstanceSummary.mockResolvedValueOnce(mockedAlertInstanceSummary); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -65,8 +65,8 @@ describe('getAlertInstanceSummaryRoute', () => { await handler(context, req, res); - expect(alertsClient.getAlertInstanceSummary).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertInstanceSummary.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertInstanceSummary).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertInstanceSummary.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "dateStart": undefined, @@ -86,12 +86,12 @@ describe('getAlertInstanceSummaryRoute', () => { const [, handler] = router.get.mock.calls[0]; - alertsClient.getAlertInstanceSummary = jest + rulesClient.getAlertInstanceSummary = jest .fn() .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts index 00c96197f6f9b..ecbb1bf18fb26 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts @@ -36,10 +36,10 @@ export const getAlertInstanceSummaryRoute = ( if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; const { dateStart } = req.query; - const summary = await alertsClient.getAlertInstanceSummary({ id, dateStart }); + const summary = await rulesClient.getAlertInstanceSummary({ id, dateStart }); return res.ok({ body: summary }); }) ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.test.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.test.ts index f08e0992cbba0..f07d9cc79c3ac 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.test.ts @@ -10,9 +10,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from 'src/core/server'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -50,10 +50,10 @@ describe('getAlertStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - alertsClient.getAlertState.mockResolvedValueOnce(mockedAlertState); + rulesClient.getAlertState.mockResolvedValueOnce(mockedAlertState); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -64,8 +64,8 @@ describe('getAlertStateRoute', () => { await handler(context, req, res); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -86,10 +86,10 @@ describe('getAlertStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - alertsClient.getAlertState.mockResolvedValueOnce(undefined); + rulesClient.getAlertState.mockResolvedValueOnce(undefined); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -100,8 +100,8 @@ describe('getAlertStateRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -122,12 +122,12 @@ describe('getAlertStateRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - alertsClient.getAlertState = jest + rulesClient.getAlertState = jest .fn() .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -138,8 +138,8 @@ describe('getAlertStateRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.getAlertState).toHaveBeenCalledTimes(1); - expect(alertsClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.getAlertState).toHaveBeenCalledTimes(1); + expect(rulesClient.getAlertState.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts index 5e7cbfbe6eb95..a3156fc5ed42a 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts @@ -28,9 +28,9 @@ export const getAlertStateRoute = (router: AlertingRouter, licenseState: ILicens if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; - const state = await alertsClient.getAlertState({ id }); + const state = await rulesClient.getAlertState({ id }); return state ? res.ok({ body: state }) : res.noContent(); }) ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/health.test.ts b/x-pack/plugins/alerting/server/routes/legacy/health.test.ts index bc60eae34e0ce..57bfdc29024f6 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/health.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/health.test.ts @@ -10,10 +10,10 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { mockHandlerArguments } from './../_mock_handler_arguments'; import { licenseStateMock } from '../../lib/license_state.mock'; import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { HealthStatus } from '../../types'; import { alertsMock } from '../../mocks'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -62,7 +62,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -98,7 +98,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -134,7 +134,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); @@ -171,7 +171,7 @@ describe('healthRoute', () => { const [context, req, res] = mockHandlerArguments( { - alertsClient, + rulesClient, getFrameworkHealth: alerting.getFrameworkHealth, areApiKeysEnabled: () => Promise.resolve(false), }, @@ -211,7 +211,7 @@ describe('healthRoute', () => { const [context, req, res] = mockHandlerArguments( { - alertsClient, + rulesClient, getFrameworkHealth: alerting.getFrameworkHealth, areApiKeysEnabled: () => Promise.resolve(false), }, @@ -250,7 +250,7 @@ describe('healthRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments( - { alertsClient, getFrameworkHealth: alerting.getFrameworkHealth }, + { rulesClient, getFrameworkHealth: alerting.getFrameworkHealth }, {}, ['ok'] ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts index e2bf1afdb0f6e..c047c78a8606e 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts @@ -10,11 +10,11 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { RecoveredActionGroup } from '../../../common'; import { RegistryAlertTypeWithAuth } from '../../authorization'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -58,9 +58,9 @@ describe('listAlertTypesRoute', () => { enabledInLicense: true, } as RegistryAlertTypeWithAuth, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}, ['ok']); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}, ['ok']); expect(await handler(context, req, res)).toMatchInlineSnapshot(` Object { @@ -93,7 +93,7 @@ describe('listAlertTypesRoute', () => { } `); - expect(alertsClient.listAlertTypes).toHaveBeenCalledTimes(1); + expect(rulesClient.listAlertTypes).toHaveBeenCalledTimes(1); expect(res.ok).toHaveBeenCalledWith({ body: listTypes, @@ -134,10 +134,10 @@ describe('listAlertTypesRoute', () => { } as RegistryAlertTypeWithAuth, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -187,10 +187,10 @@ describe('listAlertTypesRoute', () => { } as RegistryAlertTypeWithAuth, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts index da41cc487228c..6d5ab21c0b0b0 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts @@ -22,7 +22,7 @@ export const listAlertTypesRoute = (router: AlertingRouter, licenseState: ILicen return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } return res.ok({ - body: Array.from(await context.alerting.getAlertsClient().listAlertTypes()), + body: Array.from(await context.alerting.getRulesClient().listAlertTypes()), }); }) ); diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_all.test.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_all.test.ts index ffe893fa60490..538e9d92c43da 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/mute_all.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/mute_all.test.ts @@ -9,10 +9,10 @@ import { muteAllAlertRoute } from './mute_all'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('muteAllAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_mute_all"`); - alertsClient.muteAll.mockResolvedValueOnce(); + rulesClient.muteAll.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('muteAllAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.muteAll).toHaveBeenCalledTimes(1); - expect(alertsClient.muteAll.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.muteAll).toHaveBeenCalledTimes(1); + expect(rulesClient.muteAll.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,9 +66,9 @@ describe('muteAllAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.muteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.muteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts index 643aeb97084a8..506ffa0570b6a 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts @@ -29,10 +29,10 @@ export const muteAllAlertRoute = (router: AlertingRouter, licenseState: ILicense if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.muteAll({ id }); + await rulesClient.muteAll({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.test.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.test.ts index a00c75663c5f0..05ecd3978493b 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.test.ts @@ -9,10 +9,10 @@ import { muteAlertInstanceRoute } from './mute_instance'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -34,10 +34,10 @@ describe('muteAlertInstanceRoute', () => { `"/api/alerts/alert/{alert_id}/alert_instance/{alert_instance_id}/_mute"` ); - alertsClient.muteInstance.mockResolvedValueOnce(); + rulesClient.muteInstance.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { alert_id: '1', @@ -49,8 +49,8 @@ describe('muteAlertInstanceRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.muteInstance).toHaveBeenCalledTimes(1); - expect(alertsClient.muteInstance.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.muteInstance).toHaveBeenCalledTimes(1); + expect(rulesClient.muteInstance.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "alertId": "1", @@ -70,11 +70,11 @@ describe('muteAlertInstanceRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.muteInstance.mockRejectedValue( + rulesClient.muteInstance.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts index 2b35f59c7fce1..caf224006677f 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts @@ -11,7 +11,7 @@ import { ILicenseState } from '../../lib/license_state'; import { verifyApiAccess } from '../../lib/license_api_access'; import { LEGACY_BASE_ALERT_API_PATH } from '../../../common'; import { renameKeys } from './../lib/rename_keys'; -import { MuteOptions } from '../../alerts_client'; +import { MuteOptions } from '../../rules_client'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; const paramSchema = schema.object({ @@ -32,7 +32,7 @@ export const muteAlertInstanceRoute = (router: AlertingRouter, licenseState: ILi if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const renameMap = { alert_id: 'alertId', @@ -41,7 +41,7 @@ export const muteAlertInstanceRoute = (router: AlertingRouter, licenseState: ILi const renamedQuery = renameKeys>(renameMap, req.params); try { - await alertsClient.muteInstance(renamedQuery); + await rulesClient.muteInstance(renamedQuery); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.test.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.test.ts index 8511a8b68a447..49bfb63efa80e 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.test.ts @@ -9,10 +9,10 @@ import { unmuteAllAlertRoute } from './unmute_all'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('unmuteAllAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_unmute_all"`); - alertsClient.unmuteAll.mockResolvedValueOnce(); + rulesClient.unmuteAll.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('unmuteAllAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.unmuteAll).toHaveBeenCalledTimes(1); - expect(alertsClient.unmuteAll.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.unmuteAll).toHaveBeenCalledTimes(1); + expect(rulesClient.unmuteAll.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,9 +66,9 @@ describe('unmuteAllAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.unmuteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.unmuteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts index 1259428be3329..4e01b20d8569e 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts @@ -29,10 +29,10 @@ export const unmuteAllAlertRoute = (router: AlertingRouter, licenseState: ILicen if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.unmuteAll({ id }); + await rulesClient.unmuteAll({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.test.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.test.ts index d28868a3c9230..602fb38eb9afc 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.test.ts @@ -9,10 +9,10 @@ import { unmuteAlertInstanceRoute } from './unmute_instance'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -34,10 +34,10 @@ describe('unmuteAlertInstanceRoute', () => { `"/api/alerts/alert/{alertId}/alert_instance/{alertInstanceId}/_unmute"` ); - alertsClient.unmuteInstance.mockResolvedValueOnce(); + rulesClient.unmuteInstance.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { alertId: '1', @@ -49,8 +49,8 @@ describe('unmuteAlertInstanceRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.unmuteInstance).toHaveBeenCalledTimes(1); - expect(alertsClient.unmuteInstance.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.unmuteInstance).toHaveBeenCalledTimes(1); + expect(rulesClient.unmuteInstance.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "alertId": "1", @@ -70,11 +70,11 @@ describe('unmuteAlertInstanceRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.unmuteInstance.mockRejectedValue( + rulesClient.unmuteInstance.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts index 25f5aa654bde1..f188cfcbbf79b 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts @@ -30,10 +30,10 @@ export const unmuteAlertInstanceRoute = (router: AlertingRouter, licenseState: I if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { alertId, alertInstanceId } = req.params; try { - await alertsClient.unmuteInstance({ alertId, alertInstanceId }); + await rulesClient.unmuteInstance({ alertId, alertInstanceId }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/legacy/update.test.ts b/x-pack/plugins/alerting/server/routes/legacy/update.test.ts index da58d0dc41522..7e9f6a23efc6a 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/update.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/update.test.ts @@ -10,11 +10,11 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { verifyApiAccess } from '../../lib/license_api_access'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; import { AlertNotifyWhenType } from '../../../common'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -57,10 +57,10 @@ describe('updateAlertRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - alertsClient.update.mockResolvedValueOnce(mockedResponse); + rulesClient.update.mockResolvedValueOnce(mockedResponse); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -90,8 +90,8 @@ describe('updateAlertRoute', () => { expect(await handler(context, req, res)).toEqual({ body: mockedResponse }); - expect(alertsClient.update).toHaveBeenCalledTimes(1); - expect(alertsClient.update.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.update).toHaveBeenCalledTimes(1); + expect(rulesClient.update.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -133,10 +133,10 @@ describe('updateAlertRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockResolvedValueOnce(mockedResponse); + rulesClient.update.mockResolvedValueOnce(mockedResponse); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -180,10 +180,10 @@ describe('updateAlertRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockResolvedValueOnce(mockedResponse); + rulesClient.update.mockResolvedValueOnce(mockedResponse); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -223,9 +223,9 @@ describe('updateAlertRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.update.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/update.ts b/x-pack/plugins/alerting/server/routes/legacy/update.ts index 23a0719319e00..40b88b4eab068 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/update.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/update.ts @@ -57,11 +57,11 @@ export const updateAlertRoute = (router: AlertingRouter, licenseState: ILicenseS if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; const { name, actions, params, schedule, tags, throttle, notifyWhen } = req.body; try { - const alertRes = await alertsClient.update({ + const alertRes = await rulesClient.update({ id, data: { name, diff --git a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.test.ts b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.test.ts index 3f556f480f69c..6cef59834933e 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.test.ts @@ -9,10 +9,10 @@ import { updateApiKeyRoute } from './update_api_key'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../../lib/license_state.mock'; import { mockHandlerArguments } from './../_mock_handler_arguments'; -import { alertsClientMock } from '../../alerts_client.mock'; +import { rulesClientMock } from '../../rules_client.mock'; import { AlertTypeDisabledError } from '../../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('updateApiKeyRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_update_api_key"`); - alertsClient.updateApiKey.mockResolvedValueOnce(); + rulesClient.updateApiKey.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('updateApiKeyRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.updateApiKey).toHaveBeenCalledTimes(1); - expect(alertsClient.updateApiKey.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.updateApiKey).toHaveBeenCalledTimes(1); + expect(rulesClient.updateApiKey.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,11 +66,11 @@ describe('updateApiKeyRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.updateApiKey.mockRejectedValue( + rulesClient.updateApiKey.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts index a4da2538b0bf9..82d322d2332b8 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts @@ -31,10 +31,10 @@ export const updateApiKeyRoute = (router: AlertingRouter, licenseState: ILicense if (!context.alerting) { return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.updateApiKey({ id }); + await rulesClient.updateApiKey({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/mute_alert.test.ts b/x-pack/plugins/alerting/server/routes/mute_alert.test.ts index 64ba22f2980ec..284a89ea8a677 100644 --- a/x-pack/plugins/alerting/server/routes/mute_alert.test.ts +++ b/x-pack/plugins/alerting/server/routes/mute_alert.test.ts @@ -9,10 +9,10 @@ import { muteAlertRoute } from './mute_alert'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -34,10 +34,10 @@ describe('muteAlertRoute', () => { `"/api/alerting/rule/{rule_id}/alert/{alert_id}/_mute"` ); - alertsClient.muteInstance.mockResolvedValueOnce(); + rulesClient.muteInstance.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { rule_id: '1', @@ -49,8 +49,8 @@ describe('muteAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.muteInstance).toHaveBeenCalledTimes(1); - expect(alertsClient.muteInstance.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.muteInstance).toHaveBeenCalledTimes(1); + expect(rulesClient.muteInstance.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "alertId": "1", @@ -70,11 +70,11 @@ describe('muteAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.muteInstance.mockRejectedValue( + rulesClient.muteInstance.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/mute_alert.ts b/x-pack/plugins/alerting/server/routes/mute_alert.ts index f1b928cf8c543..301d04f362313 100644 --- a/x-pack/plugins/alerting/server/routes/mute_alert.ts +++ b/x-pack/plugins/alerting/server/routes/mute_alert.ts @@ -8,7 +8,7 @@ import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ILicenseState, AlertTypeDisabledError } from '../lib'; -import { MuteOptions } from '../alerts_client'; +import { MuteOptions } from '../rules_client'; import { RewriteRequestCase, verifyAccessAndContext } from './lib'; import { AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../types'; @@ -38,10 +38,10 @@ export const muteAlertRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const params = rewriteParamsReq(req.params); try { - await alertsClient.muteInstance(params); + await rulesClient.muteInstance(params); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/mute_all_rule.test.ts b/x-pack/plugins/alerting/server/routes/mute_all_rule.test.ts index 0d53708db2567..56e46db082514 100644 --- a/x-pack/plugins/alerting/server/routes/mute_all_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/mute_all_rule.test.ts @@ -9,10 +9,10 @@ import { muteAllRuleRoute } from './mute_all_rule'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('muteAllRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}/_mute_all"`); - alertsClient.muteAll.mockResolvedValueOnce(); + rulesClient.muteAll.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('muteAllRuleRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.muteAll).toHaveBeenCalledTimes(1); - expect(alertsClient.muteAll.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.muteAll).toHaveBeenCalledTimes(1); + expect(rulesClient.muteAll.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,9 +66,9 @@ describe('muteAllRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.muteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.muteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/mute_all_rule.ts b/x-pack/plugins/alerting/server/routes/mute_all_rule.ts index 29d40249ef079..f6d3870ef6744 100644 --- a/x-pack/plugins/alerting/server/routes/mute_all_rule.ts +++ b/x-pack/plugins/alerting/server/routes/mute_all_rule.ts @@ -28,10 +28,10 @@ export const muteAllRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.muteAll({ id }); + await rulesClient.muteAll({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/rule_types.test.ts b/x-pack/plugins/alerting/server/routes/rule_types.test.ts index 4f04f8c7575c5..2e8f43508a969 100644 --- a/x-pack/plugins/alerting/server/routes/rule_types.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule_types.test.ts @@ -10,12 +10,12 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { RecoveredActionGroup } from '../../common'; import { RegistryAlertTypeWithAuth } from '../authorization'; import { AsApiContract } from './lib'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -82,9 +82,9 @@ describe('ruleTypesRoute', () => { enabled_in_license: true, }, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); - const [context, req, res] = mockHandlerArguments({ alertsClient }, {}, ['ok']); + const [context, req, res] = mockHandlerArguments({ rulesClient }, {}, ['ok']); expect(await handler(context, req, res)).toMatchInlineSnapshot(` Object { @@ -117,7 +117,7 @@ describe('ruleTypesRoute', () => { } `); - expect(alertsClient.listAlertTypes).toHaveBeenCalledTimes(1); + expect(rulesClient.listAlertTypes).toHaveBeenCalledTimes(1); expect(res.ok).toHaveBeenCalledWith({ body: expectedResult, @@ -158,10 +158,10 @@ describe('ruleTypesRoute', () => { } as RegistryAlertTypeWithAuth, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, @@ -211,10 +211,10 @@ describe('ruleTypesRoute', () => { } as RegistryAlertTypeWithAuth, ]; - alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + rulesClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/alerting/server/routes/rule_types.ts b/x-pack/plugins/alerting/server/routes/rule_types.ts index f67e07f13feed..153ae96ff68ea 100644 --- a/x-pack/plugins/alerting/server/routes/rule_types.ts +++ b/x-pack/plugins/alerting/server/routes/rule_types.ts @@ -48,7 +48,7 @@ export const ruleTypesRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const ruleTypes = Array.from(await context.alerting.getAlertsClient().listAlertTypes()); + const ruleTypes = Array.from(await context.alerting.getRulesClient().listAlertTypes()); return res.ok({ body: rewriteBodyRes(ruleTypes), }); diff --git a/x-pack/plugins/alerting/server/routes/unmute_alert.test.ts b/x-pack/plugins/alerting/server/routes/unmute_alert.test.ts index a491ba394f839..09c0033542dbb 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_alert.test.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_alert.test.ts @@ -9,10 +9,10 @@ import { unmuteAlertRoute } from './unmute_alert'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -34,10 +34,10 @@ describe('unmuteAlertRoute', () => { `"/api/alerting/rule/{rule_id}/alert/{alert_id}/_unmute"` ); - alertsClient.unmuteInstance.mockResolvedValueOnce(); + rulesClient.unmuteInstance.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { rule_id: '1', @@ -49,8 +49,8 @@ describe('unmuteAlertRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.unmuteInstance).toHaveBeenCalledTimes(1); - expect(alertsClient.unmuteInstance.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.unmuteInstance).toHaveBeenCalledTimes(1); + expect(rulesClient.unmuteInstance.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "alertId": "1", @@ -70,11 +70,11 @@ describe('unmuteAlertRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.unmuteInstance.mockRejectedValue( + rulesClient.unmuteInstance.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/unmute_alert.ts b/x-pack/plugins/alerting/server/routes/unmute_alert.ts index 94bd6cd9af75f..58c3f59b836b1 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_alert.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_alert.ts @@ -8,7 +8,7 @@ import { IRouter } from 'kibana/server'; import { schema } from '@kbn/config-schema'; import { ILicenseState, AlertTypeDisabledError } from '../lib'; -import { MuteOptions } from '../alerts_client'; +import { MuteOptions } from '../rules_client'; import { RewriteRequestCase, verifyAccessAndContext } from './lib'; import { AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../types'; @@ -38,10 +38,10 @@ export const unmuteAlertRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const params = rewriteParamsReq(req.params); try { - await alertsClient.unmuteInstance(params); + await rulesClient.unmuteInstance(params); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/unmute_all_rule.test.ts b/x-pack/plugins/alerting/server/routes/unmute_all_rule.test.ts index f873863bcb902..0f031c2d8cc80 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_all_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_all_rule.test.ts @@ -9,10 +9,10 @@ import { unmuteAllRuleRoute } from './unmute_all_rule'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('unmuteAllRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}/_unmute_all"`); - alertsClient.unmuteAll.mockResolvedValueOnce(); + rulesClient.unmuteAll.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('unmuteAllRuleRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.unmuteAll).toHaveBeenCalledTimes(1); - expect(alertsClient.unmuteAll.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.unmuteAll).toHaveBeenCalledTimes(1); + expect(rulesClient.unmuteAll.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,9 +66,9 @@ describe('unmuteAllRuleRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.unmuteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.unmuteAll.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts b/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts index 96176e916cd7c..a0b562404b0b1 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts @@ -28,10 +28,10 @@ export const unmuteAllRuleRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.unmuteAll({ id }); + await rulesClient.unmuteAll({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/routes/update_rule.test.ts b/x-pack/plugins/alerting/server/routes/update_rule.test.ts index a7121214cd3d3..46f23641f70d9 100644 --- a/x-pack/plugins/alerting/server/routes/update_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/update_rule.test.ts @@ -11,14 +11,14 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { UpdateOptions } from '../alerts_client'; -import { alertsClientMock } from '../alerts_client.mock'; +import { UpdateOptions } from '../rules_client'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; import { AlertNotifyWhenType } from '../../common'; import { AsApiContract } from './lib'; import { PartialAlert } from '../types'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -87,10 +87,10 @@ describe('updateRuleRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/api/alerting/rule/{id}"`); - alertsClient.update.mockResolvedValueOnce(mockedAlert); + rulesClient.update.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -102,8 +102,8 @@ describe('updateRuleRoute', () => { expect(await handler(context, req, res)).toEqual({ body: updateResult }); - expect(alertsClient.update).toHaveBeenCalledTimes(1); - expect(alertsClient.update.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.update).toHaveBeenCalledTimes(1); + expect(rulesClient.update.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "data": Object { @@ -145,10 +145,10 @@ describe('updateRuleRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockResolvedValueOnce(mockedAlert); + rulesClient.update.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -175,10 +175,10 @@ describe('updateRuleRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockResolvedValueOnce(mockedAlert); + rulesClient.update.mockResolvedValueOnce(mockedAlert); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -201,9 +201,9 @@ describe('updateRuleRoute', () => { const [, handler] = router.put.mock.calls[0]; - alertsClient.update.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); + rulesClient.update.mockRejectedValue(new AlertTypeDisabledError('Fail', 'license_invalid')); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/update_rule.ts b/x-pack/plugins/alerting/server/routes/update_rule.ts index ef5bd00558752..6e8024a0ddbf5 100644 --- a/x-pack/plugins/alerting/server/routes/update_rule.ts +++ b/x-pack/plugins/alerting/server/routes/update_rule.ts @@ -9,7 +9,7 @@ import { schema } from '@kbn/config-schema'; import { IRouter } from 'kibana/server'; import { ILicenseState, AlertTypeDisabledError, validateDurationSchema } from '../lib'; import { AlertNotifyWhenType } from '../../common'; -import { UpdateOptions } from '../alerts_client'; +import { UpdateOptions } from '../rules_client'; import { verifyAccessAndContext, RewriteResponseCase, @@ -118,11 +118,11 @@ export const updateRuleRoute = ( handleDisabledApiKeysError( router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; const rule = req.body; try { - const alertRes = await alertsClient.update( + const alertRes = await rulesClient.update( rewriteBodyReq({ id, data: { diff --git a/x-pack/plugins/alerting/server/routes/update_rule_api_key.test.ts b/x-pack/plugins/alerting/server/routes/update_rule_api_key.test.ts index ced335136adb1..b4fb7602bf034 100644 --- a/x-pack/plugins/alerting/server/routes/update_rule_api_key.test.ts +++ b/x-pack/plugins/alerting/server/routes/update_rule_api_key.test.ts @@ -9,10 +9,10 @@ import { updateRuleApiKeyRoute } from './update_rule_api_key'; import { httpServiceMock } from 'src/core/server/mocks'; import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; -import { alertsClientMock } from '../alerts_client.mock'; +import { rulesClientMock } from '../rules_client.mock'; import { AlertTypeDisabledError } from '../lib/errors/alert_type_disabled'; -const alertsClient = alertsClientMock.create(); +const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), })); @@ -32,10 +32,10 @@ describe('updateRuleApiKeyRoute', () => { expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/_update_api_key"`); - alertsClient.updateApiKey.mockResolvedValueOnce(); + rulesClient.updateApiKey.mockResolvedValueOnce(); const [context, req, res] = mockHandlerArguments( - { alertsClient }, + { rulesClient }, { params: { id: '1', @@ -46,8 +46,8 @@ describe('updateRuleApiKeyRoute', () => { expect(await handler(context, req, res)).toEqual(undefined); - expect(alertsClient.updateApiKey).toHaveBeenCalledTimes(1); - expect(alertsClient.updateApiKey.mock.calls[0]).toMatchInlineSnapshot(` + expect(rulesClient.updateApiKey).toHaveBeenCalledTimes(1); + expect(rulesClient.updateApiKey.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "id": "1", @@ -66,11 +66,11 @@ describe('updateRuleApiKeyRoute', () => { const [, handler] = router.post.mock.calls[0]; - alertsClient.updateApiKey.mockRejectedValue( + rulesClient.updateApiKey.mockRejectedValue( new AlertTypeDisabledError('Fail', 'license_invalid') ); - const [context, req, res] = mockHandlerArguments({ alertsClient }, { params: {}, body: {} }, [ + const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: {}, body: {} }, [ 'ok', 'forbidden', ]); diff --git a/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts b/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts index 57206c68d448d..11d76f3992efd 100644 --- a/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts +++ b/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts @@ -28,10 +28,10 @@ export const updateRuleApiKeyRoute = ( }, router.handleLegacyErrors( verifyAccessAndContext(licenseState, async function (context, req, res) { - const alertsClient = context.alerting.getAlertsClient(); + const rulesClient = context.alerting.getRulesClient(); const { id } = req.params; try { - await alertsClient.updateApiKey({ id }); + await rulesClient.updateApiKey({ id }); return res.noContent(); } catch (e) { if (e instanceof AlertTypeDisabledError) { diff --git a/x-pack/plugins/alerting/server/alerts_client.mock.ts b/x-pack/plugins/alerting/server/rules_client.mock.ts similarity index 70% rename from x-pack/plugins/alerting/server/alerts_client.mock.ts rename to x-pack/plugins/alerting/server/rules_client.mock.ts index 57ac0e1a514c6..5c9247ebc177e 100644 --- a/x-pack/plugins/alerting/server/alerts_client.mock.ts +++ b/x-pack/plugins/alerting/server/rules_client.mock.ts @@ -6,13 +6,13 @@ */ import type { PublicMethodsOf } from '@kbn/utility-types'; -import { AlertsClient } from './alerts_client'; +import { RulesClient } from './rules_client'; -type Schema = PublicMethodsOf; -export type AlertsClientMock = jest.Mocked; +type Schema = PublicMethodsOf; +export type RulesClientMock = jest.Mocked; -const createAlertsClientMock = () => { - const mocked: AlertsClientMock = { +const createRulesClientMock = () => { + const mocked: RulesClientMock = { aggregate: jest.fn(), create: jest.fn(), get: jest.fn(), @@ -33,8 +33,8 @@ const createAlertsClientMock = () => { return mocked; }; -export const alertsClientMock: { - create: () => AlertsClientMock; +export const rulesClientMock: { + create: () => RulesClientMock; } = { - create: createAlertsClientMock, + create: createRulesClientMock, }; diff --git a/x-pack/plugins/alerting/server/alerts_client/audit_events.test.ts b/x-pack/plugins/alerting/server/rules_client/audit_events.test.ts similarity index 100% rename from x-pack/plugins/alerting/server/alerts_client/audit_events.test.ts rename to x-pack/plugins/alerting/server/rules_client/audit_events.test.ts diff --git a/x-pack/plugins/alerting/server/alerts_client/audit_events.ts b/x-pack/plugins/alerting/server/rules_client/audit_events.ts similarity index 100% rename from x-pack/plugins/alerting/server/alerts_client/audit_events.ts rename to x-pack/plugins/alerting/server/rules_client/audit_events.ts diff --git a/x-pack/plugins/alerting/server/alerts_client/index.ts b/x-pack/plugins/alerting/server/rules_client/index.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/index.ts rename to x-pack/plugins/alerting/server/rules_client/index.ts index 06571d1f9f631..e5f2b18ee82d1 100644 --- a/x-pack/plugins/alerting/server/alerts_client/index.ts +++ b/x-pack/plugins/alerting/server/rules_client/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export * from './alerts_client'; +export * from './rules_client'; diff --git a/x-pack/plugins/alerting/server/alerts_client/lib/index.ts b/x-pack/plugins/alerting/server/rules_client/lib/index.ts similarity index 100% rename from x-pack/plugins/alerting/server/alerts_client/lib/index.ts rename to x-pack/plugins/alerting/server/rules_client/lib/index.ts diff --git a/x-pack/plugins/alerting/server/alerts_client/lib/map_sort_field.test.ts b/x-pack/plugins/alerting/server/rules_client/lib/map_sort_field.test.ts similarity index 100% rename from x-pack/plugins/alerting/server/alerts_client/lib/map_sort_field.test.ts rename to x-pack/plugins/alerting/server/rules_client/lib/map_sort_field.test.ts diff --git a/x-pack/plugins/alerting/server/alerts_client/lib/map_sort_field.ts b/x-pack/plugins/alerting/server/rules_client/lib/map_sort_field.ts similarity index 100% rename from x-pack/plugins/alerting/server/alerts_client/lib/map_sort_field.ts rename to x-pack/plugins/alerting/server/rules_client/lib/map_sort_field.ts diff --git a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts b/x-pack/plugins/alerting/server/rules_client/rules_client.ts similarity index 98% rename from x-pack/plugins/alerting/server/alerts_client/alerts_client.ts rename to x-pack/plugins/alerting/server/rules_client/rules_client.ts index 53d888967c431..04c55cf3651ad 100644 --- a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts +++ b/x-pack/plugins/alerting/server/rules_client/rules_client.ts @@ -54,7 +54,7 @@ import { AlertingAuthorizationFilterType, AlertingAuthorizationFilterOpts, } from '../authorization'; -import { IEventLogClient } from '../../../../plugins/event_log/server'; +import { IEventLogClient } from '../../../event_log/server'; import { parseIsoOrRelativeDate } from '../lib/iso_or_relative_date'; import { alertInstanceSummaryFromEventLog } from '../lib/alert_instance_summary_from_event_log'; import { IEvent } from '../../../event_log/server'; @@ -187,7 +187,7 @@ const alertingAuthorizationFilterOpts: AlertingAuthorizationFilterOpts = { type: AlertingAuthorizationFilterType.KQL, fieldNames: { ruleTypeId: 'alert.attributes.alertTypeId', consumer: 'alert.attributes.consumer' }, }; -export class AlertsClient { +export class RulesClient { private readonly logger: Logger; private readonly getUserName: () => Promise; private readonly spaceId?: string; @@ -443,7 +443,7 @@ export class AlertsClient { events = queryResults.data; } catch (err) { this.logger.debug( - `alertsClient.getAlertInstanceSummary(): error searching event log for alert ${id}: ${err.message}` + `rulesClient.getAlertInstanceSummary(): error searching event log for alert ${id}: ${err.message}` ); events = []; } @@ -659,7 +659,7 @@ export class AlertsClient { }: UpdateOptions): Promise> { return await retryIfConflicts( this.logger, - `alertsClient.update('${id}')`, + `rulesClient.update('${id}')`, async () => await this.updateWithOCC({ id, data }) ); } @@ -828,7 +828,7 @@ export class AlertsClient { public async updateApiKey({ id }: { id: string }): Promise { return await retryIfConflicts( this.logger, - `alertsClient.updateApiKey('${id}')`, + `rulesClient.updateApiKey('${id}')`, async () => await this.updateApiKeyWithOCC({ id }) ); } @@ -933,7 +933,7 @@ export class AlertsClient { public async enable({ id }: { id: string }): Promise { return await retryIfConflicts( this.logger, - `alertsClient.enable('${id}')`, + `rulesClient.enable('${id}')`, async () => await this.enableWithOCC({ id }) ); } @@ -1051,7 +1051,7 @@ export class AlertsClient { public async disable({ id }: { id: string }): Promise { return await retryIfConflicts( this.logger, - `alertsClient.disable('${id}')`, + `rulesClient.disable('${id}')`, async () => await this.disableWithOCC({ id }) ); } @@ -1143,7 +1143,7 @@ export class AlertsClient { public async muteAll({ id }: { id: string }): Promise { return await retryIfConflicts( this.logger, - `alertsClient.muteAll('${id}')`, + `rulesClient.muteAll('${id}')`, async () => await this.muteAllWithOCC({ id }) ); } @@ -1205,7 +1205,7 @@ export class AlertsClient { public async unmuteAll({ id }: { id: string }): Promise { return await retryIfConflicts( this.logger, - `alertsClient.unmuteAll('${id}')`, + `rulesClient.unmuteAll('${id}')`, async () => await this.unmuteAllWithOCC({ id }) ); } @@ -1267,7 +1267,7 @@ export class AlertsClient { public async muteInstance({ alertId, alertInstanceId }: MuteOptions): Promise { return await retryIfConflicts( this.logger, - `alertsClient.muteInstance('${alertId}')`, + `rulesClient.muteInstance('${alertId}')`, async () => await this.muteInstanceWithOCC({ alertId, alertInstanceId }) ); } @@ -1329,7 +1329,7 @@ export class AlertsClient { public async unmuteInstance({ alertId, alertInstanceId }: MuteOptions): Promise { return await retryIfConflicts( this.logger, - `alertsClient.unmuteInstance('${alertId}')`, + `rulesClient.unmuteInstance('${alertId}')`, async () => await this.unmuteInstanceWithOCC({ alertId, alertInstanceId }) ); } @@ -1495,7 +1495,7 @@ export class AlertsClient { if (actionsUsingConnectorsWithMissingSecrets.length) { throw Boom.badRequest( - i18n.translate('xpack.alerting.alertsClient.validateActions.misconfiguredConnector', { + i18n.translate('xpack.alerting.rulesClient.validateActions.misconfiguredConnector', { defaultMessage: 'Invalid connectors: {groups}', values: { groups: actionsUsingConnectorsWithMissingSecrets @@ -1515,7 +1515,7 @@ export class AlertsClient { ); if (invalidActionGroups.length) { throw Boom.badRequest( - i18n.translate('xpack.alerting.alertsClient.validateActions.invalidGroups', { + i18n.translate('xpack.alerting.rulesClient.validateActions.invalidGroups', { defaultMessage: 'Invalid action groups: {groups}', values: { groups: invalidActionGroups.join(', '), @@ -1593,7 +1593,7 @@ function parseDate(dateString: string | undefined, propertyName: string, default const parsedDate = parseIsoOrRelativeDate(dateString); if (parsedDate === undefined) { throw Boom.badRequest( - i18n.translate('xpack.alerting.alertsClient.invalidDate', { + i18n.translate('xpack.alerting.rulesClient.invalidDate', { defaultMessage: 'Invalid date for parameter {field}: "{dateValue}"', values: { field: propertyName, diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/aggregate.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts similarity index 91% rename from x-pack/plugins/alerting/server/alerts_client/tests/aggregate.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts index 611ff23e46256..2e6944a8bb4f8 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/aggregate.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -28,7 +28,7 @@ const authorization = alertingAuthorizationMock.create(); const actionsAuthorization = actionsAuthorizationMock.create(); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -46,7 +46,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); }); setGlobalDate(); @@ -124,8 +124,8 @@ describe('aggregate()', () => { }); test('calls saved objects client with given params to perform aggregation', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - const result = await alertsClient.aggregate({ options: {} }); + const rulesClient = new RulesClient(rulesClientParams); + const result = await rulesClient.aggregate({ options: {} }); expect(result).toMatchInlineSnapshot(` Object { "alertExecutionStatus": Object { @@ -154,8 +154,8 @@ describe('aggregate()', () => { }); test('supports filters when aggregating', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.aggregate({ options: { filter: 'someTerm' } }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.aggregate({ options: { filter: 'someTerm' } }); expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledTimes( AlertExecutionStatusValues.length diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/create.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts similarity index 94% rename from x-pack/plugins/alerting/server/alerts_client/tests/create.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/create.test.ts index e231d1e3c27a2..5ae7b6394102b 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/create.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts @@ -6,7 +6,7 @@ */ import { schema } from '@kbn/config-schema'; -import { AlertsClient, ConstructorOptions, CreateOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions, CreateOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -36,7 +36,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -55,7 +55,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -92,12 +92,12 @@ function getMockData( } describe('create()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; let actionsClient: jest.Mocked; beforeEach(async () => { - alertsClient = new AlertsClient(alertsClientParams); - actionsClient = (await alertsClientParams.getActionsClient()) as jest.Mocked; + rulesClient = new RulesClient(rulesClientParams); + actionsClient = (await rulesClientParams.getActionsClient()) as jest.Mocked; actionsClient.getBulk.mockReset(); actionsClient.getBulk.mockResolvedValue([ { @@ -116,7 +116,7 @@ describe('create()', () => { isPreconfigured: false, }, ]); - alertsClientParams.getActionsClient.mockResolvedValue(actionsClient); + rulesClientParams.getActionsClient.mockResolvedValue(actionsClient); }); describe('authorization', () => { @@ -183,7 +183,7 @@ describe('create()', () => { ], }); - return alertsClient.create(options); + return rulesClient.create(options); } test('ensures user is authorised to create this type of alert under the consumer', async () => { @@ -237,7 +237,7 @@ describe('create()', () => { attributes: data, references: [], }); - await alertsClient.create({ data }); + await rulesClient.create({ data }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -253,7 +253,7 @@ describe('create()', () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); await expect( - alertsClient.create({ + rulesClient.create({ data: getMockData({ enabled: false, actions: [], @@ -347,7 +347,7 @@ describe('create()', () => { }, ], }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', consumer: 'bar', @@ -537,7 +537,7 @@ describe('create()', () => { params: {}, ownerId: null, }); - const result = await alertsClient.create({ data, options: { id: '123' } }); + const result = await rulesClient.create({ data, options: { id: '123' } }); expect(result.id).toEqual('123'); expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(` Object { @@ -691,7 +691,7 @@ describe('create()', () => { }, references: [], }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(result).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -770,7 +770,7 @@ describe('create()', () => { }, ], }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(result).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -849,8 +849,8 @@ describe('create()', () => { ownerId: null, }); - await alertsClient.create({ data }); - expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my alert name'); + await rulesClient.create({ data }); + expect(rulesClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my alert name'); }); test('should create alert with given notifyWhen value if notifyWhen is not null', async () => { @@ -905,7 +905,7 @@ describe('create()', () => { params: {}, ownerId: null, }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { @@ -1045,7 +1045,7 @@ describe('create()', () => { params: {}, ownerId: null, }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { @@ -1185,7 +1185,7 @@ describe('create()', () => { params: {}, ownerId: null, }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { @@ -1297,7 +1297,7 @@ describe('create()', () => { async executor() {}, producer: 'alerts', }); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"params invalid: [param1]: expected value of type [string] but got [undefined]"` ); }); @@ -1307,7 +1307,7 @@ describe('create()', () => { // Reset from default behaviour actionsClient.getBulk.mockReset(); actionsClient.getBulk.mockRejectedValueOnce(new Error('Test Error')); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test Error"` ); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); @@ -1316,7 +1316,7 @@ describe('create()', () => { test('throws error and add API key to invalidatePendingApiKey SO when create saved object fails', async () => { const data = getMockData(); - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', name: '123', api_key: 'abc' }, }); @@ -1331,7 +1331,7 @@ describe('create()', () => { }, references: [], }); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test failure"` ); expect(taskManager.schedule).not.toHaveBeenCalled(); @@ -1374,7 +1374,7 @@ describe('create()', () => { }); taskManager.schedule.mockRejectedValueOnce(new Error('Test failure')); unsecuredSavedObjectsClient.delete.mockResolvedValueOnce({}); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test failure"` ); expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledTimes(1); @@ -1420,10 +1420,10 @@ describe('create()', () => { unsecuredSavedObjectsClient.delete.mockRejectedValueOnce( new Error('Saved object delete error') ); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Task manager error"` ); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'Failed to cleanup alert "1" after scheduling task failed. Error: Saved object delete error' ); }); @@ -1433,14 +1433,14 @@ describe('create()', () => { alertTypeRegistry.get.mockImplementation(() => { throw new Error('Invalid type'); }); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid type"` ); }); test('calls the API key function', async () => { const data = getMockData(); - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', name: '123', api_key: 'abc' }, }); @@ -1500,9 +1500,9 @@ describe('create()', () => { }, ], }); - await alertsClient.create({ data }); + await rulesClient.create({ data }); - expect(alertsClientParams.createAPIKey).toHaveBeenCalledTimes(1); + expect(rulesClientParams.createAPIKey).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { @@ -1611,9 +1611,9 @@ describe('create()', () => { }, ], }); - await alertsClient.create({ data }); + await rulesClient.create({ data }); - expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { @@ -1666,11 +1666,11 @@ describe('create()', () => { test('throws an error if API key creation throws', async () => { const data = getMockData(); - alertsClientParams.createAPIKey.mockImplementation(() => { + rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); expect( - async () => await alertsClient.create({ data }) + async () => await rulesClient.create({ data }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error creating rule: could not create API key - no"` ); @@ -1681,9 +1681,7 @@ describe('create()', () => { alertTypeRegistry.ensureAlertTypeEnabled.mockImplementation(() => { throw new Error('Fail'); }); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( - `"Fail"` - ); + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(`"Fail"`); }); test('throws error when adding action using connector with missing secrets', async () => { @@ -1707,7 +1705,7 @@ describe('create()', () => { isPreconfigured: false, }, ]); - await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid connectors: email connector"` ); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/delete.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/tests/delete.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts index ca0f0cf0fb5a6..50a3cbf632a05 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/delete.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -46,12 +46,12 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); describe('delete()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; const existingAlert = { id: '1', type: 'alert', @@ -91,7 +91,7 @@ describe('delete()', () => { }; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); unsecuredSavedObjectsClient.delete.mockResolvedValue({ success: true, @@ -109,7 +109,7 @@ describe('delete()', () => { }, references: [], }); - const result = await alertsClient.delete({ id: '1' }); + const result = await rulesClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); @@ -134,13 +134,13 @@ describe('delete()', () => { references: [], }); - const result = await alertsClient.delete({ id: '1' }); + const result = await rulesClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'delete(): Failed to load API key to invalidate on alert 1: Fail' ); }); @@ -154,7 +154,7 @@ describe('delete()', () => { }, }); - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(taskManager.removeIfExists).not.toHaveBeenCalled(); }); @@ -176,17 +176,17 @@ describe('delete()', () => { }, }); - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); test('swallows error when invalidate API key throws', async () => { unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Fail')); - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toBe( 'api_key_pending_invalidation' ); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'Failed to mark for API key [id="MTIzOmFiYw=="] for invalidation: Fail' ); }); @@ -203,9 +203,9 @@ describe('delete()', () => { }); encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'delete(): Failed to load API key to invalidate on alert 1: Fail' ); }); @@ -214,7 +214,7 @@ describe('delete()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); unsecuredSavedObjectsClient.get.mockRejectedValue(new Error('SOC Fail')); - await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"SOC Fail"` ); }); @@ -222,14 +222,14 @@ describe('delete()', () => { test('throws error when taskManager.removeIfExists throws an error', async () => { taskManager.removeIfExists.mockRejectedValue(new Error('TM Fail')); - await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"TM Fail"` ); }); describe('authorization', () => { test('ensures user is authorised to delete this type of alert under the consumer', async () => { - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -244,7 +244,7 @@ describe('delete()', () => { new Error(`Unauthorized to delete a "myType" alert for "myApp"`) ); - await expect(alertsClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to delete a "myType" alert for "myApp"]` ); @@ -259,7 +259,7 @@ describe('delete()', () => { describe('auditLogger', () => { test('logs audit event when deleting a rule', async () => { - await alertsClient.delete({ id: '1' }); + await rulesClient.delete({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -274,7 +274,7 @@ describe('delete()', () => { test('logs audit event when not authorised to delete a rule', async () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.delete({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.delete({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/disable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts similarity index 90% rename from x-pack/plugins/alerting/server/alerts_client/tests/disable.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts index da1c5ea8bfe8d..2cae591849323 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/disable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -28,7 +28,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -47,14 +47,14 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); setGlobalDate(); describe('disable()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; const existingAlert = { id: '1', type: 'alert', @@ -90,14 +90,14 @@ describe('disable()', () => { }; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); }); describe('authorization', () => { test('ensures user is authorised to disable this type of alert under the consumer', async () => { - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -112,7 +112,7 @@ describe('disable()', () => { new Error(`Unauthorized to disable a "myType" alert for "myApp"`) ); - await expect(alertsClient.disable({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.disable({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to disable a "myType" alert for "myApp"]` ); @@ -127,7 +127,7 @@ describe('disable()', () => { describe('auditLogger', () => { test('logs audit event when disabling a rule', async () => { - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -142,7 +142,7 @@ describe('disable()', () => { test('logs audit event when not authorised to disable a rule', async () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.disable({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.disable({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -174,7 +174,7 @@ describe('disable()', () => { }, references: [], }); - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', @@ -229,7 +229,7 @@ describe('disable()', () => { references: [], }); - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', @@ -290,7 +290,7 @@ describe('disable()', () => { references: [], }); - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); expect(taskManager.removeIfExists).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); @@ -308,7 +308,7 @@ describe('disable()', () => { }); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce(existingAlert); - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); @@ -324,11 +324,11 @@ describe('disable()', () => { }); encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); - await alertsClient.disable({ id: '1' }); + await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); expect(taskManager.removeIfExists).toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'disable(): Failed to load API key to invalidate on alert 1: Fail' ); }); @@ -336,15 +336,15 @@ describe('disable()', () => { test('throws when unsecuredSavedObjectsClient update fails', async () => { unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update')); - await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Failed to update"` ); }); test('swallows error when invalidate API key throws', async () => { unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Fail')); - await alertsClient.disable({ id: '1' }); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + await rulesClient.disable({ id: '1' }); + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'Failed to mark for API key [id="MTIzOmFiYw=="] for invalidation: Fail' ); }); @@ -352,7 +352,7 @@ describe('disable()', () => { test('throws when failing to remove task from task manager', async () => { taskManager.removeIfExists.mockRejectedValueOnce(new Error('Failed to remove task')); - await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Failed to remove task"` ); }); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/enable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts similarity index 85% rename from x-pack/plugins/alerting/server/alerts_client/tests/enable.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts index b3c8d3bd83980..4692abbae5217 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/enable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -29,7 +29,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -48,14 +48,14 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); setGlobalDate(); describe('enable()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; const existingAlert = { id: '1', type: 'alert', @@ -81,10 +81,10 @@ describe('enable()', () => { }; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); - alertsClientParams.createAPIKey.mockResolvedValue({ + rulesClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false, }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ @@ -116,7 +116,7 @@ describe('enable()', () => { beforeEach(() => { encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); - alertsClientParams.createAPIKey.mockResolvedValue({ + rulesClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false, }); taskManager.schedule.mockResolvedValue({ @@ -135,7 +135,7 @@ describe('enable()', () => { }); test('ensures user is authorised to enable this type of alert under the consumer', async () => { - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -151,7 +151,7 @@ describe('enable()', () => { new Error(`Unauthorized to enable a "myType" alert for "myApp"`) ); - await expect(alertsClient.enable({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.enable({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to enable a "myType" alert for "myApp"]` ); @@ -166,7 +166,7 @@ describe('enable()', () => { describe('auditLogger', () => { test('logs audit event when enabling a rule', async () => { - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -181,7 +181,7 @@ describe('enable()', () => { test('logs audit event when not authorised to enable a rule', async () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.enable({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.enable({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -225,13 +225,13 @@ describe('enable()', () => { references: [], }); - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); expect(unsecuredSavedObjectsClient.create).not.toBeCalledWith('api_key_pending_invalidation'); - expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -308,7 +308,7 @@ describe('enable()', () => { references: [], }); - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', @@ -327,20 +327,20 @@ describe('enable()', () => { }, }); - await alertsClient.enable({ id: '1' }); - expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); - expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + await rulesClient.enable({ id: '1' }); + expect(rulesClientParams.getUserName).not.toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('sets API key when createAPIKey returns one', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', name: '123', api_key: 'abc' }, }); - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -380,11 +380,11 @@ describe('enable()', () => { }); test('throws an error if API key creation throws', async () => { - alertsClientParams.createAPIKey.mockImplementation(() => { + rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); expect( - async () => await alertsClient.enable({ id: '1' }) + async () => await rulesClient.enable({ id: '1' }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error enabling rule: could not create API key - no"` ); @@ -393,9 +393,9 @@ describe('enable()', () => { test('falls back when failing to getDecryptedAsInternalUser', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); - await alertsClient.enable({ id: '1' }); + await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'enable(): Failed to load API key to invalidate on alert 1: Fail' ); }); @@ -404,18 +404,18 @@ describe('enable()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get')); - await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to get"` ); - expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); - expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(rulesClientParams.getUserName).not.toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('throws error when failing to update the first time', async () => { const createdAt = new Date().toISOString(); - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', name: '123', api_key: 'abc' }, }); @@ -431,11 +431,11 @@ describe('enable()', () => { references: [], }); - await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to update"` ); - expect(alertsClientParams.getUserName).toHaveBeenCalled(); - expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(rulesClientParams.getUserName).toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).toHaveBeenCalled(); expect( (unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId ).toBe('123'); @@ -456,11 +456,11 @@ describe('enable()', () => { new Error('Fail to update second time') ); - await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to update second time"` ); - expect(alertsClientParams.getUserName).toHaveBeenCalled(); - expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(rulesClientParams.getUserName).toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.schedule).toHaveBeenCalled(); }); @@ -468,11 +468,11 @@ describe('enable()', () => { test('throws error when failing to schedule task', async () => { taskManager.schedule.mockRejectedValueOnce(new Error('Fail to schedule')); - await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to schedule"` ); - expect(alertsClientParams.getUserName).toHaveBeenCalled(); - expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(rulesClientParams.getUserName).toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/find.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/tests/find.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/find.test.ts index 5ec39681a758b..e2636fdeac7ee 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/find.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -31,7 +31,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -49,7 +49,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -139,8 +139,8 @@ describe('find()', () => { }); test('calls saved objects client with given params', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - const result = await alertsClient.find({ options: {} }); + const rulesClient = new RulesClient(rulesClientParams); + const result = await rulesClient.find({ options: {} }); expect(result).toMatchInlineSnapshot(` Object { "data": Array [ @@ -186,8 +186,8 @@ describe('find()', () => { }); test('calls mapSortField', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.find({ options: { sortField: 'name' } }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.find({ options: { sortField: 'name' } }); expect(jest.requireMock('../lib/map_sort_field').mapSortField).toHaveBeenCalledWith('name'); }); @@ -202,8 +202,8 @@ describe('find()', () => { logSuccessfulAuthorization() {}, }); - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.find({ options: { filter: 'someTerm' } }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.find({ options: { filter: 'someTerm' } }); const [options] = unsecuredSavedObjectsClient.find.mock.calls[0]; expect(options.filter).toEqual( @@ -213,9 +213,9 @@ describe('find()', () => { }); test('throws if user is not authorized to find any types', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.getFindAuthorizationFilter.mockRejectedValue(new Error('not authorized')); - await expect(alertsClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot( `"not authorized"` ); }); @@ -249,8 +249,8 @@ describe('find()', () => { ], }); - const alertsClient = new AlertsClient(alertsClientParams); - expect(await alertsClient.find({ options: { fields: ['tags'] } })).toMatchInlineSnapshot(` + const rulesClient = new RulesClient(rulesClientParams); + expect(await rulesClient.find({ options: { fields: ['tags'] } })).toMatchInlineSnapshot(` Object { "data": Array [ Object { @@ -280,8 +280,8 @@ describe('find()', () => { describe('auditLogger', () => { test('logs audit event when searching rules', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); - await alertsClient.find(); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); + await rulesClient.find(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -294,10 +294,10 @@ describe('find()', () => { }); test('logs audit event when not authorised to search rules', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); authorization.getFindAuthorizationFilter.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.find()).rejects.toThrow(); + await expect(rulesClient.find()).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -313,7 +313,7 @@ describe('find()', () => { }); test('logs audit event when not authorised to search rule type', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); authorization.getFindAuthorizationFilter.mockResolvedValue({ ensureRuleTypeIsAuthorized: jest.fn(() => { throw new Error('Unauthorized'); @@ -321,7 +321,7 @@ describe('find()', () => { logSuccessfulAuthorization: jest.fn(), }); - await expect(async () => await alertsClient.find()).rejects.toThrow(); + await expect(async () => await rulesClient.find()).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/get.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/tests/get.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/get.test.ts index 1be9d3e3ba2c9..4a7625eaaa6e7 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/get.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -45,7 +45,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -53,7 +53,7 @@ setGlobalDate(); describe('get()', () => { test('calls saved objects client with given params', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -84,7 +84,7 @@ describe('get()', () => { }, ], }); - const result = await alertsClient.get({ id: '1' }); + const result = await rulesClient.get({ id: '1' }); expect(result).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -119,7 +119,7 @@ describe('get()', () => { }); test(`throws an error when references aren't found`, async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -141,7 +141,7 @@ describe('get()', () => { }, references: [], }); - await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Action reference \\"action_0\\" not found in alert id: 1"` ); }); @@ -179,8 +179,8 @@ describe('get()', () => { }); test('ensures user is authorised to get this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.get({ id: '1' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.get({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -191,12 +191,12 @@ describe('get()', () => { }); test('throws when user is not authorised to get this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.ensureAuthorized.mockRejectedValue( new Error(`Unauthorized to get a "myType" alert for "myApp"`) ); - await expect(alertsClient.get({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.get({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to get a "myType" alert for "myApp"]` ); @@ -227,8 +227,8 @@ describe('get()', () => { }); test('logs audit event when getting a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); - await alertsClient.get({ id: '1' }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); + await rulesClient.get({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -241,10 +241,10 @@ describe('get()', () => { }); test('logs audit event when not authorised to get a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.get({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.get({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/get_alert_instance_summary.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts similarity index 92% rename from x-pack/plugins/alerting/server/alerts_client/tests/get_alert_instance_summary.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts index 2ef9982ba8f85..85a59e35b64d2 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/get_alert_instance_summary.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -31,7 +31,7 @@ const authorization = alertingAuthorizationMock.create(); const actionsAuthorization = actionsAuthorizationMock.create(); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -49,7 +49,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry, eventLogClient); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry, eventLogClient); }); setGlobalDate(); @@ -104,10 +104,10 @@ function getAlertInstanceSummarySavedObject( } describe('getAlertInstanceSummary()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); }); test('runs as expected with some event log data', async () => { @@ -137,7 +137,7 @@ describe('getAlertInstanceSummary()', () => { const dateStart = new Date(Date.now() - 60 * 1000).toISOString(); - const result = await alertsClient.getAlertInstanceSummary({ id: '1', dateStart }); + const result = await rulesClient.getAlertInstanceSummary({ id: '1', dateStart }); expect(result).toMatchInlineSnapshot(` Object { "alertTypeId": "123", @@ -194,7 +194,7 @@ describe('getAlertInstanceSummary()', () => { AlertInstanceSummaryFindEventsResult ); - await alertsClient.getAlertInstanceSummary({ id: '1' }); + await rulesClient.getAlertInstanceSummary({ id: '1' }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds).toHaveBeenCalledTimes(1); @@ -233,7 +233,7 @@ describe('getAlertInstanceSummary()', () => { const dateStart = new Date( Date.now() - 60 * AlertInstanceSummaryIntervalSeconds * 1000 ).toISOString(); - await alertsClient.getAlertInstanceSummary({ id: '1', dateStart }); + await rulesClient.getAlertInstanceSummary({ id: '1', dateStart }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds).toHaveBeenCalledTimes(1); @@ -254,7 +254,7 @@ describe('getAlertInstanceSummary()', () => { ); const dateStart = '2m'; - await alertsClient.getAlertInstanceSummary({ id: '1', dateStart }); + await rulesClient.getAlertInstanceSummary({ id: '1', dateStart }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds).toHaveBeenCalledTimes(1); @@ -276,7 +276,7 @@ describe('getAlertInstanceSummary()', () => { const dateStart = 'ain"t no way this will get parsed as a date'; expect( - alertsClient.getAlertInstanceSummary({ id: '1', dateStart }) + rulesClient.getAlertInstanceSummary({ id: '1', dateStart }) ).rejects.toMatchInlineSnapshot( `[Error: Invalid date for parameter dateStart: "ain"t no way this will get parsed as a date"]` ); @@ -288,7 +288,7 @@ describe('getAlertInstanceSummary()', () => { AlertInstanceSummaryFindEventsResult ); - expect(alertsClient.getAlertInstanceSummary({ id: '1' })).rejects.toMatchInlineSnapshot( + expect(rulesClient.getAlertInstanceSummary({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: OMG!]` ); }); @@ -298,6 +298,6 @@ describe('getAlertInstanceSummary()', () => { eventLogClient.findEventsBySavedObjectIds.mockRejectedValueOnce(new Error('OMG 2!')); // error eaten but logged - await alertsClient.getAlertInstanceSummary({ id: '1' }); + await rulesClient.getAlertInstanceSummary({ id: '1' }); }); }); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/get_alert_state.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts similarity index 90% rename from x-pack/plugins/alerting/server/alerts_client/tests/get_alert_state.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts index 07f58924d727d..e8074692d202e 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/get_alert_state.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -26,7 +26,7 @@ const authorization = alertingAuthorizationMock.create(); const actionsAuthorization = actionsAuthorizationMock.create(); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -44,12 +44,12 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); }); describe('getAlertState()', () => { test('calls saved objects client with given params', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -92,7 +92,7 @@ describe('getAlertState()', () => { ownerId: null, }); - await alertsClient.getAlertState({ id: '1' }); + await rulesClient.getAlertState({ id: '1' }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` Array [ @@ -103,7 +103,7 @@ describe('getAlertState()', () => { }); test('gets the underlying task from TaskManager', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); const scheduledTaskId = 'task-123'; @@ -155,7 +155,7 @@ describe('getAlertState()', () => { ownerId: null, }); - await alertsClient.getAlertState({ id: '1' }); + await rulesClient.getAlertState({ id: '1' }); expect(taskManager.get).toHaveBeenCalledTimes(1); expect(taskManager.get).toHaveBeenCalledWith(scheduledTaskId); }); @@ -207,8 +207,8 @@ describe('getAlertState()', () => { }); test('ensures user is authorised to get this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.getAlertState({ id: '1' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.getAlertState({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -219,7 +219,7 @@ describe('getAlertState()', () => { }); test('throws when user is not authorised to getAlertState this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); // `get` check authorization.ensureAuthorized.mockResolvedValueOnce(); // `getRuleState` check @@ -227,7 +227,7 @@ describe('getAlertState()', () => { new Error(`Unauthorized to getRuleState a "myType" alert for "myApp"`) ); - await expect(alertsClient.getAlertState({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.getAlertState({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to getRuleState a "myType" alert for "myApp"]` ); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/lib.ts b/x-pack/plugins/alerting/server/rules_client/tests/lib.ts similarity index 87% rename from x-pack/plugins/alerting/server/alerts_client/tests/lib.ts rename to x-pack/plugins/alerting/server/rules_client/tests/lib.ts index e0f4f9f6da0f1..5bd256dcc3c4b 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/lib.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/lib.ts @@ -8,7 +8,7 @@ import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { IEventLogClient } from '../../../../event_log/server'; import { actionsClientMock } from '../../../../actions/server/mocks'; -import { ConstructorOptions } from '../alerts_client'; +import { ConstructorOptions } from '../rules_client'; import { eventLogClientMock } from '../../../../event_log/server/mocks'; import { AlertTypeRegistry } from '../../alert_type_registry'; import { RecoveredActionGroup } from '../../../common'; @@ -42,14 +42,14 @@ export function setGlobalDate() { } export function getBeforeSetup( - alertsClientParams: jest.Mocked, + rulesClientParams: jest.Mocked, taskManager: ReturnType, alertTypeRegistry: jest.Mocked>, eventLogClient?: jest.Mocked ) { jest.resetAllMocks(); - alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false }); - alertsClientParams.getUserName.mockResolvedValue('elastic'); + rulesClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false }); + rulesClientParams.getUserName.mockResolvedValue('elastic'); taskManager.runNow.mockResolvedValue({ id: '' }); const actionsClient = actionsClientMock.create(); @@ -79,7 +79,7 @@ export function getBeforeSetup( name: 'test', }, ]); - alertsClientParams.getActionsClient.mockResolvedValue(actionsClient); + rulesClientParams.getActionsClient.mockResolvedValue(actionsClient); alertTypeRegistry.get.mockImplementation(() => ({ id: '123', @@ -92,7 +92,7 @@ export function getBeforeSetup( async executor() {}, producer: 'alerts', })); - alertsClientParams.getEventLogClient.mockResolvedValue( + rulesClientParams.getEventLogClient.mockResolvedValue( eventLogClient ?? eventLogClientMock.create() ); } diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/list_alert_types.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts similarity index 92% rename from x-pack/plugins/alerting/server/alerts_client/tests/list_alert_types.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts index 0f849423409d8..2ea00f0bd6c2b 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/list_alert_types.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -30,7 +30,7 @@ const authorization = alertingAuthorizationMock.create(); const actionsAuthorization = actionsAuthorizationMock.create(); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -48,11 +48,11 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); }); describe('listAlertTypes', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; const alertingAlertType: RegistryAlertType = { actionGroups: [], actionVariables: undefined, @@ -86,7 +86,7 @@ describe('listAlertTypes', () => { }; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); }); test('should return a list of AlertTypes that exist in the registry', async () => { @@ -97,7 +97,7 @@ describe('listAlertTypes', () => { { ...alertingAlertType, authorizedConsumers }, ]) ); - expect(await alertsClient.listAlertTypes()).toEqual( + expect(await rulesClient.listAlertTypes()).toEqual( new Set([ { ...myAppAlertType, authorizedConsumers }, { ...alertingAlertType, authorizedConsumers }, @@ -154,7 +154,7 @@ describe('listAlertTypes', () => { ]); authorization.filterByRuleTypeAuthorization.mockResolvedValue(authorizedTypes); - expect(await alertsClient.listAlertTypes()).toEqual(authorizedTypes); + expect(await rulesClient.listAlertTypes()).toEqual(authorizedTypes); }); }); }); diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/mute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/tests/mute_all.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts index 43f43b539ebf2..ed315dfff40cd 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/mute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -45,7 +45,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -53,7 +53,7 @@ setGlobalDate(); describe('muteAll()', () => { test('mutes an alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -75,7 +75,7 @@ describe('muteAll()', () => { version: '123', }); - await alertsClient.muteAll({ id: '1' }); + await rulesClient.muteAll({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -123,8 +123,8 @@ describe('muteAll()', () => { }); test('ensures user is authorised to muteAll this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.muteAll({ id: '1' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.muteAll({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -136,12 +136,12 @@ describe('muteAll()', () => { }); test('throws when user is not authorised to muteAll this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.ensureAuthorized.mockRejectedValue( new Error(`Unauthorized to muteAll a "myType" alert for "myApp"`) ); - await expect(alertsClient.muteAll({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.muteAll({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to muteAll a "myType" alert for "myApp"]` ); @@ -156,7 +156,7 @@ describe('muteAll()', () => { describe('auditLogger', () => { test('logs audit event when muting a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -177,7 +177,7 @@ describe('muteAll()', () => { references: [], version: '123', }); - await alertsClient.muteAll({ id: '1' }); + await rulesClient.muteAll({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -190,7 +190,7 @@ describe('muteAll()', () => { }); test('logs audit event when not authorised to mute a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -213,7 +213,7 @@ describe('muteAll()', () => { }); authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.muteAll({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.muteAll({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/mute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts similarity index 85% rename from x-pack/plugins/alerting/server/alerts_client/tests/mute_instance.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts index e2e4aff61866b..8f4c3ea5d68b3 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/mute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -45,7 +45,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -53,7 +53,7 @@ setGlobalDate(); describe('muteInstance()', () => { test('mutes an alert instance', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -69,7 +69,7 @@ describe('muteInstance()', () => { references: [], }); - await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -85,7 +85,7 @@ describe('muteInstance()', () => { }); test('skips muting when alert instance already muted', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -100,12 +100,12 @@ describe('muteInstance()', () => { references: [], }); - await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); test('skips muting when alert is muted', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -121,7 +121,7 @@ describe('muteInstance()', () => { references: [], }); - await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); @@ -155,8 +155,8 @@ describe('muteInstance()', () => { }); test('ensures user is authorised to muteInstance this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ @@ -168,13 +168,13 @@ describe('muteInstance()', () => { }); test('throws when user is not authorised to muteInstance this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.ensureAuthorized.mockRejectedValue( new Error(`Unauthorized to muteAlert a "myType" alert for "myApp"`) ); await expect( - alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }) + rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }) ).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to muteAlert a "myType" alert for "myApp"]` ); @@ -190,7 +190,7 @@ describe('muteInstance()', () => { describe('auditLogger', () => { test('logs audit event when muting an alert', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -205,7 +205,7 @@ describe('muteInstance()', () => { version: '123', references: [], }); - await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -218,7 +218,7 @@ describe('muteInstance()', () => { }); test('logs audit event when not authorised to mute an alert', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -236,7 +236,7 @@ describe('muteInstance()', () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); await expect( - alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }) + rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }) ).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/unmute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client/tests/unmute_all.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts index 02439d3cd6bad..732cf0083fd1a 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/unmute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -45,7 +45,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -53,7 +53,7 @@ setGlobalDate(); describe('unmuteAll()', () => { test('unmutes an alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -75,7 +75,7 @@ describe('unmuteAll()', () => { version: '123', }); - await alertsClient.unmuteAll({ id: '1' }); + await rulesClient.unmuteAll({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -123,8 +123,8 @@ describe('unmuteAll()', () => { }); test('ensures user is authorised to unmuteAll this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.unmuteAll({ id: '1' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.unmuteAll({ id: '1' }); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ entity: 'rule', @@ -136,12 +136,12 @@ describe('unmuteAll()', () => { }); test('throws when user is not authorised to unmuteAll this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.ensureAuthorized.mockRejectedValue( new Error(`Unauthorized to unmuteAll a "myType" alert for "myApp"`) ); - await expect(alertsClient.unmuteAll({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.unmuteAll({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to unmuteAll a "myType" alert for "myApp"]` ); @@ -156,7 +156,7 @@ describe('unmuteAll()', () => { describe('auditLogger', () => { test('logs audit event when unmuting a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -177,7 +177,7 @@ describe('unmuteAll()', () => { references: [], version: '123', }); - await alertsClient.unmuteAll({ id: '1' }); + await rulesClient.unmuteAll({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -190,7 +190,7 @@ describe('unmuteAll()', () => { }); test('logs audit event when not authorised to unmute a rule', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -213,7 +213,7 @@ describe('unmuteAll()', () => { }); authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.unmuteAll({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.unmuteAll({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/unmute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts similarity index 85% rename from x-pack/plugins/alerting/server/alerts_client/tests/unmute_instance.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts index 3f3ec697a9478..e94007171e07f 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/unmute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -27,7 +27,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -45,7 +45,7 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); @@ -53,7 +53,7 @@ setGlobalDate(); describe('unmuteInstance()', () => { test('unmutes an alert instance', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -69,7 +69,7 @@ describe('unmuteInstance()', () => { references: [], }); - await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -83,7 +83,7 @@ describe('unmuteInstance()', () => { }); test('skips unmuting when alert instance not muted', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -98,12 +98,12 @@ describe('unmuteInstance()', () => { references: [], }); - await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); test('skips unmuting when alert is muted', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -119,7 +119,7 @@ describe('unmuteInstance()', () => { references: [], }); - await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); }); @@ -153,8 +153,8 @@ describe('unmuteInstance()', () => { }); test('ensures user is authorised to unmuteInstance this type of alert under the consumer', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + const rulesClient = new RulesClient(rulesClientParams); + await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ @@ -166,13 +166,13 @@ describe('unmuteInstance()', () => { }); test('throws when user is not authorised to unmuteInstance this type of alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); authorization.ensureAuthorized.mockRejectedValue( new Error(`Unauthorized to unmuteAlert a "myType" alert for "myApp"`) ); await expect( - alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }) + rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }) ).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to unmuteAlert a "myType" alert for "myApp"]` ); @@ -188,7 +188,7 @@ describe('unmuteInstance()', () => { describe('auditLogger', () => { test('logs audit event when unmuting an alert', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -203,7 +203,7 @@ describe('unmuteInstance()', () => { version: '123', references: [], }); - await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ @@ -216,7 +216,7 @@ describe('unmuteInstance()', () => { }); test('logs audit event when not authorised to unmute an alert', async () => { - const alertsClient = new AlertsClient({ ...alertsClientParams, auditLogger }); + const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -234,7 +234,7 @@ describe('unmuteInstance()', () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); await expect( - alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }) + rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }) ).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/update.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts similarity index 96% rename from x-pack/plugins/alerting/server/alerts_client/tests/update.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/update.test.ts index 2de56d20702f4..988638cd01011 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/update.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts @@ -7,7 +7,7 @@ import uuid from 'uuid'; import { schema } from '@kbn/config-schema'; -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -33,7 +33,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -52,14 +52,14 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); setGlobalDate(); describe('update()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; let actionsClient: jest.Mocked; const existingAlert = { id: '1', @@ -98,8 +98,8 @@ describe('update()', () => { }; beforeEach(async () => { - alertsClient = new AlertsClient(alertsClientParams); - actionsClient = (await alertsClientParams.getActionsClient()) as jest.Mocked; + rulesClient = new RulesClient(rulesClientParams); + actionsClient = (await rulesClientParams.getActionsClient()) as jest.Mocked; actionsClient.getBulk.mockReset(); actionsClient.getBulk.mockResolvedValue([ { @@ -118,7 +118,7 @@ describe('update()', () => { isPreconfigured: false, }, ]); - alertsClientParams.getActionsClient.mockResolvedValue(actionsClient); + rulesClientParams.getActionsClient.mockResolvedValue(actionsClient); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); alertTypeRegistry.get.mockReturnValue({ @@ -235,7 +235,7 @@ describe('update()', () => { }, references: [], }); - const result = await alertsClient.update({ + const result = await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -402,7 +402,7 @@ describe('update()', () => { }); it('calls the createApiKey function', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', name: '123', api_key: 'abc' }, }); @@ -458,7 +458,7 @@ describe('update()', () => { }, references: [], }); - const result = await alertsClient.update({ + const result = await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -614,7 +614,7 @@ describe('update()', () => { }, references: [], }); - const result = await alertsClient.update({ + const result = await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -636,7 +636,7 @@ describe('update()', () => { ], }, }); - expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(rulesClientParams.createAPIKey).not.toHaveBeenCalled(); expect(result).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -721,12 +721,12 @@ describe('update()', () => { }); it('throws an error if API key creation throws', async () => { - alertsClientParams.createAPIKey.mockImplementation(() => { + rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); expect( async () => - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -785,7 +785,7 @@ describe('update()', () => { producer: 'alerts', }); await expect( - alertsClient.update({ + rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -846,7 +846,7 @@ describe('update()', () => { }, ], }); - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { ...existingAlert.attributes, @@ -854,7 +854,7 @@ describe('update()', () => { }, }); - expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: myType/my alert name'); + expect(rulesClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: myType/my alert name'); }); it('swallows error when invalidate API key throws', async () => { @@ -888,7 +888,7 @@ describe('update()', () => { ], }); unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Fail')); // add ApiKey to invalidate - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -910,7 +910,7 @@ describe('update()', () => { ], }, }); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'Failed to mark for API key [id="MTIzOmFiYw=="] for invalidation: Fail' ); }); @@ -1007,7 +1007,7 @@ describe('update()', () => { }, ], }); - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1044,19 +1044,19 @@ describe('update()', () => { }, }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'update(): Failed to load API key to invalidate on alert 1: Fail' ); }); test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '234', name: '234', api_key: 'abc' }, }); unsecuredSavedObjectsClient.create.mockRejectedValue(new Error('Fail')); await expect( - alertsClient.update({ + rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1166,7 +1166,7 @@ describe('update()', () => { mockApiCalls(alertId, taskId, { interval: '60m' }, { interval: '10s' }); - await alertsClient.update({ + await rulesClient.update({ id: alertId, data: { schedule: { interval: '10s' }, @@ -1198,7 +1198,7 @@ describe('update()', () => { mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '10s' }); - await alertsClient.update({ + await rulesClient.update({ id: alertId, data: { schedule: { interval: '10s' }, @@ -1235,7 +1235,7 @@ describe('update()', () => { taskManager.runNow.mockReset(); taskManager.runNow.mockReturnValue(resolveAfterAlertUpdatedCompletes); - await alertsClient.update({ + await rulesClient.update({ id: alertId, data: { schedule: { interval: '10s' }, @@ -1271,7 +1271,7 @@ describe('update()', () => { taskManager.runNow.mockReset(); taskManager.runNow.mockRejectedValue(new Error('Failed to run alert')); - await alertsClient.update({ + await rulesClient.update({ id: alertId, data: { schedule: { interval: '10s' }, @@ -1296,7 +1296,7 @@ describe('update()', () => { expect(taskManager.runNow).toHaveBeenCalled(); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( `Alert update failed to run its underlying task. TaskManager runNow failed with Error: Failed to run alert` ); }); @@ -1339,7 +1339,7 @@ describe('update()', () => { ]); await expect( - alertsClient.update({ + rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1403,7 +1403,7 @@ describe('update()', () => { }); test('ensures user is authorised to update this type of alert under the consumer', async () => { - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1432,7 +1432,7 @@ describe('update()', () => { ); await expect( - alertsClient.update({ + rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1480,7 +1480,7 @@ describe('update()', () => { }); test('logs audit event when updating a rule', async () => { - await alertsClient.update({ + await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, @@ -1510,7 +1510,7 @@ describe('update()', () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); await expect( - alertsClient.update({ + rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, diff --git a/x-pack/plugins/alerting/server/alerts_client/tests/update_api_key.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts similarity index 89% rename from x-pack/plugins/alerting/server/alerts_client/tests/update_api_key.test.ts rename to x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts index 15aa0dbc64eb8..6c9015814f9bd 100644 --- a/x-pack/plugins/alerting/server/alerts_client/tests/update_api_key.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AlertsClient, ConstructorOptions } from '../alerts_client'; +import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks'; import { taskManagerMock } from '../../../../task_manager/server/mocks'; import { alertTypeRegistryMock } from '../../alert_type_registry.mock'; @@ -28,7 +28,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const auditLogger = auditServiceMock.create().asScoped(httpServerMock.createKibanaRequest()); const kibanaVersion = 'v7.10.0'; -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -47,14 +47,14 @@ const alertsClientParams: jest.Mocked = { }; beforeEach(() => { - getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry); + getBeforeSetup(rulesClientParams, taskManager, alertTypeRegistry); (auditLogger.log as jest.Mock).mockClear(); }); setGlobalDate(); describe('updateApiKey()', () => { - let alertsClient: AlertsClient; + let rulesClient: RulesClient; const existingAlert = { id: '1', type: 'alert', @@ -87,7 +87,7 @@ describe('updateApiKey()', () => { }; beforeEach(() => { - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', @@ -102,11 +102,11 @@ describe('updateApiKey()', () => { }); test('updates the API key for the alert', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '234', name: '123', api_key: 'abc' }, }); - await alertsClient.updateApiKey({ id: '1' }); + await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', @@ -146,18 +146,18 @@ describe('updateApiKey()', () => { }); test('throws an error if API key creation throws', async () => { - alertsClientParams.createAPIKey.mockImplementation(() => { + rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); expect( - async () => await alertsClient.updateApiKey({ id: '1' }) + async () => await rulesClient.updateApiKey({ id: '1' }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error updating API key for rule: could not create API key - no"` ); }); test('falls back to SOC when getDecryptedAsInternalUser throws an error', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '234', name: '123', api_key: 'abc' }, }); @@ -172,7 +172,7 @@ describe('updateApiKey()', () => { references: [], }); - await alertsClient.updateApiKey({ id: '1' }); + await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', @@ -212,7 +212,7 @@ describe('updateApiKey()', () => { test('swallows error when invalidate API key throws', async () => { unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Fail')); - await alertsClient.updateApiKey({ id: '1' }); + await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toBe( 'api_key_pending_invalidation' @@ -231,8 +231,8 @@ describe('updateApiKey()', () => { references: [], }); - await alertsClient.updateApiKey({ id: '1' }); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + await rulesClient.updateApiKey({ id: '1' }); + expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'updateApiKey(): Failed to load API key to invalidate on alert 1: Fail' ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); @@ -240,7 +240,7 @@ describe('updateApiKey()', () => { }); test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => { - alertsClientParams.createAPIKey.mockResolvedValueOnce({ + rulesClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '234', name: '234', api_key: 'abc' }, }); @@ -255,7 +255,7 @@ describe('updateApiKey()', () => { references: [], }); - await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.updateApiKey({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail"` ); expect( @@ -265,7 +265,7 @@ describe('updateApiKey()', () => { describe('authorization', () => { test('ensures user is authorised to updateApiKey this type of alert under the consumer', async () => { - await alertsClient.updateApiKey({ id: '1' }); + await rulesClient.updateApiKey({ id: '1' }); expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); expect(authorization.ensureAuthorized).toHaveBeenCalledWith({ @@ -281,7 +281,7 @@ describe('updateApiKey()', () => { new Error(`Unauthorized to updateApiKey a "myType" alert for "myApp"`) ); - await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.updateApiKey({ id: '1' })).rejects.toMatchInlineSnapshot( `[Error: Unauthorized to updateApiKey a "myType" alert for "myApp"]` ); @@ -296,7 +296,7 @@ describe('updateApiKey()', () => { describe('auditLogger', () => { test('logs audit event when updating the API key of a rule', async () => { - await alertsClient.updateApiKey({ id: '1' }); + await rulesClient.updateApiKey({ id: '1' }); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ @@ -312,7 +312,7 @@ describe('updateApiKey()', () => { test('logs audit event when not authorised to update the API key of a rule', async () => { authorization.ensureAuthorized.mockRejectedValue(new Error('Unauthorized')); - await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toThrow(); + await expect(rulesClient.updateApiKey({ id: '1' })).rejects.toThrow(); expect(auditLogger.log).toHaveBeenCalledWith( expect.objectContaining({ event: expect.objectContaining({ diff --git a/x-pack/plugins/alerting/server/alerts_client_conflict_retries.test.ts b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts similarity index 88% rename from x-pack/plugins/alerting/server/alerts_client_conflict_retries.test.ts rename to x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts index e45b3513eef26..deded9eee81cf 100644 --- a/x-pack/plugins/alerting/server/alerts_client_conflict_retries.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts @@ -7,7 +7,7 @@ import { cloneDeep } from 'lodash'; -import { AlertsClient, ConstructorOptions } from './alerts_client'; +import { RulesClient, ConstructorOptions } from './rules_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../src/core/server/mocks'; import { taskManagerMock } from '../../task_manager/server/mocks'; import { alertTypeRegistryMock } from './alert_type_registry.mock'; @@ -21,7 +21,7 @@ import { RetryForConflictsAttempts } from './lib/retry_if_conflicts'; import { TaskStatus } from '../../../plugins/task_manager/server/task'; import { RecoveredActionGroup } from '../common'; -let alertsClient: AlertsClient; +let rulesClient: RulesClient; const MockAlertId = 'alert-id'; @@ -37,7 +37,7 @@ const actionsAuthorization = actionsAuthorizationMock.create(); const kibanaVersion = 'v7.10.0'; const logger = loggingSystemMock.create().get(); -const alertsClientParams: jest.Mocked = { +const rulesClientParams: jest.Mocked = { taskManager, alertTypeRegistry, unsecuredSavedObjectsClient, @@ -54,10 +54,10 @@ const alertsClientParams: jest.Mocked = { kibanaVersion, }; -// this suite consists of two suites running tests against mutable alertsClient APIs: +// this suite consists of two suites running tests against mutable RulesClient APIs: // - one to run tests where an SO update conflicts once // - one to run tests where an SO update conflicts too many times -describe('alerts_client_conflict_retries', () => { +describe('rules_client_conflict_retries', () => { // tests that mutable operations work if only one SO conflict occurs describe(`1 retry works for method`, () => { beforeEach(() => { @@ -91,14 +91,14 @@ describe('alerts_client_conflict_retries', () => { }); }); -// alertsClients methods being tested -// - success is passed as an indication if the alertsClient method +// RulesClients methods being tested +// - success is passed as an indication if the RulesClient method // is expected to succeed or not, based on the number of conflicts // set up in the `beforeEach()` method async function update(success: boolean) { try { - await alertsClient.update({ + await rulesClient.update({ id: MockAlertId, data: { schedule: { interval: '5s' }, @@ -112,20 +112,18 @@ async function update(success: boolean) { }); } catch (err) { // only checking the warn messages in this test - expect(logger.warn).lastCalledWith( - `alertsClient.update('alert-id') conflict, exceeded retries` - ); + expect(logger.warn).lastCalledWith(`rulesClient.update('alert-id') conflict, exceeded retries`); return expectConflict(success, err, 'create'); } expectSuccess(success, 3, 'create'); // only checking the debug messages in this test - expect(logger.debug).nthCalledWith(1, `alertsClient.update('alert-id') conflict, retrying ...`); + expect(logger.debug).nthCalledWith(1, `rulesClient.update('alert-id') conflict, retrying ...`); } async function updateApiKey(success: boolean) { try { - await alertsClient.updateApiKey({ id: MockAlertId }); + await rulesClient.updateApiKey({ id: MockAlertId }); } catch (err) { return expectConflict(success, err); } @@ -137,7 +135,7 @@ async function enable(success: boolean) { setupRawAlertMocks({}, { enabled: false }); try { - await alertsClient.enable({ id: MockAlertId }); + await rulesClient.enable({ id: MockAlertId }); } catch (err) { return expectConflict(success, err); } @@ -149,7 +147,7 @@ async function enable(success: boolean) { async function disable(success: boolean) { try { - await alertsClient.disable({ id: MockAlertId }); + await rulesClient.disable({ id: MockAlertId }); } catch (err) { return expectConflict(success, err); } @@ -159,7 +157,7 @@ async function disable(success: boolean) { async function muteAll(success: boolean) { try { - await alertsClient.muteAll({ id: MockAlertId }); + await rulesClient.muteAll({ id: MockAlertId }); } catch (err) { return expectConflict(success, err); } @@ -169,7 +167,7 @@ async function muteAll(success: boolean) { async function unmuteAll(success: boolean) { try { - await alertsClient.unmuteAll({ id: MockAlertId }); + await rulesClient.unmuteAll({ id: MockAlertId }); } catch (err) { return expectConflict(success, err); } @@ -179,7 +177,7 @@ async function unmuteAll(success: boolean) { async function muteInstance(success: boolean) { try { - await alertsClient.muteInstance({ alertId: MockAlertId, alertInstanceId: 'instance-id' }); + await rulesClient.muteInstance({ alertId: MockAlertId, alertInstanceId: 'instance-id' }); } catch (err) { return expectConflict(success, err); } @@ -190,7 +188,7 @@ async function muteInstance(success: boolean) { async function unmuteInstance(success: boolean) { setupRawAlertMocks({}, { mutedInstanceIds: ['instance-id'] }); try { - await alertsClient.unmuteInstance({ alertId: MockAlertId, alertInstanceId: 'instance-id' }); + await rulesClient.unmuteInstance({ alertId: MockAlertId, alertInstanceId: 'instance-id' }); } catch (err) { return expectConflict(success, err); } @@ -307,8 +305,8 @@ function setupRawAlertMocks( beforeEach(() => { jest.resetAllMocks(); - alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false }); - alertsClientParams.getUserName.mockResolvedValue('elastic'); + rulesClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false }); + rulesClientParams.getUserName.mockResolvedValue('elastic'); taskManager.runNow.mockResolvedValue({ id: '' }); taskManager.schedule.mockResolvedValue({ @@ -327,7 +325,7 @@ beforeEach(() => { const actionsClient = actionsClientMock.create(); actionsClient.getBulk.mockResolvedValue([]); - alertsClientParams.getActionsClient.mockResolvedValue(actionsClient); + rulesClientParams.getActionsClient.mockResolvedValue(actionsClient); alertTypeRegistry.get.mockImplementation((id) => ({ id: '123', @@ -353,7 +351,7 @@ beforeEach(() => { producer: 'alerts', }); - alertsClient = new AlertsClient(alertsClientParams); + rulesClient = new RulesClient(rulesClientParams); setupRawAlertMocks(); }); diff --git a/x-pack/plugins/alerting/server/alerts_client_factory.test.ts b/x-pack/plugins/alerting/server/rules_client_factory.test.ts similarity index 74% rename from x-pack/plugins/alerting/server/alerts_client_factory.test.ts rename to x-pack/plugins/alerting/server/rules_client_factory.test.ts index 1b39af9972814..0c259d8080761 100644 --- a/x-pack/plugins/alerting/server/alerts_client_factory.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.test.ts @@ -6,7 +6,7 @@ */ import { Request } from '@hapi/hapi'; -import { AlertsClientFactory, AlertsClientFactoryOpts } from './alerts_client_factory'; +import { RulesClientFactory, RulesClientFactoryOpts } from './rules_client_factory'; import { alertTypeRegistryMock } from './alert_type_registry.mock'; import { taskManagerMock } from '../../task_manager/server/mocks'; import { KibanaRequest } from '../../../../src/core/server'; @@ -28,7 +28,7 @@ import { alertingAuthorizationClientFactoryMock } from './alerting_authorization import { AlertingAuthorization } from './authorization'; import { AlertingAuthorizationClientFactory } from './alerting_authorization_client_factory'; -jest.mock('./alerts_client'); +jest.mock('./rules_client'); jest.mock('./authorization/alerting_authorization'); jest.mock('./authorization/audit_logger'); @@ -41,7 +41,7 @@ const securityPluginStart = securityMock.createStart(); const alertsAuthorization = alertingAuthorizationMock.create(); const alertingAuthorizationClientFactory = alertingAuthorizationClientFactoryMock.createFactory(); -const alertsClientFactoryParams: jest.Mocked = { +const rulesClientFactoryParams: jest.Mocked = { logger: loggingSystemMock.create().get(), taskManager: taskManagerMock.createStart(), alertTypeRegistry: alertTypeRegistryMock.create(), @@ -75,17 +75,17 @@ const actionsAuthorization = actionsAuthorizationMock.create(); beforeEach(() => { jest.resetAllMocks(); - alertsClientFactoryParams.actions = actionsMock.createStart(); - (alertsClientFactoryParams.actions as jest.Mocked).getActionsAuthorizationWithRequest.mockReturnValue( + rulesClientFactoryParams.actions = actionsMock.createStart(); + (rulesClientFactoryParams.actions as jest.Mocked).getActionsAuthorizationWithRequest.mockReturnValue( actionsAuthorization ); - alertsClientFactoryParams.getSpaceId.mockReturnValue('default'); - alertsClientFactoryParams.spaceIdToNamespace.mockReturnValue('default'); + rulesClientFactoryParams.getSpaceId.mockReturnValue('default'); + rulesClientFactoryParams.spaceIdToNamespace.mockReturnValue('default'); }); test('creates an alerts client with proper constructor arguments when security is enabled', async () => { - const factory = new AlertsClientFactory(); - factory.initialize({ securityPluginSetup, securityPluginStart, ...alertsClientFactoryParams }); + const factory = new RulesClientFactory(); + factory.initialize({ securityPluginSetup, securityPluginStart, ...rulesClientFactoryParams }); const request = KibanaRequest.from(fakeRequest); savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); @@ -109,31 +109,31 @@ test('creates an alerts client with proper constructor arguments when security i ALERTS_FEATURE_ID, ]); - expect(alertsClientFactoryParams.actions.getActionsAuthorizationWithRequest).toHaveBeenCalledWith( + expect(rulesClientFactoryParams.actions.getActionsAuthorizationWithRequest).toHaveBeenCalledWith( request ); - expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({ + expect(jest.requireMock('./rules_client').RulesClient).toHaveBeenCalledWith({ unsecuredSavedObjectsClient: savedObjectsClient, authorization: alertsAuthorization, actionsAuthorization, - logger: alertsClientFactoryParams.logger, - taskManager: alertsClientFactoryParams.taskManager, - alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, + logger: rulesClientFactoryParams.logger, + taskManager: rulesClientFactoryParams.taskManager, + alertTypeRegistry: rulesClientFactoryParams.alertTypeRegistry, spaceId: 'default', namespace: 'default', getUserName: expect.any(Function), getActionsClient: expect.any(Function), getEventLogClient: expect.any(Function), createAPIKey: expect.any(Function), - encryptedSavedObjectsClient: alertsClientFactoryParams.encryptedSavedObjectsClient, + encryptedSavedObjectsClient: rulesClientFactoryParams.encryptedSavedObjectsClient, kibanaVersion: '7.10.0', }); }); test('creates an alerts client with proper constructor arguments', async () => { - const factory = new AlertsClientFactory(); - factory.initialize(alertsClientFactoryParams); + const factory = new RulesClientFactory(); + factory.initialize(rulesClientFactoryParams); const request = KibanaRequest.from(fakeRequest); savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); @@ -152,18 +152,18 @@ test('creates an alerts client with proper constructor arguments', async () => { ALERTS_FEATURE_ID, ]); - expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({ + expect(jest.requireMock('./rules_client').RulesClient).toHaveBeenCalledWith({ unsecuredSavedObjectsClient: savedObjectsClient, authorization: alertsAuthorization, actionsAuthorization, - logger: alertsClientFactoryParams.logger, - taskManager: alertsClientFactoryParams.taskManager, - alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, + logger: rulesClientFactoryParams.logger, + taskManager: rulesClientFactoryParams.taskManager, + alertTypeRegistry: rulesClientFactoryParams.alertTypeRegistry, spaceId: 'default', namespace: 'default', getUserName: expect.any(Function), createAPIKey: expect.any(Function), - encryptedSavedObjectsClient: alertsClientFactoryParams.encryptedSavedObjectsClient, + encryptedSavedObjectsClient: rulesClientFactoryParams.encryptedSavedObjectsClient, getActionsClient: expect.any(Function), getEventLogClient: expect.any(Function), kibanaVersion: '7.10.0', @@ -171,24 +171,24 @@ test('creates an alerts client with proper constructor arguments', async () => { }); test('getUserName() returns null when security is disabled', async () => { - const factory = new AlertsClientFactory(); - factory.initialize(alertsClientFactoryParams); + const factory = new RulesClientFactory(); + factory.initialize(rulesClientFactoryParams); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; const userNameResult = await constructorCall.getUserName(); expect(userNameResult).toEqual(null); }); test('getUserName() returns a name when security is enabled', async () => { - const factory = new AlertsClientFactory(); + const factory = new RulesClientFactory(); factory.initialize({ - ...alertsClientFactoryParams, + ...rulesClientFactoryParams, securityPluginSetup, securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; securityPluginStart.authc.getCurrentUser.mockReturnValueOnce(({ username: 'bob', @@ -198,30 +198,30 @@ test('getUserName() returns a name when security is enabled', async () => { }); test('getActionsClient() returns ActionsClient', async () => { - const factory = new AlertsClientFactory(); - factory.initialize(alertsClientFactoryParams); + const factory = new RulesClientFactory(); + factory.initialize(rulesClientFactoryParams); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; const actionsClient = await constructorCall.getActionsClient(); expect(actionsClient).not.toBe(null); }); test('createAPIKey() returns { apiKeysEnabled: false } when security is disabled', async () => { - const factory = new AlertsClientFactory(); - factory.initialize(alertsClientFactoryParams); + const factory = new RulesClientFactory(); + factory.initialize(rulesClientFactoryParams); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; const createAPIKeyResult = await constructorCall.createAPIKey(); expect(createAPIKeyResult).toEqual({ apiKeysEnabled: false }); }); test('createAPIKey() returns { apiKeysEnabled: false } when security is enabled but ES security is disabled', async () => { - const factory = new AlertsClientFactory(); - factory.initialize(alertsClientFactoryParams); + const factory = new RulesClientFactory(); + factory.initialize(rulesClientFactoryParams); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; securityPluginStart.authc.apiKeys.grantAsInternalUser.mockResolvedValueOnce(null); const createAPIKeyResult = await constructorCall.createAPIKey(); @@ -229,14 +229,14 @@ test('createAPIKey() returns { apiKeysEnabled: false } when security is enabled }); test('createAPIKey() returns an API key when security is enabled', async () => { - const factory = new AlertsClientFactory(); + const factory = new RulesClientFactory(); factory.initialize({ - ...alertsClientFactoryParams, + ...rulesClientFactoryParams, securityPluginSetup, securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; securityPluginStart.authc.apiKeys.grantAsInternalUser.mockResolvedValueOnce({ api_key: '123', @@ -251,14 +251,14 @@ test('createAPIKey() returns an API key when security is enabled', async () => { }); test('createAPIKey() throws when security plugin createAPIKey throws an error', async () => { - const factory = new AlertsClientFactory(); + const factory = new RulesClientFactory(); factory.initialize({ - ...alertsClientFactoryParams, + ...rulesClientFactoryParams, securityPluginSetup, securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); - const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; + const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; securityPluginStart.authc.apiKeys.grantAsInternalUser.mockRejectedValueOnce( new Error('TLS disabled') diff --git a/x-pack/plugins/alerting/server/alerts_client_factory.ts b/x-pack/plugins/alerting/server/rules_client_factory.ts similarity index 94% rename from x-pack/plugins/alerting/server/alerts_client_factory.ts rename to x-pack/plugins/alerting/server/rules_client_factory.ts index 3bb014bf9fd07..3c6800fc5bd74 100644 --- a/x-pack/plugins/alerting/server/alerts_client_factory.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.ts @@ -12,7 +12,7 @@ import { PluginInitializerContext, } from 'src/core/server'; import { PluginStartContract as ActionsPluginStartContract } from '../../actions/server'; -import { AlertsClient } from './alerts_client'; +import { RulesClient } from './rules_client'; import { AlertTypeRegistry, SpaceIdToNamespaceFunction } from './types'; import { SecurityPluginSetup, SecurityPluginStart } from '../../security/server'; import { EncryptedSavedObjectsClient } from '../../encrypted_saved_objects/server'; @@ -20,7 +20,7 @@ import { TaskManagerStartContract } from '../../task_manager/server'; import { IEventLogClientService } from '../../../plugins/event_log/server'; import { AlertingAuthorizationClientFactory } from './alerting_authorization_client_factory'; import { ALERTS_FEATURE_ID } from '../common'; -export interface AlertsClientFactoryOpts { +export interface RulesClientFactoryOpts { logger: Logger; taskManager: TaskManagerStartContract; alertTypeRegistry: AlertTypeRegistry; @@ -35,7 +35,7 @@ export interface AlertsClientFactoryOpts { authorization: AlertingAuthorizationClientFactory; } -export class AlertsClientFactory { +export class RulesClientFactory { private isInitialized = false; private logger!: Logger; private taskManager!: TaskManagerStartContract; @@ -50,9 +50,9 @@ export class AlertsClientFactory { private kibanaVersion!: PluginInitializerContext['env']['packageInfo']['version']; private authorization!: AlertingAuthorizationClientFactory; - public initialize(options: AlertsClientFactoryOpts) { + public initialize(options: RulesClientFactoryOpts) { if (this.isInitialized) { - throw new Error('AlertsClientFactory already initialized'); + throw new Error('RulesClientFactory already initialized'); } this.isInitialized = true; this.logger = options.logger; @@ -69,7 +69,7 @@ export class AlertsClientFactory { this.authorization = options.authorization; } - public create(request: KibanaRequest, savedObjects: SavedObjectsServiceStart): AlertsClient { + public create(request: KibanaRequest, savedObjects: SavedObjectsServiceStart): RulesClient { const { securityPluginSetup, securityPluginStart, actions, eventLog } = this; const spaceId = this.getSpaceId(request); @@ -77,7 +77,7 @@ export class AlertsClientFactory { throw new Error('AlertingAuthorizationClientFactory is not defined'); } - return new AlertsClient({ + return new RulesClient({ spaceId, kibanaVersion: this.kibanaVersion, logger: this.logger, diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts index 4f650975f830e..a3472c4f40630 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts @@ -29,7 +29,7 @@ import { } from '../../../../../src/core/server/mocks'; import { PluginStartContract as ActionsPluginStart } from '../../../actions/server'; import { actionsMock, actionsClientMock } from '../../../actions/server/mocks'; -import { alertsMock, alertsClientMock } from '../mocks'; +import { alertsMock, rulesClientMock } from '../mocks'; import { eventLoggerMock } from '../../../event_log/server/event_logger.mock'; import { IEventLogger } from '../../../event_log/server'; import { SavedObjectsErrorHelpers } from '../../../../../src/core/server'; @@ -81,7 +81,7 @@ describe('Task Runner', () => { const encryptedSavedObjectsClient = encryptedSavedObjectsMock.createClient(); const services = alertsMock.createAlertServices(); const actionsClient = actionsClientMock.create(); - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const alertTypeRegistry = alertTypeRegistryMock.create(); const taskRunnerFactoryInitializerParams: jest.Mocked & { @@ -90,7 +90,7 @@ describe('Task Runner', () => { } = { getServices: jest.fn().mockReturnValue(services), actionsPlugin: actionsMock.createStart(), - getAlertsClientWithRequest: jest.fn().mockReturnValue(alertsClient), + getRulesClientWithRequest: jest.fn().mockReturnValue(rulesClient), encryptedSavedObjectsClient, logger: loggingSystemMock.create().get(), spaceIdToNamespace: jest.fn().mockReturnValue(undefined), @@ -151,7 +151,7 @@ describe('Task Runner', () => { beforeEach(() => { jest.resetAllMocks(); taskRunnerFactoryInitializerParams.getServices.mockReturnValue(services); - taskRunnerFactoryInitializerParams.getAlertsClientWithRequest.mockReturnValue(alertsClient); + taskRunnerFactoryInitializerParams.getRulesClientWithRequest.mockReturnValue(rulesClient); taskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mockResolvedValue( actionsClient ); @@ -173,7 +173,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -337,7 +337,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -571,7 +571,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, muteAll: true, }); @@ -760,7 +760,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, mutedInstanceIds: ['2'], }); @@ -830,7 +830,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', }); @@ -995,7 +995,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', }); @@ -1051,7 +1051,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', }); @@ -1088,7 +1088,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -1387,7 +1387,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -1735,7 +1735,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: alertId, type: 'alert', @@ -1818,7 +1818,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, actions: [ { @@ -1940,7 +1940,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -2137,7 +2137,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -2165,7 +2165,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -2198,7 +2198,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -2229,8 +2229,8 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); - alertsClient.get.mockResolvedValueOnce({ + rulesClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValueOnce({ ...mockedAlertTypeSavedObject, schedule: { interval: '30s' }, }); @@ -2278,7 +2278,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -2395,7 +2395,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); const runnerResult = await taskRunner.run(); @@ -2504,7 +2504,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -2621,7 +2621,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -2728,7 +2728,7 @@ describe('Task Runner', () => { }); test('recovers gracefully when the Alert Task Runner throws an exception when fetching attributes', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw new Error('OMG'); }); @@ -2844,7 +2844,7 @@ describe('Task Runner', () => { }); test('recovers gracefully when the Runner of a legacy Alert task which has no schedule throws an exception when fetching attributes', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw new Error('OMG'); }); @@ -2907,7 +2907,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -2925,7 +2925,7 @@ describe('Task Runner', () => { }); test('avoids rescheduling a failed Alert Task Runner when it throws due to failing to fetch the alert', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1'); }); @@ -2960,7 +2960,7 @@ describe('Task Runner', () => { }); test('correctly logs warning when Alert Task Runner throws due to failing to fetch the alert in a space', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1'); }); @@ -3027,7 +3027,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', actions: [], @@ -3313,7 +3313,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', actions: [], @@ -3519,7 +3519,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', actions: [], @@ -3716,7 +3716,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', actions: [], @@ -3919,7 +3919,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - alertsClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', actions: [], diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.ts index c66c054bc8ac3..c8cc41f3d410a 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -39,7 +39,7 @@ import { taskInstanceToAlertTaskInstance } from './alert_task_instance'; import { EVENT_LOG_ACTIONS } from '../plugin'; import { IEvent, IEventLogger, SAVED_OBJECT_REL_PRIMARY } from '../../../event_log/server'; import { isAlertSavedObjectNotFoundError } from '../lib/is_alert_not_found_error'; -import { AlertsClient } from '../alerts_client'; +import { RulesClient } from '../rules_client'; import { partiallyUpdateAlert } from '../saved_objects'; import { ActionGroup, @@ -154,9 +154,9 @@ export class TaskRunner< private getServicesWithSpaceLevelPermissions( spaceId: string, apiKey: RawAlert['apiKey'] - ): [Services, PublicMethodsOf] { + ): [Services, PublicMethodsOf] { const request = this.getFakeKibanaRequest(spaceId, apiKey); - return [this.context.getServices(request), this.context.getAlertsClientWithRequest(request)]; + return [this.context.getServices(request), this.context.getRulesClientWithRequest(request)]; } private getExecutionHandler( @@ -456,13 +456,13 @@ export class TaskRunner< } catch (err) { throw new ErrorWithReason(AlertExecutionStatusErrorReasons.Decrypt, err); } - const [services, alertsClient] = this.getServicesWithSpaceLevelPermissions(spaceId, apiKey); + const [services, rulesClient] = this.getServicesWithSpaceLevelPermissions(spaceId, apiKey); let alert: SanitizedAlert; // Ensure API key is still valid and user has access try { - alert = await alertsClient.get({ id: alertId }); + alert = await rulesClient.get({ id: alertId }); } catch (err) { throw new ErrorWithReason(AlertExecutionStatusErrorReasons.Read, err); } @@ -479,7 +479,7 @@ export class TaskRunner< schedule: asOk( // fetch the alert again to ensure we return the correct schedule as it may have // cahnged during the task execution - (await alertsClient.get({ id: alertId })).schedule + (await rulesClient.get({ id: alertId })).schedule ), }; } diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts index 050345f3e617f..b0ec95135ffa8 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts @@ -15,7 +15,7 @@ import { httpServiceMock, } from '../../../../../src/core/server/mocks'; import { actionsMock } from '../../../actions/server/mocks'; -import { alertsMock, alertsClientMock } from '../mocks'; +import { alertsMock, rulesClientMock } from '../mocks'; import { eventLoggerMock } from '../../../event_log/server/event_logger.mock'; import { UntypedNormalizedAlertType } from '../alert_type_registry'; import { alertTypeRegistryMock } from '../alert_type_registry.mock'; @@ -65,11 +65,11 @@ describe('Task Runner Factory', () => { const encryptedSavedObjectsPlugin = encryptedSavedObjectsMock.createStart(); const services = alertsMock.createAlertServices(); - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const taskRunnerFactoryInitializerParams: jest.Mocked = { getServices: jest.fn().mockReturnValue(services), - getAlertsClientWithRequest: jest.fn().mockReturnValue(alertsClient), + getRulesClientWithRequest: jest.fn().mockReturnValue(rulesClient), actionsPlugin: actionsMock.createStart(), encryptedSavedObjectsClient: encryptedSavedObjectsPlugin.getClient(), logger: loggingSystemMock.create().get(), diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.ts index a023776134e9c..61ce385c2a2a0 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.ts @@ -26,13 +26,13 @@ import { } from '../types'; import { TaskRunner } from './task_runner'; import { IEventLogger } from '../../../event_log/server'; -import { AlertsClient } from '../alerts_client'; +import { RulesClient } from '../rules_client'; import { NormalizedAlertType } from '../alert_type_registry'; export interface TaskRunnerContext { logger: Logger; getServices: GetServicesFunction; - getAlertsClientWithRequest(request: KibanaRequest): PublicMethodsOf; + getRulesClientWithRequest(request: KibanaRequest): PublicMethodsOf; actionsPlugin: ActionsPluginStartContract; eventLogger: IEventLogger; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; diff --git a/x-pack/plugins/alerting/server/types.ts b/x-pack/plugins/alerting/server/types.ts index f21e17adc841d..77d78813828d0 100644 --- a/x-pack/plugins/alerting/server/types.ts +++ b/x-pack/plugins/alerting/server/types.ts @@ -10,7 +10,7 @@ import type { PublicMethodsOf } from '@kbn/utility-types'; import { PublicAlertInstance } from './alert_instance'; import { AlertTypeRegistry as OrigAlertTypeRegistry } from './alert_type_registry'; import { PluginSetupContract, PluginStartContract } from './plugin'; -import { AlertsClient } from './alerts_client'; +import { RulesClient } from './rules_client'; export * from '../common'; import { IScopedClusterClient, @@ -44,7 +44,7 @@ export type SpaceIdToNamespaceFunction = (spaceId?: string) => string | undefine * @public */ export interface AlertingApiRequestHandlerContext { - getAlertsClient: () => AlertsClient; + getRulesClient: () => RulesClient; listTypes: AlertTypeRegistry['list']; getFrameworkHealth: () => Promise; areApiKeysEnabled: () => Promise; diff --git a/x-pack/plugins/ml/server/models/job_service/index.ts b/x-pack/plugins/ml/server/models/job_service/index.ts index 94dc669bfd946..94c25581e8e84 100644 --- a/x-pack/plugins/ml/server/models/job_service/index.ts +++ b/x-pack/plugins/ml/server/models/job_service/index.ts @@ -13,16 +13,16 @@ import { newJobCapsProvider } from './new_job_caps'; import { newJobChartsProvider, topCategoriesProvider } from './new_job'; import { modelSnapshotProvider } from './model_snapshots'; import type { MlClient } from '../../lib/ml_client'; -import type { AlertsClient } from '../../../../alerting/server'; +import type { RulesClient } from '../../../../alerting/server'; export function jobServiceProvider( client: IScopedClusterClient, mlClient: MlClient, - alertsClient?: AlertsClient + rulesClient?: RulesClient ) { return { ...datafeedsProvider(client, mlClient), - ...jobsProvider(client, mlClient, alertsClient), + ...jobsProvider(client, mlClient, rulesClient), ...groupsProvider(mlClient), ...newJobCapsProvider(client), ...newJobChartsProvider(client), diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index 22bac1cb08e19..6732c8fe7e2f1 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -40,7 +40,7 @@ import { import { groupsProvider } from './groups'; import type { MlClient } from '../../lib/ml_client'; import { isPopulatedObject } from '../../../common/util/object_utils'; -import type { AlertsClient } from '../../../../alerting/server'; +import type { RulesClient } from '../../../../alerting/server'; import { ML_ALERT_TYPES } from '../../../common/constants/alerts'; import { MlAnomalyDetectionAlertParams } from '../../routes/schemas/alerting_schema'; @@ -54,7 +54,7 @@ interface Results { export function jobsProvider( client: IScopedClusterClient, mlClient: MlClient, - alertsClient?: AlertsClient + rulesClient?: RulesClient ) { const { asInternalUser } = client; @@ -421,8 +421,8 @@ export function jobsProvider( jobs.push(tempJob); }); - if (alertsClient) { - const mlAlertingRules = await alertsClient.find({ + if (rulesClient) { + const mlAlertingRules = await rulesClient.find({ options: { filter: `alert.attributes.alertTypeId:${ML_ALERT_TYPES.ANOMALY_DETECTION}`, perPage: 1000, diff --git a/x-pack/plugins/ml/server/routes/job_service.ts b/x-pack/plugins/ml/server/routes/job_service.ts index 992822f6d6eb8..023997a35a6a6 100644 --- a/x-pack/plugins/ml/server/routes/job_service.ts +++ b/x-pack/plugins/ml/server/routes/job_service.ts @@ -235,7 +235,7 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { const { jobsSummary } = jobServiceProvider( client, mlClient, - context.alerting?.getAlertsClient() + context.alerting?.getRulesClient() ); const { jobIds } = request.body; const resp = await jobsSummary(jobIds); @@ -340,7 +340,7 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { const { createFullJobsList } = jobServiceProvider( client, mlClient, - context.alerting?.getAlertsClient() + context.alerting?.getRulesClient() ); const { jobIds } = request.body; const resp = await createFullJobsList(jobIds); diff --git a/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts b/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts index bd18d285e29aa..8cda6a15b5393 100644 --- a/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts +++ b/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts @@ -17,16 +17,16 @@ jest.mock('../static_globals', () => ({ })); describe('AlertsFactory', () => { - const alertsClient = { + const rulesClient = { find: jest.fn(), }; afterEach(() => { - alertsClient.find.mockReset(); + rulesClient.find.mockReset(); }); it('should get by type', async () => { - alertsClient.find = jest.fn().mockImplementation(() => { + rulesClient.find = jest.fn().mockImplementation(() => { return { total: 1, data: [ @@ -36,20 +36,20 @@ describe('AlertsFactory', () => { ], }; }); - const alert = await AlertsFactory.getByType(ALERT_CPU_USAGE, alertsClient as any); + const alert = await AlertsFactory.getByType(ALERT_CPU_USAGE, rulesClient as any); expect(alert).not.toBeNull(); expect(alert?.getId()).toBe(ALERT_CPU_USAGE); }); it('should pass in the correct filters', async () => { let filter = null; - alertsClient.find = jest.fn().mockImplementation(({ options }) => { + rulesClient.find = jest.fn().mockImplementation(({ options }) => { filter = options.filter; return { total: 0, }; }); - await AlertsFactory.getByType(ALERT_CPU_USAGE, alertsClient as any); + await AlertsFactory.getByType(ALERT_CPU_USAGE, rulesClient as any); expect(filter).toBe(`alert.attributes.alertTypeId:${ALERT_CPU_USAGE}`); }); }); diff --git a/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts b/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts index 0bb8fe39fd9a0..fad3da83e36a5 100644 --- a/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts +++ b/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts @@ -38,7 +38,7 @@ import { ALERT_CCR_READ_EXCEPTIONS, ALERT_LARGE_SHARD_SIZE, } from '../../common/constants'; -import { AlertsClient } from '../../../alerting/server'; +import { RulesClient } from '../../../alerting/server'; import { Alert } from '../../../alerting/common'; const BY_TYPE = { @@ -61,13 +61,13 @@ const BY_TYPE = { export class AlertsFactory { public static async getByType( type: string, - alertsClient: AlertsClient | undefined + rulesClient: RulesClient | undefined ): Promise { const alertCls = BY_TYPE[type]; - if (!alertCls || !alertsClient) { + if (!alertCls || !rulesClient) { return; } - const alertClientAlerts = await alertsClient.find({ + const alertClientAlerts = await rulesClient.find({ options: { filter: `alert.attributes.alertTypeId:${type}`, }, diff --git a/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts index c89890397be7c..3fe4eac712487 100644 --- a/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts +++ b/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts @@ -19,7 +19,7 @@ describe('BaseAlert', () => { describe('create', () => { it('should create an alert if it does not exist', async () => { const alert = new BaseAlert(); - const alertsClient = { + const rulesClient = { create: jest.fn(), find: jest.fn().mockImplementation(() => { return { @@ -41,8 +41,8 @@ describe('BaseAlert', () => { }, ]; - await alert.createIfDoesNotExist(alertsClient as any, actionsClient as any, actions); - expect(alertsClient.create).toHaveBeenCalledWith({ + await alert.createIfDoesNotExist(rulesClient as any, actionsClient as any, actions); + expect(rulesClient.create).toHaveBeenCalledWith({ data: { actions: [ { @@ -73,7 +73,7 @@ describe('BaseAlert', () => { it('should not create an alert if it exists', async () => { const alert = new BaseAlert(); - const alertsClient = { + const rulesClient = { create: jest.fn(), find: jest.fn().mockImplementation(() => { return { @@ -96,14 +96,14 @@ describe('BaseAlert', () => { }, ]; - await alert.createIfDoesNotExist(alertsClient as any, actionsClient as any, actions); - expect(alertsClient.create).not.toHaveBeenCalled(); + await alert.createIfDoesNotExist(rulesClient as any, actionsClient as any, actions); + expect(rulesClient.create).not.toHaveBeenCalled(); }); }); describe('getStates', () => { it('should get alert states', async () => { - const alertsClient = { + const rulesClient = { getAlertState: jest.fn().mockImplementation(() => { return { alertInstances: { @@ -117,7 +117,7 @@ describe('BaseAlert', () => { const id = '456def'; const filters: any[] = []; const alert = new BaseAlert(); - const states = await alert.getStates(alertsClient as any, id, filters); + const states = await alert.getStates(rulesClient as any, id, filters); expect(states).toStrictEqual({ abc123: { id: 'foobar', @@ -126,7 +126,7 @@ describe('BaseAlert', () => { }); it('should return nothing if no states are available', async () => { - const alertsClient = { + const rulesClient = { getAlertState: jest.fn().mockImplementation(() => { return null; }), @@ -134,7 +134,7 @@ describe('BaseAlert', () => { const id = '456def'; const filters: any[] = []; const alert = new BaseAlert(); - const states = await alert.getStates(alertsClient as any, id, filters); + const states = await alert.getStates(rulesClient as any, id, filters); expect(states).toStrictEqual({}); }); }); diff --git a/x-pack/plugins/monitoring/server/alerts/base_alert.ts b/x-pack/plugins/monitoring/server/alerts/base_alert.ts index cfd7630a65dbc..b54c6df76bff2 100644 --- a/x-pack/plugins/monitoring/server/alerts/base_alert.ts +++ b/x-pack/plugins/monitoring/server/alerts/base_alert.ts @@ -11,7 +11,7 @@ import { AlertType, AlertExecutorOptions, AlertInstance, - AlertsClient, + RulesClient, AlertServices, } from '../../../alerting/server'; import { Alert, AlertTypeParams, RawAlertInstance, SanitizedAlert } from '../../../alerting/common'; @@ -114,11 +114,11 @@ export class BaseAlert { } public async createIfDoesNotExist( - alertsClient: AlertsClient, + rulesClient: RulesClient, actionsClient: ActionsClient, actions: AlertEnableAction[] ): Promise> { - const existingAlertData = await alertsClient.find({ + const existingAlertData = await rulesClient.find({ options: { search: this.alertOptions.id, }, @@ -152,7 +152,7 @@ export class BaseAlert { throttle = '1d', interval = '1m', } = this.alertOptions; - return await alertsClient.create({ + return await rulesClient.create({ data: { enabled: true, tags: [], @@ -169,11 +169,11 @@ export class BaseAlert { } public async getStates( - alertsClient: AlertsClient, + rulesClient: RulesClient, id: string, filters: CommonAlertFilter[] ): Promise<{ [instanceId: string]: RawAlertInstance }> { - const states = await alertsClient.getAlertState({ id }); + const states = await rulesClient.getAlertState({ id }); if (!states || !states.alertInstances) { return {}; } diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts index 0d2d9fdbed635..ffcab27568597 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts @@ -47,7 +47,7 @@ describe('fetchStatus', () => { }; let alertStates: AlertState[] = []; const licenseService = null; - const alertsClient = { + const rulesClient = { find: jest.fn(() => ({ total: 1, data: [ @@ -68,13 +68,13 @@ describe('fetchStatus', () => { }; afterEach(() => { - (alertsClient.find as jest.Mock).mockClear(); - (alertsClient.getAlertState as jest.Mock).mockClear(); + (rulesClient.find as jest.Mock).mockClear(); + (rulesClient.getAlertState as jest.Mock).mockClear(); alertStates.length = 0; }); it('should fetch from the alerts client', async () => { - const status = await fetchStatus(alertsClient as any, licenseService as any, alertTypes, [ + const status = await fetchStatus(rulesClient as any, licenseService as any, alertTypes, [ defaultClusterState.clusterUuid, ]); expect(status).toEqual({ @@ -96,7 +96,7 @@ describe('fetchStatus', () => { }, ]; - const status = await fetchStatus(alertsClient as any, licenseService as any, alertTypes, [ + const status = await fetchStatus(rulesClient as any, licenseService as any, alertTypes, [ defaultClusterState.clusterUuid, ]); expect(Object.values(status).length).toBe(1); @@ -105,32 +105,32 @@ describe('fetchStatus', () => { }); it('should pass in the right filter to the alerts client', async () => { - await fetchStatus(alertsClient as any, licenseService as any, alertTypes, [ + await fetchStatus(rulesClient as any, licenseService as any, alertTypes, [ defaultClusterState.clusterUuid, ]); - expect((alertsClient.find as jest.Mock).mock.calls[0][0].options.filter).toBe( + expect((rulesClient.find as jest.Mock).mock.calls[0][0].options.filter).toBe( `alert.attributes.alertTypeId:${alertType}` ); }); it('should return nothing if no alert state is found', async () => { - alertsClient.getAlertState = jest.fn(() => ({ + rulesClient.getAlertState = jest.fn(() => ({ alertTypeState: null, })) as any; - const status = await fetchStatus(alertsClient as any, licenseService as any, alertTypes, [ + const status = await fetchStatus(rulesClient as any, licenseService as any, alertTypes, [ defaultClusterState.clusterUuid, ]); expect(status[alertType].states.length).toEqual(0); }); it('should return nothing if no alerts are found', async () => { - alertsClient.find = jest.fn(() => ({ + rulesClient.find = jest.fn(() => ({ total: 0, data: [], })) as any; - const status = await fetchStatus(alertsClient as any, licenseService as any, alertTypes, [ + const status = await fetchStatus(rulesClient as any, licenseService as any, alertTypes, [ defaultClusterState.clusterUuid, ]); expect(status).toEqual({}); @@ -145,7 +145,7 @@ describe('fetchStatus', () => { })), }; await fetchStatus( - alertsClient as any, + rulesClient as any, customLicenseService as any, [ALERT_CLUSTER_HEALTH], [defaultClusterState.clusterUuid] @@ -154,7 +154,7 @@ describe('fetchStatus', () => { }); it('should sort the alerts', async () => { - const customAlertsClient = { + const customRulesClient = { find: jest.fn(() => ({ total: 1, data: [ @@ -182,7 +182,7 @@ describe('fetchStatus', () => { })), }; const status = await fetchStatus( - customAlertsClient as any, + customRulesClient as any, licenseService as any, [ALERT_CPU_USAGE, ALERT_DISK_USAGE, ALERT_MISSING_MONITORING_DATA], [defaultClusterState.clusterUuid] diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts index a7b2457130744..f4fd792ddf922 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts @@ -6,7 +6,7 @@ */ import { AlertInstanceState } from '../../../common/types/alerts'; -import { AlertsClient } from '../../../../alerting/server'; +import { RulesClient } from '../../../../alerting/server'; import { AlertsFactory } from '../../alerts'; import { CommonAlertStatus, @@ -17,7 +17,7 @@ import { ALERTS } from '../../../common/constants'; import { MonitoringLicenseService } from '../../types'; export async function fetchStatus( - alertsClient: AlertsClient, + rulesClient: RulesClient, licenseService: MonitoringLicenseService, alertTypes: string[] | undefined, clusterUuids: string[], @@ -27,7 +27,7 @@ export async function fetchStatus( const byType: { [type: string]: CommonAlertStatus } = {}; await Promise.all( (alertTypes || ALERTS).map(async (type) => { - const alert = await AlertsFactory.getByType(type, alertsClient); + const alert = await AlertsFactory.getByType(type, rulesClient); if (!alert || !alert.rawAlert) { return; } @@ -45,7 +45,7 @@ export async function fetchStatus( } // Now that we have the id, we can get the state - const states = await alert.getStates(alertsClient, id, filters); + const states = await alert.getStates(rulesClient, id, filters); if (!states) { return result; } diff --git a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js index 77b71d3e92f4c..9ef309cee7312 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js @@ -117,16 +117,16 @@ export async function getClustersFromRequest( // add alerts data if (isInCodePath(codePaths, [CODE_PATH_ALERTS])) { - const alertsClient = req.getAlertsClient(); + const rulesClient = req.getRulesClient(); const alertStatus = await fetchStatus( - alertsClient, + rulesClient, req.server.plugins.monitoring.info, undefined, clusters.map((cluster) => get(cluster, 'elasticsearch.cluster.id', cluster.cluster_uuid)) ); for (const cluster of clusters) { - if (!alertsClient) { + if (!rulesClient) { cluster.alerts = { list: {}, alertsMeta: { diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index ca8d87bd300a0..aed48b7391529 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -347,9 +347,9 @@ export class MonitoringPlugin getKibanaStatsCollector: () => this.legacyShimDependencies.kibanaStatsCollector, getUiSettingsService: () => context.core.uiSettings.client, getActionTypeRegistry: () => context.actions?.listTypes(), - getAlertsClient: () => { + getRulesClient: () => { try { - return plugins.alerting.getAlertsClientWithRequest(req); + return plugins.alerting.getRulesClientWithRequest(req); } catch (err) { // If security is disabled, this call will throw an error unless a certain config is set for dist builds return null; diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts index e21304e8458e3..ef6e03e7c999c 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts +++ b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts @@ -56,10 +56,10 @@ export function enableAlertsRoute(server: LegacyServer, npRoute: RouteDependenci } } - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const actionsClient = context.actions?.getActionsClient(); const types = context.actions?.listTypes(); - if (!alertsClient || !actionsClient || !types) { + if (!rulesClient || !actionsClient || !types) { return response.ok({ body: undefined }); } @@ -99,7 +99,7 @@ export function enableAlertsRoute(server: LegacyServer, npRoute: RouteDependenci if (disabledWatcherClusterAlerts) { createdAlerts = await Promise.all( - alerts.map((alert) => alert.createIfDoesNotExist(alertsClient, actionsClient, actions)) + alerts.map((alert) => alert.createIfDoesNotExist(rulesClient, actionsClient, actions)) ); } diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts index 95e2cb63bec86..f77630e5d61a5 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts +++ b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts @@ -34,13 +34,13 @@ export function alertStatusRoute(server: any, npRoute: RouteDependencies) { try { const { clusterUuid } = request.params; const { alertTypeIds, filters } = request.body; - const alertsClient = context.alerting?.getAlertsClient(); - if (!alertsClient) { + const rulesClient = context.alerting?.getRulesClient(); + if (!rulesClient) { return response.ok({ body: undefined }); } const status = await fetchStatus( - alertsClient, + rulesClient, npRoute.licenseService, alertTypeIds, [clusterUuid], diff --git a/x-pack/plugins/monitoring/server/types.ts b/x-pack/plugins/monitoring/server/types.ts index b920f2bfacf80..07e56f0c00232 100644 --- a/x-pack/plugins/monitoring/server/types.ts +++ b/x-pack/plugins/monitoring/server/types.ts @@ -115,7 +115,7 @@ export interface LegacyRequest { getKibanaStatsCollector: () => any; getUiSettingsService: () => any; getActionTypeRegistry: () => any; - getAlertsClient: () => any; + getRulesClient: () => any; getActionsClient: () => any; server: LegacyServer; } diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/install_prepackaged_rules.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/install_prepackaged_rules.ts index a387b7e3fdca5..dd51c8b85d2b2 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/install_prepackaged_rules.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/install_prepackaged_rules.ts @@ -67,7 +67,7 @@ export const installPrepackagedRules = async ({ // @ts-expect-error context, appClient, - alerts.getAlertsClientWithRequest(request), + alerts.getRulesClientWithRequest(request), frameworkRequest, maxTimelineImportExportSize, exceptionsClient diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.test.ts index f9244add61651..33721c055cb89 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.test.ts @@ -5,21 +5,21 @@ * 2.0. */ -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { createNotifications } from './create_notifications'; describe('createNotifications', () => { - let alertsClient: ReturnType; + let rulesClient: ReturnType; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); }); - it('calls the alertsClient with proper params', async () => { + it('calls the rulesClient with proper params', async () => { const ruleAlertId = 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd'; await createNotifications({ - alertsClient, + rulesClient, actions: [], ruleAlertId, enabled: true, @@ -27,7 +27,7 @@ describe('createNotifications', () => { name: '', }); - expect(alertsClient.create).toHaveBeenCalledWith( + expect(rulesClient.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -38,7 +38,7 @@ describe('createNotifications', () => { ); }); - it('calls the alertsClient with transformed actions', async () => { + it('calls the rulesClient with transformed actions', async () => { const action = { group: 'default', id: '99403909-ca9b-49ba-9d7a-7e5320e68d05', @@ -46,7 +46,7 @@ describe('createNotifications', () => { action_type_id: '.slack', }; await createNotifications({ - alertsClient, + rulesClient, actions: [action], ruleAlertId: 'new-rule-id', enabled: true, @@ -54,7 +54,7 @@ describe('createNotifications', () => { name: '', }); - expect(alertsClient.create).toHaveBeenCalledWith( + expect(rulesClient.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: expect.arrayContaining([ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts index c445c33566289..907976062b519 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts @@ -12,14 +12,14 @@ import { addTags } from './add_tags'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; export const createNotifications = async ({ - alertsClient, + rulesClient, actions, enabled, ruleAlertId, interval, name, }: CreateNotificationParams): Promise> => - alertsClient.create({ + rulesClient.create({ data: { name, tags: addTags([], ruleAlertId), diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.test.ts index d277f04fb4826..9cd01df6bcdf3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.test.ts @@ -5,25 +5,25 @@ * 2.0. */ -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { deleteNotifications } from './delete_notifications'; import { readNotifications } from './read_notifications'; jest.mock('./read_notifications'); describe('deleteNotifications', () => { - let alertsClient: ReturnType; + let rulesClient: ReturnType; const notificationId = 'notification-52128c15-0d1b-4716-a4c5-46997ac7f3bd'; const ruleAlertId = 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd'; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); }); it('should return null if notification was not found', async () => { (readNotifications as jest.Mock).mockResolvedValue(null); const result = await deleteNotifications({ - alertsClient, + rulesClient, id: notificationId, ruleAlertId, }); @@ -31,18 +31,18 @@ describe('deleteNotifications', () => { expect(result).toBe(null); }); - it('should call alertsClient.delete if notification was found', async () => { + it('should call rulesClient.delete if notification was found', async () => { (readNotifications as jest.Mock).mockResolvedValue({ id: notificationId, }); const result = await deleteNotifications({ - alertsClient, + rulesClient, id: notificationId, ruleAlertId, }); - expect(alertsClient.delete).toHaveBeenCalledWith( + expect(rulesClient.delete).toHaveBeenCalledWith( expect.objectContaining({ id: notificationId, }) @@ -50,18 +50,18 @@ describe('deleteNotifications', () => { expect(result).toEqual({ id: notificationId }); }); - it('should call alertsClient.delete if notification.id was null', async () => { + it('should call rulesClient.delete if notification.id was null', async () => { (readNotifications as jest.Mock).mockResolvedValue({ id: null, }); const result = await deleteNotifications({ - alertsClient, + rulesClient, id: notificationId, ruleAlertId, }); - expect(alertsClient.delete).toHaveBeenCalledWith( + expect(rulesClient.delete).toHaveBeenCalledWith( expect.objectContaining({ id: notificationId, }) @@ -69,24 +69,24 @@ describe('deleteNotifications', () => { expect(result).toEqual({ id: null }); }); - it('should return null if alertsClient.delete rejects with 404 if notification.id was null', async () => { + it('should return null if rulesClient.delete rejects with 404 if notification.id was null', async () => { (readNotifications as jest.Mock).mockResolvedValue({ id: null, }); - alertsClient.delete.mockRejectedValue({ + rulesClient.delete.mockRejectedValue({ output: { statusCode: 404, }, }); const result = await deleteNotifications({ - alertsClient, + rulesClient, id: notificationId, ruleAlertId, }); - expect(alertsClient.delete).toHaveBeenCalledWith( + expect(rulesClient.delete).toHaveBeenCalledWith( expect.objectContaining({ id: notificationId, }) @@ -94,7 +94,7 @@ describe('deleteNotifications', () => { expect(result).toEqual(null); }); - it('should return error object if alertsClient.delete rejects with status different than 404 and if notification.id was null', async () => { + it('should return error object if rulesClient.delete rejects with status different than 404 and if notification.id was null', async () => { (readNotifications as jest.Mock).mockResolvedValue({ id: null, }); @@ -105,12 +105,12 @@ describe('deleteNotifications', () => { }, }; - alertsClient.delete.mockRejectedValue(errorObject); + rulesClient.delete.mockRejectedValue(errorObject); let errorResult; try { await deleteNotifications({ - alertsClient, + rulesClient, id: notificationId, ruleAlertId, }); @@ -118,7 +118,7 @@ describe('deleteNotifications', () => { errorResult = error; } - expect(alertsClient.delete).toHaveBeenCalledWith( + expect(rulesClient.delete).toHaveBeenCalledWith( expect.objectContaining({ id: notificationId, }) @@ -132,7 +132,7 @@ describe('deleteNotifications', () => { }); const result = await deleteNotifications({ - alertsClient, + rulesClient, id: undefined, ruleAlertId, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.ts index 09dc0044db02f..cf6812b7cacdc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/delete_notifications.ts @@ -9,21 +9,21 @@ import { readNotifications } from './read_notifications'; import { DeleteNotificationParams } from './types'; export const deleteNotifications = async ({ - alertsClient, + rulesClient, id, ruleAlertId, }: DeleteNotificationParams) => { - const notification = await readNotifications({ alertsClient, id, ruleAlertId }); + const notification = await readNotifications({ rulesClient, id, ruleAlertId }); if (notification == null) { return null; } if (notification.id != null) { - await alertsClient.delete({ id: notification.id }); + await rulesClient.delete({ id: notification.id }); return notification; } else if (id != null) { try { - await alertsClient.delete({ id }); + await rulesClient.delete({ id }); return notification; } catch (err) { if (err.output.statusCode === 404) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/find_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/find_notifications.ts index 6f8b1de1d9325..1f3d4247a0ad9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/find_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/find_notifications.ts @@ -18,7 +18,7 @@ export const getFilter = (filter: string | null | undefined) => { }; export const findNotifications = async ({ - alertsClient, + rulesClient, perPage, page, fields, @@ -26,7 +26,7 @@ export const findNotifications = async ({ sortField, sortOrder, }: FindNotificationParams): Promise> => - alertsClient.find({ + rulesClient.find({ options: { fields, page, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.test.ts index 0ee09dd4074c8..0e87dc76bd1cf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.test.ts @@ -6,7 +6,7 @@ */ import { readNotifications } from './read_notifications'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getNotificationResult, getFindNotificationsResultWithSingleHit, @@ -23,18 +23,18 @@ class TestError extends Error { } describe('read_notifications', () => { - let alertsClient: ReturnType; + let rulesClient: ReturnType; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); }); describe('readNotifications', () => { - test('should return the output from alertsClient if id is set but ruleAlertId is undefined', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); + test('should return the output from rulesClient if id is set but ruleAlertId is undefined', async () => { + rulesClient.get.mockResolvedValue(getNotificationResult()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleAlertId: undefined, }); @@ -44,10 +44,10 @@ describe('read_notifications', () => { const result = getNotificationResult(); // @ts-expect-error delete result.alertTypeId; - alertsClient.get.mockResolvedValue(result); + rulesClient.get.mockResolvedValue(result); const rule = await readNotifications({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleAlertId: undefined, }); @@ -55,12 +55,12 @@ describe('read_notifications', () => { }); test('should return error if alerts client throws 404 error on get', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw new TestError(); }); const rule = await readNotifications({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleAlertId: undefined, }); @@ -68,12 +68,12 @@ describe('read_notifications', () => { }); test('should return error if alerts client throws error on get', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw new Error('Test error'); }); try { await readNotifications({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleAlertId: undefined, }); @@ -82,47 +82,47 @@ describe('read_notifications', () => { } }); - test('should return the output from alertsClient if id is set but ruleAlertId is null', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); + test('should return the output from rulesClient if id is set but ruleAlertId is null', async () => { + rulesClient.get.mockResolvedValue(getNotificationResult()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleAlertId: null, }); expect(rule).toEqual(getNotificationResult()); }); - test('should return the output from alertsClient if id is undefined but ruleAlertId is set', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); - alertsClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); + test('should return the output from rulesClient if id is undefined but ruleAlertId is set', async () => { + rulesClient.get.mockResolvedValue(getNotificationResult()); + rulesClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: undefined, ruleAlertId: 'rule-1', }); expect(rule).toEqual(getNotificationResult()); }); - test('should return null if the output from alertsClient with ruleAlertId set is empty', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); - alertsClient.find.mockResolvedValue({ data: [], page: 0, perPage: 1, total: 0 }); + test('should return null if the output from rulesClient with ruleAlertId set is empty', async () => { + rulesClient.get.mockResolvedValue(getNotificationResult()); + rulesClient.find.mockResolvedValue({ data: [], page: 0, perPage: 1, total: 0 }); const rule = await readNotifications({ - alertsClient, + rulesClient, id: undefined, ruleAlertId: 'rule-1', }); expect(rule).toEqual(null); }); - test('should return the output from alertsClient if id is null but ruleAlertId is set', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); - alertsClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); + test('should return the output from rulesClient if id is null but ruleAlertId is set', async () => { + rulesClient.get.mockResolvedValue(getNotificationResult()); + rulesClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: null, ruleAlertId: 'rule-1', }); @@ -130,11 +130,11 @@ describe('read_notifications', () => { }); test('should return null if id and ruleAlertId are null', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); - alertsClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); + rulesClient.get.mockResolvedValue(getNotificationResult()); + rulesClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: null, ruleAlertId: null, }); @@ -142,11 +142,11 @@ describe('read_notifications', () => { }); test('should return null if id and ruleAlertId are undefined', async () => { - alertsClient.get.mockResolvedValue(getNotificationResult()); - alertsClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); + rulesClient.get.mockResolvedValue(getNotificationResult()); + rulesClient.find.mockResolvedValue(getFindNotificationsResultWithSingleHit()); const rule = await readNotifications({ - alertsClient, + rulesClient, id: undefined, ruleAlertId: undefined, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.ts index 2f14f36fc5e0a..a31281821d2d7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/read_notifications.ts @@ -11,13 +11,13 @@ import { findNotifications } from './find_notifications'; import { INTERNAL_RULE_ALERT_ID_KEY } from '../../../../common/constants'; export const readNotifications = async ({ - alertsClient, + rulesClient, id, ruleAlertId, }: ReadNotificationParams): Promise | null> => { if (id != null) { try { - const notification = await alertsClient.get({ id }); + const notification = await rulesClient.get({ id }); if (isAlertType(notification)) { return notification; } else { @@ -33,7 +33,7 @@ export const readNotifications = async ({ } } else if (ruleAlertId != null) { const notificationFromFind = await findNotifications({ - alertsClient, + rulesClient, filter: `alert.attributes.tags: "${INTERNAL_RULE_ALERT_ID_KEY}:${ruleAlertId}"`, page: 1, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/types.ts index 0a32e0c21a075..aae5d2c6c616a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/types.ts @@ -6,7 +6,7 @@ */ import { - AlertsClient, + RulesClient, PartialAlert, AlertType, AlertTypeParams, @@ -25,7 +25,7 @@ export interface RuleNotificationAlertTypeParams extends AlertTypeParams { export type RuleNotificationAlertType = Alert; export interface FindNotificationParams { - alertsClient: AlertsClient; + rulesClient: RulesClient; perPage?: number; page?: number; sortField?: string; @@ -45,7 +45,7 @@ export interface FindNotificationsRequestParams { } export interface Clients { - alertsClient: AlertsClient; + rulesClient: RulesClient; } export type UpdateNotificationParams = Omit< @@ -73,7 +73,7 @@ export interface NotificationAlertParams { export type CreateNotificationParams = NotificationAlertParams & Clients; export interface ReadNotificationParams { - alertsClient: AlertsClient; + rulesClient: RulesClient; id?: string | null; ruleAlertId?: string | null; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.test.ts index 0d4af8cd029a0..a2a858b552c0d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { updateNotifications } from './update_notifications'; import { readNotifications } from './read_notifications'; import { createNotifications } from './create_notifications'; @@ -16,17 +16,17 @@ jest.mock('./create_notifications'); describe('updateNotifications', () => { const notification = getNotificationResult(); - let alertsClient: ReturnType; + let rulesClient: ReturnType; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); }); it('should update the existing notification if interval provided', async () => { (readNotifications as jest.Mock).mockResolvedValue(notification); await updateNotifications({ - alertsClient, + rulesClient, actions: [], ruleAlertId: 'new-rule-id', enabled: true, @@ -34,7 +34,7 @@ describe('updateNotifications', () => { name: '', }); - expect(alertsClient.update).toHaveBeenCalledWith( + expect(rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ id: notification.id, data: expect.objectContaining({ @@ -50,7 +50,7 @@ describe('updateNotifications', () => { (readNotifications as jest.Mock).mockResolvedValue(null); const params: UpdateNotificationParams = { - alertsClient, + rulesClient, actions: [], ruleAlertId: 'new-rule-id', enabled: true, @@ -67,7 +67,7 @@ describe('updateNotifications', () => { (readNotifications as jest.Mock).mockResolvedValue(notification); await updateNotifications({ - alertsClient, + rulesClient, actions: [], ruleAlertId: 'new-rule-id', enabled: true, @@ -75,14 +75,14 @@ describe('updateNotifications', () => { name: '', }); - expect(alertsClient.delete).toHaveBeenCalledWith( + expect(rulesClient.delete).toHaveBeenCalledWith( expect.objectContaining({ id: notification.id, }) ); }); - it('should call the alertsClient with transformed actions', async () => { + it('should call the rulesClient with transformed actions', async () => { (readNotifications as jest.Mock).mockResolvedValue(notification); const action = { group: 'default', @@ -91,7 +91,7 @@ describe('updateNotifications', () => { action_type_id: '.slack', }; await updateNotifications({ - alertsClient, + rulesClient, actions: [action], ruleAlertId: 'new-rule-id', enabled: true, @@ -99,7 +99,7 @@ describe('updateNotifications', () => { name: '', }); - expect(alertsClient.update).toHaveBeenCalledWith( + expect(rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: expect.arrayContaining([ @@ -120,7 +120,7 @@ describe('updateNotifications', () => { const ruleAlertId = 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd'; const result = await updateNotifications({ - alertsClient, + rulesClient, actions: [], enabled: true, ruleAlertId, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.ts index 40c2845abb607..a568bfbc608e4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/update_notifications.ts @@ -13,17 +13,17 @@ import { createNotifications } from './create_notifications'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; export const updateNotifications = async ({ - alertsClient, + rulesClient, actions, enabled, ruleAlertId, name, interval, }: UpdateNotificationParams): Promise | null> => { - const notification = await readNotifications({ alertsClient, id: undefined, ruleAlertId }); + const notification = await readNotifications({ rulesClient, id: undefined, ruleAlertId }); if (interval && notification) { - return alertsClient.update({ + return rulesClient.update({ id: notification.id, data: { tags: addTags([], ruleAlertId), @@ -41,7 +41,7 @@ export const updateNotifications = async ({ }); } else if (interval && !notification) { return createNotifications({ - alertsClient, + rulesClient, enabled, name, interval, @@ -49,7 +49,7 @@ export const updateNotifications = async ({ ruleAlertId, }); } else if (!interval && notification) { - await alertsClient.delete({ id: notification.id }); + await rulesClient.delete({ id: notification.id }); return null; } else { return null; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts index 533b3f86728f1..c3621eeba547c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts @@ -11,12 +11,12 @@ import { elasticsearchServiceMock, savedObjectsClientMock, } from '../../../../../../../../src/core/server/mocks'; -import { alertsClientMock } from '../../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../../alerting/server/mocks'; import { licensingMock } from '../../../../../../licensing/server/mocks'; import { siemMock } from '../../../../mocks'; const createMockClients = () => ({ - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), clusterClient: elasticsearchServiceMock.createLegacyScopedClusterClient(), licensing: { license: licensingMock.createLicenseMock() }, newClusterClient: elasticsearchServiceMock.createScopedClusterClient(), @@ -29,7 +29,7 @@ const createRequestContextMock = ( ) => { const coreContext = coreMock.createRequestHandlerContext(); return ({ - alerting: { getAlertsClient: jest.fn(() => clients.alertsClient) }, + alerting: { getRulesClient: jest.fn(() => clients.rulesClient) }, core: { ...coreContext, elasticsearch: { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts index 026820a8f2ff7..d689b76ab9dbd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts @@ -91,7 +91,7 @@ describe('add_prepackaged_rules_route', () => { mockExceptionsClient = listMock.getExceptionListClient(); clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); (installPrepackagedTimelines as jest.Mock).mockReset(); (installPrepackagedTimelines as jest.Mock).mockResolvedValue({ @@ -118,7 +118,7 @@ describe('add_prepackaged_rules_route', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const request = addPrepackagedRulesRequest(); const response = await server.inject(request, context); @@ -160,7 +160,7 @@ describe('add_prepackaged_rules_route', () => { describe('responses', () => { test('1 rule is installed and 0 are updated when find results are empty', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const request = addPrepackagedRulesRequest(); const response = await server.inject(request, context); @@ -301,7 +301,7 @@ describe('add_prepackaged_rules_route', () => { await createPrepackagedRules( context, siemMockClient, - clients.alertsClient, + clients.rulesClient, {} as FrameworkRequest, 1200, mockExceptionsClient @@ -317,7 +317,7 @@ describe('add_prepackaged_rules_route', () => { await createPrepackagedRules( myContext, siemMockClient, - clients.alertsClient, + clients.rulesClient, {} as FrameworkRequest, 1200, mockExceptionsClient diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 03d357ab10bb9..c2706c1d01550 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -34,7 +34,7 @@ import { getExistingPrepackagedRules } from '../../rules/get_existing_prepackage import { ruleAssetSavedObjectsClientFactory } from '../../rules/rule_asset_saved_objects_client'; import { buildSiemResponse } from '../utils'; -import { AlertsClient } from '../../../../../../alerting/server'; +import { RulesClient } from '../../../../../../alerting/server'; import { FrameworkRequest } from '../../../framework'; import { ExceptionListClient } from '../../../../../../lists/server'; @@ -65,17 +65,17 @@ export const addPrepackedRulesRoute = ( const frameworkRequest = await buildFrameworkRequest(context, security, _); try { - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const siemClient = context.securitySolution?.getAppClient(); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } const validated = await createPrepackagedRules( context, siemClient, - alertsClient, + rulesClient, frameworkRequest, config.maxTimelineImportExportSize ); @@ -102,7 +102,7 @@ class PrepackagedRulesError extends Error { export const createPrepackagedRules = async ( context: SecuritySolutionRequestHandlerContext, siemClient: AppClient, - alertsClient: AlertsClient, + rulesClient: RulesClient, frameworkRequest: FrameworkRequest, maxTimelineImportExportSize: number, exceptionsClient?: ExceptionListClient @@ -112,7 +112,7 @@ export const createPrepackagedRules = async ( const exceptionsListClient = context.lists != null ? context.lists.getExceptionListClient() : exceptionsClient; const ruleAssetsClient = ruleAssetSavedObjectsClientFactory(savedObjectsClient); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { throw new PrepackagedRulesError('', 404); } @@ -122,7 +122,7 @@ export const createPrepackagedRules = async ( } const latestPrepackagedRules = await getLatestPrepackagedRules(ruleAssetsClient); - const prepackagedRules = await getExistingPrepackagedRules({ alertsClient }); + const prepackagedRules = await getExistingPrepackagedRules({ rulesClient }); const rulesToInstall = getRulesToInstall(latestPrepackagedRules, prepackagedRules); const rulesToUpdate = getRulesToUpdate(latestPrepackagedRules, prepackagedRules); const signalsIndex = siemClient.getSignalsIndex(); @@ -136,7 +136,7 @@ export const createPrepackagedRules = async ( } } - await Promise.all(installPrepackagedRules(alertsClient, rulesToInstall, signalsIndex)); + await Promise.all(installPrepackagedRules(rulesClient, rulesToInstall, signalsIndex)); const timeline = await installPrepackagedTimelines( maxTimelineImportExportSize, frameworkRequest, @@ -146,7 +146,7 @@ export const createPrepackagedRules = async ( timeline, importTimelineResultSchema ); - await updatePrepackagedRules(alertsClient, savedObjectsClient, rulesToUpdate, signalsIndex); + await updatePrepackagedRules(rulesClient, savedObjectsClient, rulesToUpdate, signalsIndex); const prepackagedRulesOutput: PrePackagedRulesAndTimelinesSchema = { rules_installed: rulesToInstall.length, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts index 311e2fcc41a0b..8091180f44540 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts @@ -36,8 +36,8 @@ describe('create_rules_bulk', () => { ml = mlServicesMock.createSetupContract(); clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); // index exists - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); // no existing rules - clients.alertsClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful creation + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); // no existing rules + clients.rulesClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful creation // eslint-disable-next-line @typescript-eslint/no-explicit-any (context.core.elasticsearch.client.asCurrentUser.search as any).mockResolvedValue( @@ -53,7 +53,7 @@ describe('create_rules_bulk', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getReadBulkRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); @@ -109,7 +109,7 @@ describe('create_rules_bulk', () => { }); test('returns a duplicate error if rule_id already exists', async () => { - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const response = await server.inject(getReadBulkRequest(), context); expect(response.status).toEqual(200); @@ -124,7 +124,7 @@ describe('create_rules_bulk', () => { }); test('catches error if creation throws', async () => { - clients.alertsClient.create.mockImplementation(async () => { + clients.rulesClient.create.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getReadBulkRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts index 500c74e47ea7d..447da0f20a657 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts @@ -40,12 +40,12 @@ export const createRulesBulkRoute = ( }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const esClient = context.core.elasticsearch.client; const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -65,7 +65,7 @@ export const createRulesBulkRoute = ( .map(async (payloadRule) => { if (payloadRule.rule_id != null) { const rule = await readRules({ - alertsClient, + rulesClient, ruleId: payloadRule.rule_id, id: undefined, }); @@ -99,13 +99,13 @@ export const createRulesBulkRoute = ( }); } - const createdRule = await alertsClient.create({ + const createdRule = await rulesClient.create({ data: internalRule, }); const ruleActions = await updateRulesNotifications({ ruleAlertId: createdRule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: createdRule.enabled, actions: payloadRule.actions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts index b04f178363f99..c3dfcb3cf2694 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts @@ -38,8 +38,8 @@ describe('create_rules', () => { ml = mlServicesMock.createSetupContract(); clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); // index exists - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); // no current rules - clients.alertsClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); // creation succeeds + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); // no current rules + clients.rulesClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); // creation succeeds clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatus()); // needed to transform // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -62,7 +62,7 @@ describe('create_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getCreateRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); @@ -122,7 +122,7 @@ describe('create_rules', () => { }); test('returns a duplicate error if rule_id already exists', async () => { - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const response = await server.inject(getCreateRequest(), context); expect(response.status).toEqual(409); @@ -133,7 +133,7 @@ describe('create_rules', () => { }); test('catches error if creation throws', async () => { - clients.alertsClient.create.mockImplementation(async () => { + clients.rulesClient.create.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getCreateRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts index 993d9300e414f..46c144638e0ea 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -45,18 +45,18 @@ export const createRulesRoute = ( return siemResponse.error({ statusCode: 400, body: validationErrors }); } try { - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const esClient = context.core.elasticsearch.client; const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } if (request.body.rule_id != null) { const rule = await readRules({ - alertsClient, + rulesClient, ruleId: request.body.rule_id, id: undefined, }); @@ -92,13 +92,13 @@ export const createRulesRoute = ( // This will create the endpoint list if it does not exist yet await context.lists?.getExceptionListClient().createEndpointList(); - const createdRule = await alertsClient.create({ + const createdRule = await rulesClient.create({ data: internalRule, }); const ruleActions = await updateRulesNotifications({ ruleAlertId: createdRule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: createdRule.enabled, actions: request.body.actions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts index 9084557962ba0..d37b0f5a685af 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts @@ -27,8 +27,8 @@ describe('delete_rules', () => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists - clients.alertsClient.delete.mockResolvedValue({}); // successful deletion + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists + clients.rulesClient.delete.mockResolvedValue({}); // successful deletion clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatusEmpty()); // rule status request deleteRulesBulkRoute(server.router); @@ -62,13 +62,13 @@ describe('delete_rules', () => { }); test('returns 200 because the error is in the payload when deleting a single rule that does not exist with a valid actionClient and alertClient', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getDeleteBulkRequest(), context); expect(response.status).toEqual(200); }); test('returns 404 in the payload when deleting a single rule that does not exist with a valid actionClient and alertClient', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getDeleteBulkRequest(), context); expect(response.status).toEqual(200); @@ -83,7 +83,7 @@ describe('delete_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getDeleteBulkRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts index 3068521682f8f..403565debea08 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts @@ -50,10 +50,10 @@ export const deleteRulesBulkRoute = (router: SecuritySolutionPluginRouter) => { const handler: Handler = async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -73,7 +73,7 @@ export const deleteRulesBulkRoute = (router: SecuritySolutionPluginRouter) => { } try { - const rule = await readRules({ alertsClient, id, ruleId }); + const rule = await readRules({ rulesClient, id, ruleId }); if (!rule) { return getIdBulkError({ id, ruleId }); } @@ -84,7 +84,7 @@ export const deleteRulesBulkRoute = (router: SecuritySolutionPluginRouter) => { searchFields: ['alertId'], }); await deleteRules({ - alertsClient, + rulesClient, savedObjectsClient, ruleStatusClient, ruleStatuses, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts index e820487dc0c5d..b64b14dc8cd0c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts @@ -26,7 +26,7 @@ describe('delete_rules', () => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatus()); deleteRulesRoute(server.router); @@ -40,14 +40,14 @@ describe('delete_rules', () => { }); test('returns 200 when deleting a single rule with a valid actionClient and alertClient by id', async () => { - clients.alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + clients.rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); const response = await server.inject(getDeleteRequestById(), context); expect(response.status).toEqual(200); }); test('returns 404 when deleting a single rule that does not exist with a valid actionClient and alertClient', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getDeleteRequest(), context); expect(response.status).toEqual(404); @@ -58,7 +58,7 @@ describe('delete_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getDeleteRequest(), context); expect(response.status).toEqual(404); @@ -66,7 +66,7 @@ describe('delete_rules', () => { }); test('catches error if deletion throws error', async () => { - clients.alertsClient.delete.mockImplementation(async () => { + clients.rulesClient.delete.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getDeleteRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts index 4a6b41230f799..02c22750439f0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts @@ -48,15 +48,15 @@ export const deleteRulesRoute = ( try { const { id, rule_id: ruleId } = request.query; - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); - const rule = await readRules({ alertsClient, id, ruleId }); + const rule = await readRules({ rulesClient, id, ruleId }); if (!rule) { const error = getIdError({ id, ruleId }); return siemResponse.error({ @@ -71,7 +71,7 @@ export const deleteRulesRoute = ( searchFields: ['alertId'], }); await deleteRules({ - alertsClient, + rulesClient, savedObjectsClient, ruleStatusClient, ruleStatuses, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts index cb1c1feba5295..022118859aa0b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts @@ -39,9 +39,9 @@ export const exportRulesRoute = (router: SecuritySolutionPluginRouter, config: C }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -53,7 +53,7 @@ export const exportRulesRoute = (router: SecuritySolutionPluginRouter, config: C body: `Can't export more than ${exportSizeLimit} rules`, }); } else { - const nonPackagedRulesCount = await getNonPackagedRulesCount({ alertsClient }); + const nonPackagedRulesCount = await getNonPackagedRulesCount({ rulesClient }); if (nonPackagedRulesCount > exportSizeLimit) { return siemResponse.error({ statusCode: 400, @@ -64,8 +64,8 @@ export const exportRulesRoute = (router: SecuritySolutionPluginRouter, config: C const exported = request.body?.objects != null - ? await getExportByObjectIds(alertsClient, request.body.objects) - : await getExportAll(alertsClient); + ? await getExportByObjectIds(rulesClient, request.body.objects) + : await getExportAll(rulesClient); const responseBody = request.query.exclude_export_details ? exported.rulesNdjson diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts index 06f3ca83c4722..ed92c045ade29 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts @@ -25,8 +25,8 @@ describe('find_rules', () => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - clients.alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); clients.savedObjectsClient.find.mockResolvedValue(getFindBulkResultStatus()); findRulesRoute(server.router); @@ -39,14 +39,14 @@ describe('find_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getFindRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); test('catches error if search throws error', async () => { - clients.alertsClient.find.mockImplementation(async () => { + clients.rulesClient.find.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getFindRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts index 428978fe1d820..32f18d816bacf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -46,16 +46,16 @@ export const findRulesRoute = ( try { const { query } = request; - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); const rules = await findRules({ - alertsClient, + rulesClient, perPage: query.per_page, page: query.page, sortField: query.sort_field, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts index 73f076649b72f..43e60b0eb5035 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts @@ -27,18 +27,18 @@ describe('find_statuses', () => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); clients.savedObjectsClient.find.mockResolvedValue(getFindBulkResultStatus()); // successful status search - clients.alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + clients.rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); findRulesStatusesRoute(server.router); }); describe('status codes with actionClient and alertClient', () => { - test('returns 200 when finding a single rule status with a valid alertsClient', async () => { + test('returns 200 when finding a single rule status with a valid rulesClient', async () => { const response = await server.inject(ruleStatusRequest(), context); expect(response.status).toEqual(200); }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(ruleStatusRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); @@ -70,7 +70,7 @@ describe('find_statuses', () => { }; // 1. getFailingRules api found a rule where the executionStatus was 'error' - clients.alertsClient.get.mockResolvedValue({ + clients.rulesClient.get.mockResolvedValue({ ...failingExecutionRule, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts index aed8b80e4f133..1760d6bf7c18b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts @@ -40,10 +40,10 @@ export const findRulesStatusesRoute = (router: SecuritySolutionPluginRouter) => async (context, request, response) => { const { body } = request; const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -52,7 +52,7 @@ export const findRulesStatusesRoute = (router: SecuritySolutionPluginRouter) => const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); const [statusesById, failingRules] = await Promise.all([ ruleStatusClient.findBulk(ids, 6), - getFailingRules(ids, alertsClient), + getFailingRules(ids, rulesClient), ]); const statuses = ids.reduce((acc, id) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts index 3c8321ee8eb9a..2091661cebecb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts @@ -75,7 +75,7 @@ describe('get_prepackaged_rule_status_route', () => { } as unknown) as SecurityPluginSetup; clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); getPrepackagedRulesStatusRoute(server.router, createMockConfig(), securitySetup); }); @@ -87,14 +87,14 @@ describe('get_prepackaged_rule_status_route', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getPrepackagedRulesStatusRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); test('catch error when finding rules throws error', async () => { - clients.alertsClient.find.mockImplementation(async () => { + clients.rulesClient.find.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getPrepackagedRulesStatusRequest(), context); @@ -108,7 +108,7 @@ describe('get_prepackaged_rule_status_route', () => { describe('responses', () => { test('0 rules installed, 0 custom rules, 1 rules not installed, and 1 rule not updated', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const request = getPrepackagedRulesStatusRequest(); const response = await server.inject(request, context); @@ -125,7 +125,7 @@ describe('get_prepackaged_rule_status_route', () => { }); test('1 rule installed, 1 custom rules, 0 rules not installed, and 1 rule to not updated', async () => { - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const request = getPrepackagedRulesStatusRequest(); const response = await server.inject(request, context); @@ -142,7 +142,7 @@ describe('get_prepackaged_rule_status_route', () => { }); test('0 timelines installed, 3 timelines not installed, 0 timelines not updated', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); (checkTimelinesStatus as jest.Mock).mockResolvedValue( mockCheckTimelinesStatusBeforeInstallResult ); @@ -162,7 +162,7 @@ describe('get_prepackaged_rule_status_route', () => { }); test('3 timelines installed, 0 timelines not installed, 0 timelines not updated', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); (checkTimelinesStatus as jest.Mock).mockResolvedValue( mockCheckTimelinesStatusAfterInstallResult ); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts index cd02cc72ba40c..4e498d4e3f228 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts @@ -45,17 +45,17 @@ export const getPrepackagedRulesStatusRoute = ( async (context, request, response) => { const savedObjectsClient = context.core.savedObjects.client; const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const ruleAssetsClient = ruleAssetSavedObjectsClientFactory(savedObjectsClient); - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } try { const latestPrepackagedRules = await getLatestPrepackagedRules(ruleAssetsClient); const customRules = await findRules({ - alertsClient, + rulesClient, perPage: 1, page: 1, sortField: 'enabled', @@ -64,7 +64,7 @@ export const getPrepackagedRulesStatusRoute = ( fields: undefined, }); const frameworkRequest = await buildFrameworkRequest(context, security, request); - const prepackagedRules = await getExistingPrepackagedRules({ alertsClient }); + const prepackagedRules = await getExistingPrepackagedRules({ rulesClient }); const rulesToInstall = getRulesToInstall(latestPrepackagedRules, prepackagedRules); const rulesToUpdate = getRulesToUpdate(latestPrepackagedRules, prepackagedRules); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts index 0a680d1b0d1c1..53f1a43119eb9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts @@ -46,7 +46,7 @@ describe('import_rules_route', () => { ml = mlServicesMock.createSetupContract(); clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); // index exists - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); // no extant rules + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); // no extant rules // eslint-disable-next-line @typescript-eslint/no-explicit-any (context.core.elasticsearch.client.asCurrentUser.search as any).mockResolvedValue( @@ -75,7 +75,7 @@ describe('import_rules_route', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(request, context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); @@ -171,7 +171,7 @@ describe('import_rules_route', () => { describe('single rule import', () => { test('returns 200 if rule imported successfully', async () => { - clients.alertsClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); + clients.rulesClient.create.mockResolvedValue(getAlertMock(getQueryRuleParams())); const response = await server.inject(request, context); expect(response.status).toEqual(200); expect(response.body).toEqual({ @@ -204,7 +204,7 @@ describe('import_rules_route', () => { describe('rule with existing rule_id', () => { test('returns with reported conflict if `overwrite` is set to `false`', async () => { - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // extant rule + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // extant rule const response = await server.inject(request, context); expect(response.status).toEqual(200); @@ -224,7 +224,7 @@ describe('import_rules_route', () => { }); test('returns with NO reported conflict if `overwrite` is set to `true`', async () => { - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // extant rule + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // extant rule const overwriteRequest = getImportRulesRequestOverwriteTrue( buildHapiStream(ruleIdsToNdJsonString(['rule-1'])) ); @@ -344,7 +344,7 @@ describe('import_rules_route', () => { describe('rules with existing rule_id', () => { beforeEach(() => { - clients.alertsClient.find.mockResolvedValueOnce(getFindResultWithSingleHit()); // extant rule + clients.rulesClient.find.mockResolvedValueOnce(getFindResultWithSingleHit()); // extant rule }); test('returns with reported conflict if `overwrite` is set to `false`', async () => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts index 8e322405280d3..b4a7fc4ac554f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts @@ -76,12 +76,12 @@ export const importRulesRoute = ( const siemResponse = buildSiemResponse(response); try { - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const esClient = context.core.elasticsearch.client; const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -200,10 +200,10 @@ export const importRulesRoute = ( throwHttpError(await mlAuthz.validateRuleType(type)); - const rule = await readRules({ alertsClient, ruleId, id: undefined }); + const rule = await readRules({ rulesClient, ruleId, id: undefined }); if (rule == null) { await createRules({ - alertsClient, + rulesClient, anomalyThreshold, author, buildingBlockType, @@ -256,7 +256,7 @@ export const importRulesRoute = ( resolve({ rule_id: ruleId, status_code: 200 }); } else if (rule != null && request.query.overwrite) { await patchRules({ - alertsClient, + rulesClient, author, buildingBlockType, savedObjectsClient, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts index b6dd8a3fe0431..31f805c563f76 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts @@ -32,8 +32,8 @@ describe('patch_rules_bulk', () => { ({ clients, context } = requestContextMock.createTools()); ml = mlServicesMock.createSetupContract(); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists - clients.alertsClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // update succeeds + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists + clients.rulesClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // update succeeds patchRulesBulkRoute(server.router, ml); }); @@ -45,7 +45,7 @@ describe('patch_rules_bulk', () => { }); test('returns an error in the response when updating a single rule that does not exist', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getPatchBulkRequest(), context); expect(response.status).toEqual(200); expect(response.body).toEqual([ @@ -71,7 +71,7 @@ describe('patch_rules_bulk', () => { }); await server.inject(request, context); - expect(clients.alertsClient.update).toHaveBeenCalledWith( + expect(clients.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -84,7 +84,7 @@ describe('patch_rules_bulk', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getPatchBulkRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts index 7eb01e8b0d402..6def864885dcd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts @@ -46,10 +46,10 @@ export const patchRulesBulkRoute = ( async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -123,7 +123,7 @@ export const patchRulesBulkRoute = ( throwHttpError(await mlAuthz.validateRuleType(type)); } - const existingRule = await readRules({ alertsClient, ruleId, id }); + const existingRule = await readRules({ rulesClient, ruleId, id }); if (existingRule?.params.type) { // reject an unauthorized modification of an ML rule throwHttpError(await mlAuthz.validateRuleType(existingRule?.params.type)); @@ -131,7 +131,7 @@ export const patchRulesBulkRoute = ( const rule = await patchRules({ rule: existingRule, - alertsClient, + rulesClient, author, buildingBlockType, description, @@ -182,7 +182,7 @@ export const patchRulesBulkRoute = ( if (rule != null && rule.enabled != null && rule.name != null) { const ruleActions = await updateRulesNotifications({ ruleAlertId: rule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: rule.enabled, actions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts index 9920ec5229a02..840763661f0bc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts @@ -34,9 +34,9 @@ describe('patch_rules', () => { ({ clients, context } = requestContextMock.createTools()); ml = mlServicesMock.createSetupContract(); - clients.alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); // existing rule - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // existing rule - clients.alertsClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful update + clients.rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); // existing rule + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // existing rule + clients.rulesClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful update clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatus()); // successful transform patchRulesRoute(server.router, ml); @@ -49,7 +49,7 @@ describe('patch_rules', () => { }); test('returns 404 when updating a single rule that does not exist', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getPatchRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ @@ -59,14 +59,14 @@ describe('patch_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getPatchRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); test('returns error if requesting a non-rule', async () => { - clients.alertsClient.find.mockResolvedValue(nonRuleFindResult()); + clients.rulesClient.find.mockResolvedValue(nonRuleFindResult()); const response = await server.inject(getPatchRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ @@ -76,7 +76,7 @@ describe('patch_rules', () => { }); test('catches error if update throws error', async () => { - clients.alertsClient.update.mockImplementation(async () => { + clients.rulesClient.update.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getPatchRequest(), context); @@ -100,7 +100,7 @@ describe('patch_rules', () => { }); await server.inject(request, context); - expect(clients.alertsClient.update).toHaveBeenCalledWith( + expect(clients.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts index eaaa44fcf1916..c6123a5ac53c8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts @@ -107,10 +107,10 @@ export const patchRulesRoute = ( const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -125,7 +125,7 @@ export const patchRulesRoute = ( throwHttpError(await mlAuthz.validateRuleType(type)); } - const existingRule = await readRules({ alertsClient, ruleId, id }); + const existingRule = await readRules({ rulesClient, ruleId, id }); if (existingRule?.params.type) { // reject an unauthorized modification of an ML rule throwHttpError(await mlAuthz.validateRuleType(existingRule?.params.type)); @@ -133,7 +133,7 @@ export const patchRulesRoute = ( const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); const rule = await patchRules({ - alertsClient, + rulesClient, author, buildingBlockType, description, @@ -185,7 +185,7 @@ export const patchRulesRoute = ( if (rule != null && rule.enabled != null && rule.name != null) { const ruleActions = await updateRulesNotifications({ ruleAlertId: rule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: rule.enabled, actions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.test.ts index 60677fd8eda90..1facd291eede4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.test.ts @@ -31,7 +31,7 @@ describe('perform_bulk_action', () => { ({ clients, context } = requestContextMock.createTools()); ml = mlServicesMock.createSetupContract(); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatus()); performBulkActionRoute(server.router, ml); @@ -45,14 +45,14 @@ describe('perform_bulk_action', () => { }); it("returns 200 when provided filter query doesn't match any rules", async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getBulkActionRequest(), context); expect(response.status).toEqual(200); expect(response.body).toEqual({ success: true, rules_count: 0 }); }); it('returns 400 when provided filter query matches too many rules', async () => { - clients.alertsClient.find.mockResolvedValue( + clients.rulesClient.find.mockResolvedValue( getFindResultWithMultiHits({ data: [], total: Infinity }) ); const response = await server.inject(getBulkActionRequest(), context); @@ -64,14 +64,14 @@ describe('perform_bulk_action', () => { }); it('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getBulkActionRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); it('catches error if disable throws error', async () => { - clients.alertsClient.disable.mockImplementation(async () => { + clients.rulesClient.disable.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getBulkActionRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.ts index 9d569acf3782a..ab6fc24c5fa76 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/perform_bulk_action_route.ts @@ -45,7 +45,7 @@ export const performBulkActionRoute = ( const siemResponse = buildSiemResponse(response); try { - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); @@ -56,12 +56,12 @@ export const performBulkActionRoute = ( savedObjectsClient, }); - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } const rules = await findRules({ - alertsClient, + rulesClient, perPage: BULK_ACTION_RULES_LIMIT, filter: body.query !== '' ? body.query : undefined, page: undefined, @@ -83,7 +83,7 @@ export const performBulkActionRoute = ( rules.data.map(async (rule) => { if (!rule.enabled) { throwHttpError(await mlAuthz.validateRuleType(rule.params.type)); - await enableRule({ rule, alertsClient, savedObjectsClient }); + await enableRule({ rule, rulesClient, savedObjectsClient }); } }) ); @@ -93,7 +93,7 @@ export const performBulkActionRoute = ( rules.data.map(async (rule) => { if (rule.enabled) { throwHttpError(await mlAuthz.validateRuleType(rule.params.type)); - await alertsClient.disable({ id: rule.id }); + await rulesClient.disable({ id: rule.id }); } }) ); @@ -107,7 +107,7 @@ export const performBulkActionRoute = ( searchFields: ['alertId'], }); await deleteRules({ - alertsClient, + rulesClient, savedObjectsClient, ruleStatusClient, ruleStatuses, @@ -121,7 +121,7 @@ export const performBulkActionRoute = ( rules.data.map(async (rule) => { throwHttpError(await mlAuthz.validateRuleType(rule.params.type)); - const createdRule = await alertsClient.create({ + const createdRule = await rulesClient.create({ data: duplicateRule(rule), }); @@ -132,7 +132,7 @@ export const performBulkActionRoute = ( await updateRulesNotifications({ ruleAlertId: createdRule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: createdRule.enabled, actions: ruleActions?.actions || [], @@ -144,7 +144,7 @@ export const performBulkActionRoute = ( break; case BulkAction.export: const exported = await getExportByObjectIds( - alertsClient, + rulesClient, rules.data.map(({ params }) => ({ rule_id: params.ruleId })) ); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.test.ts index bc3c282c9cdde..11043273eaef0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.test.ts @@ -24,7 +24,7 @@ describe('read_signals', () => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatusEmpty()); // successful transform readRulesRoute(server.router); @@ -37,14 +37,14 @@ describe('read_signals', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getReadRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); test('returns error if requesting a non-rule', async () => { - clients.alertsClient.find.mockResolvedValue(nonRuleFindResult()); + clients.rulesClient.find.mockResolvedValue(nonRuleFindResult()); const response = await server.inject(getReadRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ @@ -54,7 +54,7 @@ describe('read_signals', () => { }); test('catches error if search throws error', async () => { - clients.alertsClient.find.mockImplementation(async () => { + clients.rulesClient.find.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getReadRequest(), context); @@ -68,7 +68,7 @@ describe('read_signals', () => { describe('data validation', () => { test('returns 404 if given a non-existent id', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const request = requestMock.create({ method: 'get', path: DETECTION_ENGINE_RULES_URL, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts index 917da6c9708d5..ab618dc2a30e8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts @@ -47,17 +47,17 @@ export const readRulesRoute = ( const { id, rule_id: ruleId } = request.query; - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; try { - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); const rule = await readRules({ - alertsClient, + rulesClient, id, ruleId, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts index a57bed7a895f9..7851920adc1d9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts @@ -34,8 +34,8 @@ describe('update_rules_bulk', () => { ({ clients, context } = requestContextMock.createTools()); ml = mlServicesMock.createSetupContract(); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - clients.alertsClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatus()); updateRulesBulkRoute(server.router, ml); @@ -48,7 +48,7 @@ describe('update_rules_bulk', () => { }); test('returns 200 as a response when updating a single rule that does not exist', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const expected: BulkError[] = [ { error: { message: 'rule_id: "rule-1" not found', status_code: 404 }, @@ -62,7 +62,7 @@ describe('update_rules_bulk', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getUpdateBulkRequest(), context); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); @@ -77,7 +77,7 @@ describe('update_rules_bulk', () => { }); test('returns an error if update throws', async () => { - clients.alertsClient.update.mockImplementation(() => { + clients.rulesClient.update.mockImplementation(() => { throw new Error('Test error'); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts index 4c59ae2ba442e..f7604ebcdc22f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts @@ -39,11 +39,11 @@ export const updateRulesBulkRoute = ( async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -71,7 +71,7 @@ export const updateRulesBulkRoute = ( throwHttpError(await mlAuthz.validateRuleType(payloadRule.type)); const rule = await updateRules({ - alertsClient, + rulesClient, savedObjectsClient, defaultOutputIndex: siemClient.getSignalsIndex(), ruleUpdate: payloadRule, @@ -79,7 +79,7 @@ export const updateRulesBulkRoute = ( if (rule != null) { const ruleActions = await updateRulesNotifications({ ruleAlertId: rule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: payloadRule.enabled ?? true, actions: payloadRule.actions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts index cf121d1610d39..60a91521bc766 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts @@ -36,9 +36,9 @@ describe('update_rules', () => { ({ clients, context } = requestContextMock.createTools()); ml = mlServicesMock.createSetupContract(); - clients.alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); // existing rule - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists - clients.alertsClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful update + clients.rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); // existing rule + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); // rule exists + clients.rulesClient.update.mockResolvedValue(getAlertMock(getQueryRuleParams())); // successful update clients.savedObjectsClient.find.mockResolvedValue(getFindResultStatusEmpty()); // successful transform updateRulesRoute(server.router, ml); @@ -57,7 +57,7 @@ describe('update_rules', () => { }); test('returns 404 when updating a single rule that does not exist', async () => { - clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + clients.rulesClient.find.mockResolvedValue(getEmptyFindResult()); const response = await server.inject(getUpdateRequest(), context); expect(response.status).toEqual(404); @@ -68,7 +68,7 @@ describe('update_rules', () => { }); test('returns 404 if alertClient is not available on the route', async () => { - context.alerting!.getAlertsClient = jest.fn(); + context.alerting!.getRulesClient = jest.fn(); const response = await server.inject(getUpdateRequest(), context); expect(response.status).toEqual(404); @@ -84,7 +84,7 @@ describe('update_rules', () => { }); test('returns error when updating non-rule', async () => { - clients.alertsClient.find.mockResolvedValue(nonRuleFindResult()); + clients.rulesClient.find.mockResolvedValue(nonRuleFindResult()); const response = await server.inject(getUpdateRequest(), context); expect(response.status).toEqual(404); @@ -95,7 +95,7 @@ describe('update_rules', () => { }); test('catches error if search throws error', async () => { - clients.alertsClient.find.mockImplementation(async () => { + clients.rulesClient.find.mockImplementation(async () => { throw new Error('Test error'); }); const response = await server.inject(getUpdateRequest(), context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts index 0ff6cb3cd2d0f..a6f07c2f84d16 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts @@ -45,12 +45,12 @@ export const updateRulesRoute = ( return siemResponse.error({ statusCode: 400, body: validationErrors }); } try { - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); - if (!siemClient || !alertsClient) { + if (!siemClient || !rulesClient) { return siemResponse.error({ statusCode: 404 }); } @@ -63,7 +63,7 @@ export const updateRulesRoute = ( throwHttpError(await mlAuthz.validateRuleType(request.body.type)); const rule = await updateRules({ - alertsClient, + rulesClient, savedObjectsClient, defaultOutputIndex: siemClient.getSignalsIndex(), ruleUpdate: request.body, @@ -72,7 +72,7 @@ export const updateRulesRoute = ( if (rule != null) { const ruleActions = await updateRulesNotifications({ ruleAlertId: rule.id, - alertsClient, + rulesClient, savedObjectsClient, enabled: request.body.enabled ?? true, actions: request.body.actions ?? [], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts index 817e4b95aabce..e22497071b2b7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts @@ -23,15 +23,15 @@ export const readTagsRoute = (router: SecuritySolutionPluginRouter) => { }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); - if (!alertsClient) { + if (!rulesClient) { return siemResponse.error({ statusCode: 404 }); } try { const tags = await readTags({ - alertsClient, + rulesClient, }); return response.ok({ body: tags }); } catch (err) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts index ce7d4b3173370..83091c7e1f82e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts @@ -9,7 +9,7 @@ import Boom from '@hapi/boom'; import { SavedObjectsFindResponse } from 'kibana/server'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { IRuleSavedAttributesSavedObjectAttributes, IRuleStatusSOAttributes } from '../rules/types'; import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { @@ -30,7 +30,7 @@ import { getAlertMock } from './__mocks__/request_responses'; import { AlertExecutionStatusErrorReasons } from '../../../../../alerting/common'; import { getQueryRuleParams } from '../schemas/rule_schemas.mock'; -let alertsClient: ReturnType; +let rulesClient: ReturnType; describe('utils', () => { describe('transformBulkError', () => { @@ -386,11 +386,11 @@ describe('utils', () => { describe('getFailingRules', () => { beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); }); it('getFailingRules finds no failing rules', async () => { - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - const res = await getFailingRules(['my-fake-id'], alertsClient); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + const res = await getFailingRules(['my-fake-id'], rulesClient); expect(res).toEqual({}); }); it('getFailingRules finds a failing rule', async () => { @@ -403,22 +403,22 @@ describe('utils', () => { message: 'oops', }, }; - alertsClient.get.mockResolvedValue(foundRule); - const res = await getFailingRules([foundRule.id], alertsClient); + rulesClient.get.mockResolvedValue(foundRule); + const res = await getFailingRules([foundRule.id], rulesClient); expect(res).toEqual({ [foundRule.id]: foundRule }); }); it('getFailingRules throws an error', async () => { - alertsClient.get.mockImplementation(() => { + rulesClient.get.mockImplementation(() => { throw new Error('my test error'); }); let error; try { - await getFailingRules(['my-fake-id'], alertsClient); + await getFailingRules(['my-fake-id'], rulesClient); } catch (exc) { error = exc; } expect(error.message).toEqual( - 'Failed to get executionStatus with AlertsClient: my test error' + 'Failed to get executionStatus with RulesClient: my test error' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts index 9ff75726322a1..8f078b01daf73 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts @@ -15,7 +15,7 @@ import { KibanaResponseFactory, CustomHttpResponseOptions, } from '../../../../../../../src/core/server'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { RuleStatusResponse, IRuleStatusSOAttributes } from '../rules/types'; import { RuleParams } from '../schemas/rule_schemas'; @@ -304,12 +304,12 @@ export type GetFailingRulesResult = Record>; export const getFailingRules = async ( ids: string[], - alertsClient: AlertsClient + rulesClient: RulesClient ): Promise => { try { const errorRules = await Promise.all( ids.map(async (id) => - alertsClient.get({ + rulesClient.get({ id, }) ) @@ -328,6 +328,6 @@ export const getFailingRules = async ( if (Boom.isBoom(exc)) { throw exc; } - throw new Error(`Failed to get executionStatus with AlertsClient: ${exc.message}`); + throw new Error(`Failed to get executionStatus with RulesClient: ${exc.message}`); } }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts index 86feed1f39cef..f7aae1564bb17 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts @@ -6,12 +6,12 @@ */ import { CreateRulesOptions } from './types'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; export const getCreateRulesOptionsMock = (): CreateRulesOptions => ({ author: ['Elastic'], buildingBlockType: undefined, - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), anomalyThreshold: undefined, description: 'some description', enabled: true, @@ -63,7 +63,7 @@ export const getCreateRulesOptionsMock = (): CreateRulesOptions => ({ export const getCreateMlRulesOptionsMock = (): CreateRulesOptions => ({ author: ['Elastic'], buildingBlockType: undefined, - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), anomalyThreshold: 55, description: 'some description', enabled: true, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts index c719412d27e4d..3dd29977a8f2c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts @@ -9,10 +9,10 @@ import { createRules } from './create_rules'; import { getCreateMlRulesOptionsMock } from './create_rules.mock'; describe('createRules', () => { - it('calls the alertsClient with legacy ML params', async () => { + it('calls the rulesClient with legacy ML params', async () => { const ruleOptions = getCreateMlRulesOptionsMock(); await createRules(ruleOptions); - expect(ruleOptions.alertsClient.create).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -24,13 +24,13 @@ describe('createRules', () => { ); }); - it('calls the alertsClient with ML params', async () => { + it('calls the rulesClient with ML params', async () => { const ruleOptions = { ...getCreateMlRulesOptionsMock(), machineLearningJobId: ['new_job_1', 'new_job_2'], }; await createRules(ruleOptions); - expect(ruleOptions.alertsClient.create).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts index db039bbc31390..c94cb39572ddc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts @@ -17,7 +17,7 @@ import { addTags } from './add_tags'; import { PartialFilter, RuleTypeParams } from '../types'; export const createRules = async ({ - alertsClient, + rulesClient, anomalyThreshold, author, buildingBlockType, @@ -67,7 +67,7 @@ export const createRules = async ({ exceptionsList, actions, }: CreateRulesOptions): Promise> => { - return alertsClient.create({ + return rulesClient.create({ data: { name, tags: addTags(tags, ruleId, immutable), diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts index f581be9e1f62b..cd7bbfd9fced7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts @@ -6,7 +6,7 @@ */ import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { ruleStatusSavedObjectsClientMock } from '../signals/__mocks__/rule_status_saved_objects_client.mock'; import { deleteRules } from './delete_rules'; import { deleteNotifications } from '../notifications/delete_notifications'; @@ -18,12 +18,12 @@ jest.mock('../notifications/delete_notifications'); jest.mock('../rule_actions/delete_rule_actions_saved_object'); describe('deleteRules', () => { - let alertsClient: ReturnType; + let rulesClient: ReturnType; let ruleStatusClient: ReturnType; let savedObjectsClient: ReturnType; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); savedObjectsClient = savedObjectsClientMock.create(); ruleStatusClient = ruleStatusSavedObjectsClientMock.create(); }); @@ -50,7 +50,7 @@ describe('deleteRules', () => { }; const rule = { - alertsClient, + rulesClient, savedObjectsClient, ruleStatusClient, id: 'ruleId', @@ -64,10 +64,10 @@ describe('deleteRules', () => { await deleteRules(rule); - expect(alertsClient.delete).toHaveBeenCalledWith({ id: rule.id }); + expect(rulesClient.delete).toHaveBeenCalledWith({ id: rule.id }); expect(deleteNotifications).toHaveBeenCalledWith({ ruleAlertId: rule.id, - alertsClient: expect.any(Object), + rulesClient: expect.any(Object), }); expect(deleteRuleActionsSavedObject).toHaveBeenCalledWith({ ruleAlertId: rule.id, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts index ed5477599253b..e1385eb05a6b4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts @@ -10,14 +10,14 @@ import { deleteRuleActionsSavedObject } from '../rule_actions/delete_rule_action import { DeleteRuleOptions } from './types'; export const deleteRules = async ({ - alertsClient, + rulesClient, savedObjectsClient, ruleStatusClient, ruleStatuses, id, }: DeleteRuleOptions) => { - await alertsClient.delete({ id }); - await deleteNotifications({ alertsClient, ruleAlertId: id }); + await rulesClient.delete({ id }); + await deleteNotifications({ rulesClient, ruleAlertId: id }); await deleteRuleActionsSavedObject({ ruleAlertId: id, savedObjectsClient }); ruleStatuses.saved_objects.forEach(async (obj) => ruleStatusClient.delete(obj.id)); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/enable_rule.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/enable_rule.ts index dc4cca2059b3e..1a81cf0cb5ebe 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/enable_rule.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/enable_rule.ts @@ -7,13 +7,13 @@ import { SavedObjectsClientContract } from 'kibana/server'; import { SanitizedAlert } from '../../../../../alerting/common'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { RuleParams } from '../schemas/rule_schemas'; import { ruleStatusSavedObjectsClientFactory } from '../signals/rule_status_saved_objects_client'; interface EnableRuleArgs { rule: SanitizedAlert; - alertsClient: AlertsClient; + rulesClient: RulesClient; savedObjectsClient: SavedObjectsClientContract; } @@ -21,11 +21,11 @@ interface EnableRuleArgs { * Enables the rule and updates its status to 'going to run' * * @param rule - rule to enable - * @param alertsClient - Alerts client + * @param rulesClient - Alerts client * @param savedObjectsClient - Saved Objects client */ -export const enableRule = async ({ rule, alertsClient, savedObjectsClient }: EnableRuleArgs) => { - await alertsClient.enable({ id: rule.id }); +export const enableRule = async ({ rule, rulesClient, savedObjectsClient }: EnableRuleArgs) => { + await rulesClient.enable({ id: rule.id }); const ruleStatusClient = ruleStatusSavedObjectsClientFactory(savedObjectsClient); const ruleCurrentStatus = await ruleStatusClient.find({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts index eae5ccd2f6ffd..e41dac066e18a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts @@ -19,7 +19,7 @@ export const getFilter = (filter: string | null | undefined) => { }; export const findRules = ({ - alertsClient, + rulesClient, perPage, page, fields, @@ -27,7 +27,7 @@ export const findRules = ({ sortField, sortOrder, }: FindRuleOptions): Promise> => { - return alertsClient.find({ + return rulesClient.find({ options: { fields, page, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.test.ts index da67bea0ca970..19a6a4e43d877 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getAlertMock, getFindResultWithSingleHit, @@ -27,14 +27,14 @@ describe('get_existing_prepackaged_rules', () => { describe('getExistingPrepackagedRules', () => { test('should return a single item in a single page', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - const rules = await getExistingPrepackagedRules({ alertsClient }); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rules = await getExistingPrepackagedRules({ rulesClient }); expect(rules).toEqual([getAlertMock(getQueryRuleParams())]); }); test('should return 3 items over 1 page with all on one page', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result1 = getAlertMock(getQueryRuleParams()); result1.params.immutable = true; @@ -49,7 +49,7 @@ describe('get_existing_prepackaged_rules', () => { result3.id = 'f3e1bf0b-b95f-43da-b1de-5d2f0af2287a'; // first result mock which is for returning the total - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1], perPage: 1, @@ -59,7 +59,7 @@ describe('get_existing_prepackaged_rules', () => { ); // second mock which will return all the data on a single page - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1, result2, result3], perPage: 3, @@ -68,21 +68,21 @@ describe('get_existing_prepackaged_rules', () => { }) ); - const rules = await getExistingPrepackagedRules({ alertsClient }); + const rules = await getExistingPrepackagedRules({ rulesClient }); expect(rules).toEqual([result1, result2, result3]); }); }); describe('getNonPackagedRules', () => { test('should return a single item in a single page', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - const rules = await getNonPackagedRules({ alertsClient }); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rules = await getNonPackagedRules({ rulesClient }); expect(rules).toEqual([getAlertMock(getQueryRuleParams())]); }); test('should return 2 items over 1 page', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result1 = getAlertMock(getQueryRuleParams()); result1.id = '4baa53f8-96da-44ee-ad58-41bccb7f9f3d'; @@ -91,7 +91,7 @@ describe('get_existing_prepackaged_rules', () => { result2.id = '5baa53f8-96da-44ee-ad58-41bccb7f9f3d'; // first result mock which is for returning the total - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1], perPage: 1, @@ -101,16 +101,16 @@ describe('get_existing_prepackaged_rules', () => { ); // second mock which will return all the data on a single page - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1, result2], perPage: 2, page: 1, total: 2 }) ); - const rules = await getNonPackagedRules({ alertsClient }); + const rules = await getNonPackagedRules({ rulesClient }); expect(rules).toEqual([result1, result2]); }); test('should return 3 items over 1 page with all on one page', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result1 = getAlertMock(getQueryRuleParams()); result1.id = '4baa53f8-96da-44ee-ad58-41bccb7f9f3d'; @@ -122,7 +122,7 @@ describe('get_existing_prepackaged_rules', () => { result3.id = 'f3e1bf0b-b95f-43da-b1de-5d2f0af2287a'; // first result mock which is for returning the total - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1], perPage: 3, @@ -132,7 +132,7 @@ describe('get_existing_prepackaged_rules', () => { ); // second mock which will return all the data on a single page - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1, result2, result3], perPage: 3, @@ -141,21 +141,21 @@ describe('get_existing_prepackaged_rules', () => { }) ); - const rules = await getNonPackagedRules({ alertsClient }); + const rules = await getNonPackagedRules({ rulesClient }); expect(rules).toEqual([result1, result2, result3]); }); }); describe('getRules', () => { test('should return a single item in a single page', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - const rules = await getRules({ alertsClient, filter: '' }); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rules = await getRules({ rulesClient, filter: '' }); expect(rules).toEqual([getAlertMock(getQueryRuleParams())]); }); test('should return 2 items over two pages, one per page', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result1 = getAlertMock(getQueryRuleParams()); result1.id = '4baa53f8-96da-44ee-ad58-41bccb7f9f3d'; @@ -164,7 +164,7 @@ describe('get_existing_prepackaged_rules', () => { result2.id = '5baa53f8-96da-44ee-ad58-41bccb7f9f3d'; // first result mock which is for returning the total - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1], perPage: 1, @@ -174,29 +174,29 @@ describe('get_existing_prepackaged_rules', () => { ); // second mock which will return all the data on a single page - alertsClient.find.mockResolvedValueOnce( + rulesClient.find.mockResolvedValueOnce( getFindResultWithMultiHits({ data: [result1, result2], perPage: 2, page: 1, total: 2 }) ); - const rules = await getRules({ alertsClient, filter: '' }); + const rules = await getRules({ rulesClient, filter: '' }); expect(rules).toEqual([result1, result2]); }); }); describe('getRulesCount', () => { test('it returns a count', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - const rules = await getRulesCount({ alertsClient, filter: '' }); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rules = await getRulesCount({ rulesClient, filter: '' }); expect(rules).toEqual(1); }); }); describe('getNonPackagedRulesCount', () => { test('it returns a count', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - const rules = await getNonPackagedRulesCount({ alertsClient }); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rules = await getNonPackagedRulesCount({ rulesClient }); expect(rules).toEqual(1); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts index a8c1d7aeb8eb1..be8bf1303846d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts @@ -6,7 +6,7 @@ */ import { INTERNAL_IMMUTABLE_KEY } from '../../../../common/constants'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { RuleAlertType, isAlertTypes } from './types'; import { findRules } from './find_rules'; @@ -14,22 +14,22 @@ export const FILTER_NON_PREPACKED_RULES = `alert.attributes.tags: "${INTERNAL_IM export const FILTER_PREPACKED_RULES = `alert.attributes.tags: "${INTERNAL_IMMUTABLE_KEY}:true"`; export const getNonPackagedRulesCount = async ({ - alertsClient, + rulesClient, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; }): Promise => { - return getRulesCount({ alertsClient, filter: FILTER_NON_PREPACKED_RULES }); + return getRulesCount({ rulesClient, filter: FILTER_NON_PREPACKED_RULES }); }; export const getRulesCount = async ({ - alertsClient, + rulesClient, filter, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; filter: string; }): Promise => { const firstRule = await findRules({ - alertsClient, + rulesClient, filter, perPage: 1, page: 1, @@ -41,15 +41,15 @@ export const getRulesCount = async ({ }; export const getRules = async ({ - alertsClient, + rulesClient, filter, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; filter: string; }): Promise => { - const count = await getRulesCount({ alertsClient, filter }); + const count = await getRulesCount({ rulesClient, filter }); const rules = await findRules({ - alertsClient, + rulesClient, filter, perPage: count, page: 1, @@ -68,23 +68,23 @@ export const getRules = async ({ }; export const getNonPackagedRules = async ({ - alertsClient, + rulesClient, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; }): Promise => { return getRules({ - alertsClient, + rulesClient, filter: FILTER_NON_PREPACKED_RULES, }); }; export const getExistingPrepackagedRules = async ({ - alertsClient, + rulesClient, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; }): Promise => { return getRules({ - alertsClient, + rulesClient, filter: FILTER_PREPACKED_RULES, }); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.test.ts index 4c937b2e4ca8a..2870bee99e51a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.test.ts @@ -10,7 +10,7 @@ import { getFindResultWithSingleHit, FindHit, } from '../routes/__mocks__/request_responses'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getExportAll } from './get_export_all'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; import { getThreatMock } from '../../../../common/detection_engine/schemas/types/threat.mock'; @@ -18,7 +18,7 @@ import { getQueryRuleParams } from '../schemas/rule_schemas.mock'; describe('getExportAll', () => { test('it exports everything from the alerts client', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result = getFindResultWithSingleHit(); const alert = getAlertMock(getQueryRuleParams()); alert.params = { @@ -30,9 +30,9 @@ describe('getExportAll', () => { timelineTitle: 'some-timeline-title', }; result.data = [alert]; - alertsClient.find.mockResolvedValue(result); + rulesClient.find.mockResolvedValue(result); - const exports = await getExportAll(alertsClient); + const exports = await getExportAll(rulesClient); const rulesJson = JSON.parse(exports.rulesNdjson); const detailsJson = JSON.parse(exports.exportDetails); expect(rulesJson).toEqual({ @@ -84,7 +84,7 @@ describe('getExportAll', () => { }); test('it will export empty rules', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const findResult: FindHit = { page: 1, perPage: 1, @@ -92,9 +92,9 @@ describe('getExportAll', () => { data: [], }; - alertsClient.find.mockResolvedValue(findResult); + rulesClient.find.mockResolvedValue(findResult); - const exports = await getExportAll(alertsClient); + const exports = await getExportAll(rulesClient); expect(exports).toEqual({ rulesNdjson: '', exportDetails: '{"exported_count":0,"missing_rules":[],"missing_rules_count":0}\n', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.ts index c0e893b8aea96..9ec51cf18c7c7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_all.ts @@ -5,19 +5,19 @@ * 2.0. */ -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { getNonPackagedRules } from './get_existing_prepackaged_rules'; import { getExportDetailsNdjson } from './get_export_details_ndjson'; import { transformAlertsToRules } from '../routes/rules/utils'; import { transformDataToNdjson } from '../../../utils/read_stream/create_stream_from_ndjson'; export const getExportAll = async ( - alertsClient: AlertsClient + rulesClient: RulesClient ): Promise<{ rulesNdjson: string; exportDetails: string; }> => { - const ruleAlertTypes = await getNonPackagedRules({ alertsClient }); + const ruleAlertTypes = await getNonPackagedRules({ rulesClient }); const rules = transformAlertsToRules(ruleAlertTypes); const rulesNdjson = transformDataToNdjson(rules); const exportDetails = getExportDetailsNdjson(rules); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.test.ts index 7410f97241966..f4325086e4212 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.test.ts @@ -11,7 +11,7 @@ import { getFindResultWithSingleHit, FindHit, } from '../routes/__mocks__/request_responses'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; import { getThreatMock } from '../../../../common/detection_engine/schemas/types/threat.mock'; import { getQueryRuleParams } from '../schemas/rule_schemas.mock'; @@ -24,11 +24,11 @@ describe('get_export_by_object_ids', () => { }); describe('getExportByObjectIds', () => { test('it exports object ids into an expected string with new line characters', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const objects = [{ rule_id: 'rule-1' }]; - const exports = await getExportByObjectIds(alertsClient, objects); + const exports = await getExportByObjectIds(rulesClient, objects); const exportsObj = { rulesNdjson: JSON.parse(exports.rulesNdjson), exportDetails: JSON.parse(exports.exportDetails), @@ -84,7 +84,7 @@ describe('get_export_by_object_ids', () => { }); test('it does not export immutable rules', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result = getAlertMock(getQueryRuleParams()); result.params.immutable = true; @@ -95,11 +95,11 @@ describe('get_export_by_object_ids', () => { data: [result], }; - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - alertsClient.find.mockResolvedValue(findResult); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + rulesClient.find.mockResolvedValue(findResult); const objects = [{ rule_id: 'rule-1' }]; - const exports = await getExportByObjectIds(alertsClient, objects); + const exports = await getExportByObjectIds(rulesClient, objects); expect(exports).toEqual({ rulesNdjson: '', exportDetails: @@ -110,11 +110,11 @@ describe('get_export_by_object_ids', () => { describe('getRulesFromObjects', () => { test('it returns transformed rules from objects sent in', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const objects = [{ rule_id: 'rule-1' }]; - const exports = await getRulesFromObjects(alertsClient, objects); + const exports = await getRulesFromObjects(rulesClient, objects); const expected: RulesErrors = { exportedCount: 1, missingRules: [], @@ -174,7 +174,7 @@ describe('get_export_by_object_ids', () => { }); test('it does not transform the rule if the rule is an immutable rule and designates it as a missing rule', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result = getAlertMock(getQueryRuleParams()); result.params.immutable = true; @@ -185,11 +185,11 @@ describe('get_export_by_object_ids', () => { data: [result], }; - alertsClient.get.mockResolvedValue(result); - alertsClient.find.mockResolvedValue(findResult); + rulesClient.get.mockResolvedValue(result); + rulesClient.find.mockResolvedValue(findResult); const objects = [{ rule_id: 'rule-1' }]; - const exports = await getRulesFromObjects(alertsClient, objects); + const exports = await getRulesFromObjects(rulesClient, objects); const expected: RulesErrors = { exportedCount: 0, missingRules: [{ rule_id: 'rule-1' }], @@ -199,7 +199,7 @@ describe('get_export_by_object_ids', () => { }); test('it exports missing rules', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const findResult: FindHit = { page: 1, @@ -208,11 +208,11 @@ describe('get_export_by_object_ids', () => { data: [], }; - alertsClient.get.mockRejectedValue({ output: { statusCode: 404 } }); - alertsClient.find.mockResolvedValue(findResult); + rulesClient.get.mockRejectedValue({ output: { statusCode: 404 } }); + rulesClient.find.mockResolvedValue(findResult); const objects = [{ rule_id: 'rule-1' }]; - const exports = await getRulesFromObjects(alertsClient, objects); + const exports = await getRulesFromObjects(rulesClient, objects); const expected: RulesErrors = { exportedCount: 0, missingRules: [{ rule_id: 'rule-1' }], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts index 63b34435e8427..5d33e37c2ecf9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts @@ -8,7 +8,7 @@ import { chunk } from 'lodash'; import { RulesSchema } from '../../../../common/detection_engine/schemas/response/rules_schema'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { getExportDetailsNdjson } from './get_export_details_ndjson'; import { isAlertType } from '../rules/types'; import { transformAlertToRule } from '../routes/rules/utils'; @@ -33,20 +33,20 @@ export interface RulesErrors { } export const getExportByObjectIds = async ( - alertsClient: AlertsClient, + rulesClient: RulesClient, objects: Array<{ rule_id: string }> ): Promise<{ rulesNdjson: string; exportDetails: string; }> => { - const rulesAndErrors = await getRulesFromObjects(alertsClient, objects); + const rulesAndErrors = await getRulesFromObjects(rulesClient, objects); const rulesNdjson = transformDataToNdjson(rulesAndErrors.rules); const exportDetails = getExportDetailsNdjson(rulesAndErrors.rules, rulesAndErrors.missingRules); return { rulesNdjson, exportDetails }; }; export const getRulesFromObjects = async ( - alertsClient: AlertsClient, + rulesClient: RulesClient, objects: Array<{ rule_id: string }> ): Promise => { // If we put more than 1024 ids in one block like "alert.attributes.tags: (id1 OR id2 OR ... OR id1100)" @@ -65,7 +65,7 @@ export const getRulesFromObjects = async ( }) .join(' OR '); const rules = await findRules({ - alertsClient, + rulesClient, filter, page: 1, fields: undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts index 7efd63cc67722..587ce3f002b80 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts @@ -7,12 +7,12 @@ import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { SanitizedAlert, AlertTypeParams } from '../../../../../alerting/common'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { createRules } from './create_rules'; import { PartialFilter } from '../types'; export const installPrepackagedRules = ( - alertsClient: AlertsClient, + rulesClient: RulesClient, rules: AddPrepackagedRulesSchemaDecoded[], outputIndex: string ): Array>> => @@ -70,7 +70,7 @@ export const installPrepackagedRules = ( return [ ...acc, createRules({ - alertsClient, + rulesClient, anomalyThreshold, author, buildingBlockType, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts index d42b6c5aeefaa..826b197cfe094 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts @@ -6,7 +6,7 @@ */ import { PatchRulesOptions } from './types'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; import { getAlertMock } from '../routes/__mocks__/request_responses'; import { getMlRuleParams, getQueryRuleParams } from '../schemas/rule_schemas.mock'; @@ -14,7 +14,7 @@ import { getMlRuleParams, getQueryRuleParams } from '../schemas/rule_schemas.moc export const getPatchRulesOptionsMock = (): PatchRulesOptions => ({ author: ['Elastic'], buildingBlockType: undefined, - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), savedObjectsClient: savedObjectsClientMock.create(), anomalyThreshold: undefined, description: 'some description', @@ -65,7 +65,7 @@ export const getPatchRulesOptionsMock = (): PatchRulesOptions => ({ export const getPatchMlRulesOptionsMock = (): PatchRulesOptions => ({ author: ['Elastic'], buildingBlockType: undefined, - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), savedObjectsClient: savedObjectsClientMock.create(), anomalyThreshold: 55, description: 'some description', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts index e275a02b2b0c1..1bd2656e41bae 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts @@ -10,21 +10,21 @@ import { getPatchRulesOptionsMock, getPatchMlRulesOptionsMock } from './patch_ru import { PatchRulesOptions } from './types'; describe('patchRules', () => { - it('should call alertsClient.disable if the rule was enabled and enabled is false', async () => { + it('should call rulesClient.disable if the rule was enabled and enabled is false', async () => { const rulesOptionsMock = getPatchRulesOptionsMock(); const ruleOptions: PatchRulesOptions = { ...rulesOptionsMock, enabled: false, }; await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.disable).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.disable).toHaveBeenCalledWith( expect.objectContaining({ id: ruleOptions.rule?.id, }) ); }); - it('should call alertsClient.enable if the rule was disabled and enabled is true', async () => { + it('should call rulesClient.enable if the rule was disabled and enabled is true', async () => { const rulesOptionsMock = getPatchRulesOptionsMock(); const ruleOptions: PatchRulesOptions = { ...rulesOptionsMock, @@ -34,14 +34,14 @@ describe('patchRules', () => { ruleOptions.rule.enabled = false; } await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.enable).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.enable).toHaveBeenCalledWith( expect.objectContaining({ id: ruleOptions.rule?.id, }) ); }); - it('calls the alertsClient with legacy ML params', async () => { + it('calls the rulesClient with legacy ML params', async () => { const rulesOptionsMock = getPatchMlRulesOptionsMock(); const ruleOptions: PatchRulesOptions = { ...rulesOptionsMock, @@ -51,7 +51,7 @@ describe('patchRules', () => { ruleOptions.rule.enabled = false; } await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -63,7 +63,7 @@ describe('patchRules', () => { ); }); - it('calls the alertsClient with new ML params', async () => { + it('calls the rulesClient with new ML params', async () => { const rulesOptionsMock = getPatchMlRulesOptionsMock(); const ruleOptions: PatchRulesOptions = { ...rulesOptionsMock, @@ -74,7 +74,7 @@ describe('patchRules', () => { ruleOptions.rule.enabled = false; } await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -103,7 +103,7 @@ describe('patchRules', () => { ], }; await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: [ @@ -138,7 +138,7 @@ describe('patchRules', () => { } await patchRules(ruleOptions); - expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( + expect(ruleOptions.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: [ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts index 72af7ebc340cd..60e406255494a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts @@ -28,7 +28,7 @@ class PatchError extends Error { } export const patchRules = async ({ - alertsClient, + rulesClient, author, buildingBlockType, savedObjectsClient, @@ -192,15 +192,15 @@ export const patchRules = async ({ throw new PatchError(`Applying patch would create invalid rule: ${errors}`, 400); } - const update = await alertsClient.update({ + const update = await rulesClient.update({ id: rule.id, data: validated, }); if (rule.enabled && enabled === false) { - await alertsClient.disable({ id: rule.id }); + await rulesClient.disable({ id: rule.id }); } else if (!rule.enabled && enabled === true) { - await enableRule({ rule, alertsClient, savedObjectsClient }); + await enableRule({ rule, rulesClient, savedObjectsClient }); } else { // enabled is null or undefined and we do not touch the rule } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts index ce82384291303..33bc002942497 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts @@ -6,7 +6,7 @@ */ import { readRules } from './read_rules'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getAlertMock, getFindResultWithSingleHit } from '../routes/__mocks__/request_responses'; import { getQueryRuleParams } from '../schemas/rule_schemas.mock'; @@ -28,26 +28,26 @@ describe('read_rules', () => { jest.clearAllMocks(); }); describe('readRules', () => { - test('should return the output from alertsClient if id is set but ruleId is undefined', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + test('should return the output from rulesClient if id is set but ruleId is undefined', async () => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); const rule = await readRules({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleId: undefined, }); expect(rule).toEqual(getAlertMock(getQueryRuleParams())); }); test('should return null if saved object found by alerts client given id is not alert type', async () => { - const alertsClient = alertsClientMock.create(); + const rulesClient = rulesClientMock.create(); const result = getAlertMock(getQueryRuleParams()); // @ts-expect-error delete result.alertTypeId; - alertsClient.get.mockResolvedValue(result); + rulesClient.get.mockResolvedValue(result); const rule = await readRules({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleId: undefined, }); @@ -55,13 +55,13 @@ describe('read_rules', () => { }); test('should return error if alerts client throws 404 error on get', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockImplementation(() => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockImplementation(() => { throw new TestError(); }); const rule = await readRules({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleId: undefined, }); @@ -69,13 +69,13 @@ describe('read_rules', () => { }); test('should return error if alerts client throws error on get', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockImplementation(() => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockImplementation(() => { throw new Error('Test error'); }); try { await readRules({ - alertsClient, + rulesClient, id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', ruleId: undefined, }); @@ -84,39 +84,39 @@ describe('read_rules', () => { } }); - test('should return the output from alertsClient if id is undefined but ruleId is set', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + test('should return the output from rulesClient if id is undefined but ruleId is set', async () => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const rule = await readRules({ - alertsClient, + rulesClient, id: undefined, ruleId: 'rule-1', }); expect(rule).toEqual(getAlertMock(getQueryRuleParams())); }); - test('should return null if the output from alertsClient with ruleId set is empty', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - alertsClient.find.mockResolvedValue({ data: [], page: 0, perPage: 1, total: 0 }); + test('should return null if the output from rulesClient with ruleId set is empty', async () => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + rulesClient.find.mockResolvedValue({ data: [], page: 0, perPage: 1, total: 0 }); const rule = await readRules({ - alertsClient, + rulesClient, id: undefined, ruleId: 'rule-1', }); expect(rule).toEqual(null); }); - test('should return the output from alertsClient if id is null but ruleId is set', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + test('should return the output from rulesClient if id is null but ruleId is set', async () => { + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const rule = await readRules({ - alertsClient, + rulesClient, id: undefined, ruleId: 'rule-1', }); @@ -124,12 +124,12 @@ describe('read_rules', () => { }); test('should return null if id and ruleId are undefined', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + const rulesClient = rulesClientMock.create(); + rulesClient.get.mockResolvedValue(getAlertMock(getQueryRuleParams())); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); const rule = await readRules({ - alertsClient, + rulesClient, id: undefined, ruleId: undefined, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts index 62f8e7642cc64..141977f2474e0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts @@ -14,19 +14,19 @@ import { isAlertType, ReadRuleOptions } from './types'; /** * This reads the rules through a cascade try of what is fastest to what is slowest. * @param id - This is the fastest. This is the auto-generated id through the parameter id. - * and the id will either be found through `alertsClient.get({ id })` or it will not + * and the id will either be found through `rulesClient.get({ id })` or it will not * be returned as a not-found or a thrown error that is not 404. * @param ruleId - This is a close second to being fast as long as it can find the rule_id from * a filter query against the tags using `alert.attributes.tags: "__internal:${ruleId}"]` */ export const readRules = async ({ - alertsClient, + rulesClient, id, ruleId, }: ReadRuleOptions): Promise | null> => { if (id != null) { try { - const rule = await alertsClient.get({ id }); + const rule = await rulesClient.get({ id }); if (isAlertType(rule)) { return rule; } else { @@ -42,7 +42,7 @@ export const readRules = async ({ } } else if (ruleId != null) { const ruleFromFind = await findRules({ - alertsClient, + rulesClient, filter: `alert.attributes.tags: "${INTERNAL_RULE_ID_KEY}:${ruleId}"`, page: 1, fields: undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts index d029393ce781e..7274614e2c9ba 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts @@ -101,7 +101,7 @@ import { EventCategoryOverrideOrUndefined, } from '../../../../common/detection_engine/schemas/common/schemas'; -import { AlertsClient, PartialAlert } from '../../../../../alerting/server'; +import { RulesClient, PartialAlert } from '../../../../../alerting/server'; import { Alert, SanitizedAlert } from '../../../../../alerting/common'; import { SIGNALS_ID } from '../../../../common/constants'; import { PartialFilter } from '../types'; @@ -186,7 +186,7 @@ export interface HapiReadableStream extends Readable { } export interface Clients { - alertsClient: AlertsClient; + rulesClient: RulesClient; } export const isAlertTypes = ( @@ -214,7 +214,7 @@ export const isRuleStatusFindType = ( }; export interface CreateRulesOptions { - alertsClient: AlertsClient; + rulesClient: RulesClient; anomalyThreshold: AnomalyThresholdOrUndefined; author: Author; buildingBlockType: BuildingBlockTypeOrUndefined; @@ -267,14 +267,14 @@ export interface CreateRulesOptions { export interface UpdateRulesOptions { savedObjectsClient: SavedObjectsClientContract; - alertsClient: AlertsClient; + rulesClient: RulesClient; defaultOutputIndex: string; ruleUpdate: UpdateRulesSchema; } export interface PatchRulesOptions { savedObjectsClient: SavedObjectsClientContract; - alertsClient: AlertsClient; + rulesClient: RulesClient; anomalyThreshold: AnomalyThresholdOrUndefined; author: AuthorOrUndefined; buildingBlockType: BuildingBlockTypeOrUndefined; @@ -324,13 +324,13 @@ export interface PatchRulesOptions { } export interface ReadRuleOptions { - alertsClient: AlertsClient; + rulesClient: RulesClient; id: IdOrUndefined; ruleId: RuleIdOrUndefined; } export interface DeleteRuleOptions { - alertsClient: AlertsClient; + rulesClient: RulesClient; savedObjectsClient: SavedObjectsClientContract; ruleStatusClient: RuleStatusSavedObjectsClient; ruleStatuses: SavedObjectsFindResponse; @@ -338,7 +338,7 @@ export interface DeleteRuleOptions { } export interface FindRuleOptions { - alertsClient: AlertsClient; + rulesClient: RulesClient; perPage: PerPageOrUndefined; page: PageOrUndefined; sortField: SortFieldOrUndefined; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts index 1f75aa5a19a98..b88c7f0450cac 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts @@ -6,7 +6,7 @@ */ import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getFindResultWithSingleHit } from '../routes/__mocks__/request_responses'; import { updatePrepackagedRules } from './update_prepacked_rules'; import { patchRules } from './patch_rules'; @@ -14,11 +14,11 @@ import { getAddPrepackagedRulesSchemaDecodedMock } from '../../../../common/dete jest.mock('./patch_rules'); describe('updatePrepackagedRules', () => { - let alertsClient: ReturnType; + let rulesClient: ReturnType; let savedObjectsClient: ReturnType; beforeEach(() => { - alertsClient = alertsClientMock.create(); + rulesClient = rulesClientMock.create(); savedObjectsClient = savedObjectsClientMock.create(); }); @@ -33,10 +33,10 @@ describe('updatePrepackagedRules', () => { ]; const outputIndex = 'outputIndex'; const prepackagedRule = getAddPrepackagedRulesSchemaDecodedMock(); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); await updatePrepackagedRules( - alertsClient, + rulesClient, savedObjectsClient, [{ ...prepackagedRule, actions }], outputIndex diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts index f3ee7e251c02d..872a3b69d27ed 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts @@ -8,7 +8,7 @@ import { SavedObjectsClientContract } from 'kibana/server'; import { chunk } from 'lodash/fp'; import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; -import { AlertsClient, PartialAlert } from '../../../../../alerting/server'; +import { RulesClient, PartialAlert } from '../../../../../alerting/server'; import { patchRules } from './patch_rules'; import { readRules } from './read_rules'; import { PartialFilter } from '../types'; @@ -43,34 +43,34 @@ export const UPDATE_CHUNK_SIZE = 50; * Updates the prepackaged rules given a set of rules and output index. * This implements a chunked approach to not saturate network connections and * avoid being a "noisy neighbor". - * @param alertsClient Alerting client + * @param rulesClient Alerting client * @param savedObjectsClient Saved object client * @param rules The rules to apply the update for * @param outputIndex The output index to apply the update to. */ export const updatePrepackagedRules = async ( - alertsClient: AlertsClient, + rulesClient: RulesClient, savedObjectsClient: SavedObjectsClientContract, rules: AddPrepackagedRulesSchemaDecoded[], outputIndex: string ): Promise => { const ruleChunks = chunk(UPDATE_CHUNK_SIZE, rules); for (const ruleChunk of ruleChunks) { - const rulePromises = createPromises(alertsClient, savedObjectsClient, ruleChunk, outputIndex); + const rulePromises = createPromises(rulesClient, savedObjectsClient, ruleChunk, outputIndex); await Promise.all(rulePromises); } }; /** * Creates promises of the rules and returns them. - * @param alertsClient Alerting client + * @param rulesClient Alerting client * @param savedObjectsClient Saved object client * @param rules The rules to apply the update for * @param outputIndex The output index to apply the update to. * @returns Promise of what was updated. */ export const createPromises = ( - alertsClient: AlertsClient, + rulesClient: RulesClient, savedObjectsClient: SavedObjectsClientContract, rules: AddPrepackagedRulesSchemaDecoded[], outputIndex: string @@ -122,7 +122,7 @@ export const createPromises = ( exceptions_list: exceptionsList, } = rule; - const existingRule = await readRules({ alertsClient, ruleId, id: undefined }); + const existingRule = await readRules({ rulesClient, ruleId, id: undefined }); // TODO: Fix these either with an is conversion or by better typing them within io-ts const filters: PartialFilter[] | undefined = filtersObject as PartialFilter[]; @@ -130,7 +130,7 @@ export const createPromises = ( // Note: we do not pass down enabled as we do not want to suddenly disable // or enable rules on the user when they were not expecting it if a rule updates return patchRules({ - alertsClient, + rulesClient, author, buildingBlockType, description, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts index fd18ac7f7b6bc..778337a3650c7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts @@ -6,7 +6,7 @@ */ import { UpdateRulesOptions } from './types'; -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; import { getUpdateRulesSchemaMock, @@ -14,14 +14,14 @@ import { } from '../../../../common/detection_engine/schemas/request/rule_schemas.mock'; export const getUpdateRulesOptionsMock = (): UpdateRulesOptions => ({ - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), savedObjectsClient: savedObjectsClientMock.create(), defaultOutputIndex: '.siem-signals-default', ruleUpdate: getUpdateRulesSchemaMock(), }); export const getUpdateMlRulesOptionsMock = (): UpdateRulesOptions => ({ - alertsClient: alertsClientMock.create(), + rulesClient: rulesClientMock.create(), savedObjectsClient: savedObjectsClientMock.create(), defaultOutputIndex: '.siem-signals-default', ruleUpdate: getUpdateMachineLearningSchemaMock(), diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts index 48b8905384566..7d04d3412899d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts @@ -8,55 +8,55 @@ import { getAlertMock } from '../routes/__mocks__/request_responses'; import { updateRules } from './update_rules'; import { getUpdateRulesOptionsMock, getUpdateMlRulesOptionsMock } from './update_rules.mock'; -import { AlertsClientMock } from '../../../../../alerting/server/alerts_client.mock'; +import { RulesClientMock } from '../../../../../alerting/server/rules_client.mock'; import { getMlRuleParams, getQueryRuleParams } from '../schemas/rule_schemas.mock'; describe('updateRules', () => { - it('should call alertsClient.disable if the rule was enabled and enabled is false', async () => { + it('should call rulesClient.disable if the rule was enabled and enabled is false', async () => { const rulesOptionsMock = getUpdateRulesOptionsMock(); rulesOptionsMock.ruleUpdate.enabled = false; - ((rulesOptionsMock.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue( + ((rulesOptionsMock.rulesClient as unknown) as RulesClientMock).get.mockResolvedValue( getAlertMock(getQueryRuleParams()) ); await updateRules(rulesOptionsMock); - expect(rulesOptionsMock.alertsClient.disable).toHaveBeenCalledWith( + expect(rulesOptionsMock.rulesClient.disable).toHaveBeenCalledWith( expect.objectContaining({ id: rulesOptionsMock.ruleUpdate.id, }) ); }); - it('should call alertsClient.enable if the rule was disabled and enabled is true', async () => { + it('should call rulesClient.enable if the rule was disabled and enabled is true', async () => { const rulesOptionsMock = getUpdateRulesOptionsMock(); rulesOptionsMock.ruleUpdate.enabled = true; - ((rulesOptionsMock.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue({ + ((rulesOptionsMock.rulesClient as unknown) as RulesClientMock).get.mockResolvedValue({ ...getAlertMock(getQueryRuleParams()), enabled: false, }); await updateRules(rulesOptionsMock); - expect(rulesOptionsMock.alertsClient.enable).toHaveBeenCalledWith( + expect(rulesOptionsMock.rulesClient.enable).toHaveBeenCalledWith( expect.objectContaining({ id: rulesOptionsMock.ruleUpdate.id, }) ); }); - it('calls the alertsClient with params', async () => { + it('calls the rulesClient with params', async () => { const rulesOptionsMock = getUpdateMlRulesOptionsMock(); rulesOptionsMock.ruleUpdate.enabled = true; - ((rulesOptionsMock.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue( + ((rulesOptionsMock.rulesClient as unknown) as RulesClientMock).get.mockResolvedValue( getAlertMock(getMlRuleParams()) ); await updateRules(rulesOptionsMock); - expect(rulesOptionsMock.alertsClient.update).toHaveBeenCalledWith( + expect(rulesOptionsMock.rulesClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts index 0fac804163afa..e0be646dc3f39 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts @@ -18,13 +18,13 @@ import { InternalRuleUpdate, RuleParams } from '../schemas/rule_schemas'; import { enableRule } from './enable_rule'; export const updateRules = async ({ - alertsClient, + rulesClient, savedObjectsClient, defaultOutputIndex, ruleUpdate, }: UpdateRulesOptions): Promise | null> => { const existingRule = await readRules({ - alertsClient, + rulesClient, ruleId: ruleUpdate.rule_id, id: ruleUpdate.id, }); @@ -80,15 +80,15 @@ export const updateRules = async ({ notifyWhen: null, }; - const update = await alertsClient.update({ + const update = await rulesClient.update({ id: existingRule.id, data: newInternalRule, }); if (existingRule.enabled && enabled === false) { - await alertsClient.disable({ id: existingRule.id }); + await rulesClient.disable({ id: existingRule.id }); } else if (!existingRule.enabled && enabled === true) { - await enableRule({ rule: existingRule, alertsClient, savedObjectsClient }); + await enableRule({ rule: existingRule, rulesClient, savedObjectsClient }); } return { ...update, enabled }; }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules_notifications.ts index 60e448e3058c8..5f2729f129948 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules_notifications.ts @@ -6,13 +6,13 @@ */ import { RuleAlertAction } from '../../../../common/detection_engine/types'; -import { AlertsClient, AlertServices } from '../../../../../alerting/server'; +import { RulesClient, AlertServices } from '../../../../../alerting/server'; import { updateOrCreateRuleActionsSavedObject } from '../rule_actions/update_or_create_rule_actions_saved_object'; import { updateNotifications } from '../notifications/update_notifications'; import { RuleActions } from '../rule_actions/types'; interface UpdateRulesNotifications { - alertsClient: AlertsClient; + rulesClient: RulesClient; savedObjectsClient: AlertServices['savedObjectsClient']; ruleAlertId: string; actions: RuleAlertAction[] | undefined; @@ -22,7 +22,7 @@ interface UpdateRulesNotifications { } export const updateRulesNotifications = async ({ - alertsClient, + rulesClient, savedObjectsClient, ruleAlertId, actions, @@ -38,7 +38,7 @@ export const updateRulesNotifications = async ({ }); await updateNotifications({ - alertsClient, + rulesClient, ruleAlertId, enabled, name, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.test.ts index b2a589dacd371..1b7bf048646ed 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { alertsClientMock } from '../../../../../alerting/server/mocks'; +import { rulesClientMock } from '../../../../../alerting/server/mocks'; import { getAlertMock, getFindResultWithMultiHits } from '../routes/__mocks__/request_responses'; import { INTERNAL_RULE_ID_KEY, INTERNAL_IDENTIFIER } from '../../../../common/constants'; import { readRawTags, readTags, convertTagsToSet, convertToTags, isTags } from './read_tags'; @@ -28,10 +28,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = ['tag 1', 'tag 2', 'tag 3', 'tag 4']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2', 'tag 3', 'tag 4']); }); @@ -46,10 +46,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = ['tag 1', 'tag 2', 'tag 2', 'tag 3', 'tag 4']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2', 'tag 3', 'tag 4']); }); @@ -64,10 +64,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = []; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); expect(tags).toEqual([]); }); @@ -77,10 +77,10 @@ describe('read_tags', () => { result1.params.ruleId = 'rule-1'; result1.tags = ['tag 1', 'tag 1', 'tag 1', 'tag 2']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2']); }); @@ -90,10 +90,10 @@ describe('read_tags', () => { result1.params.ruleId = 'rule-1'; result1.tags = []; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); expect(tags).toEqual([]); }); }); @@ -110,10 +110,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = ['tag 1', 'tag 2', 'tag 3', 'tag 4']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2', 'tag 3', 'tag 4']); }); @@ -128,10 +128,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = ['tag 1', 'tag 2', 'tag 2', 'tag 3', 'tag 4']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2', 'tag 3', 'tag 4']); }); @@ -146,10 +146,10 @@ describe('read_tags', () => { result2.params.ruleId = 'rule-2'; result2.tags = []; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1, result2] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual([]); }); @@ -159,10 +159,10 @@ describe('read_tags', () => { result1.params.ruleId = 'rule-1'; result1.tags = ['tag 1', 'tag 1', 'tag 1', 'tag 2']; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2']); }); @@ -172,10 +172,10 @@ describe('read_tags', () => { result1.params.ruleId = 'rule-1'; result1.tags = []; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual([]); }); @@ -189,10 +189,10 @@ describe('read_tags', () => { 'tag 1', ]; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual(['tag 1']); }); @@ -222,10 +222,10 @@ describe('read_tags', () => { 'tag 4', ]; - const alertsClient = alertsClientMock.create(); - alertsClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); + const rulesClient = rulesClientMock.create(); + rulesClient.find.mockResolvedValue(getFindResultWithMultiHits({ data: [result1] })); - const tags = await readTags({ alertsClient }); + const tags = await readTags({ rulesClient }); expect(tags).toEqual(['tag 1', 'tag 2', 'tag 3', 'tag 4', 'tag 5']); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts index 2d1966917d287..2314a8a49f567 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts @@ -7,7 +7,7 @@ import { has } from 'lodash/fp'; import { INTERNAL_IDENTIFIER } from '../../../../common/constants'; -import { AlertsClient } from '../../../../../alerting/server'; +import { RulesClient } from '../../../../../alerting/server'; import { findRules } from '../rules/find_rules'; export interface TagType { @@ -40,23 +40,23 @@ export const convertTagsToSet = (tagObjects: object[]): Set => { // then this should be replaced with a an aggregation call. // Ref: https://www.elastic.co/guide/en/kibana/master/saved-objects-api.html export const readTags = async ({ - alertsClient, + rulesClient, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; }): Promise => { - const tags = await readRawTags({ alertsClient }); + const tags = await readRawTags({ rulesClient }); return tags.filter((tag) => !tag.startsWith(INTERNAL_IDENTIFIER)); }; export const readRawTags = async ({ - alertsClient, + rulesClient, }: { - alertsClient: AlertsClient; + rulesClient: RulesClient; perPage?: number; }): Promise => { // Get just one record so we can get the total count const firstTags = await findRules({ - alertsClient, + rulesClient, fields: ['tags'], perPage: 1, page: 1, @@ -66,7 +66,7 @@ export const readRawTags = async ({ }); // Get all the rules to aggregate over all the tags of the rules const rules = await findRules({ - alertsClient, + rulesClient, fields: ['tags'], perPage: firstTags.total, sortField: 'createdAt', diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/helpers.test.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/helpers.test.ts index 2b3eda31916a8..a73aa23e8a86c 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/helpers.test.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/helpers.test.ts @@ -48,7 +48,7 @@ describe('installPrepackagedTimelines', () => { } as unknown) as SecurityPluginSetup; clients.clusterClient.callAsCurrentUser.mockResolvedValue(getNonEmptyIndex()); - clients.alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); + clients.rulesClient.find.mockResolvedValue(getFindResultWithSingleHit()); jest.doMock('./helpers', () => { return { diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 0cf63b94f1758..a850b15869a73 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -5193,8 +5193,8 @@ "xpack.alerting.alertNavigationRegistry.get.missingNavigationError": "「{consumer}」内のアラートタイプ「{alertType}」のナビゲーションは登録されていません。", "xpack.alerting.alertNavigationRegistry.register.duplicateDefaultError": "「{consumer}」内のデフォルトナビゲーションはすでに登録されています。", "xpack.alerting.alertNavigationRegistry.register.duplicateNavigationError": "「{consumer}」内のアラートタイプ「{alertType}」のナビゲーションはすでに登録されています。", - "xpack.alerting.alertsClient.invalidDate": "パラメーター{field}の無効な日付:「{dateValue}」", - "xpack.alerting.alertsClient.validateActions.invalidGroups": "無効なアクショングループ:{groups}", + "xpack.alerting.rulesClient.invalidDate": "パラメーター{field}の無効な日付:「{dateValue}」", + "xpack.alerting.rulesClient.validateActions.invalidGroups": "無効なアクショングループ:{groups}", "xpack.alerting.alertTypeRegistry.get.missingAlertTypeError": "アラートタイプ「{id}」は登録されていません。", "xpack.alerting.alertTypeRegistry.register.customRecoveryActionGroupUsageError": "アラートタイプ [id=\"{id}\"] を登録できません。アクショングループ [{actionGroup}] は、復元とアクティブなアクショングループの両方として使用できません。", "xpack.alerting.alertTypeRegistry.register.duplicateAlertTypeError": "アラートタイプ\"{id}\"はすでに登録されています。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 6659c51867fa6..6b94b5d924519 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -5221,8 +5221,8 @@ "xpack.alerting.alertNavigationRegistry.get.missingNavigationError": "在“{consumer}”内针对告警类型“{alertType}”的导航未注册。", "xpack.alerting.alertNavigationRegistry.register.duplicateDefaultError": "“{consumer}”内的默认导航已注册。", "xpack.alerting.alertNavigationRegistry.register.duplicateNavigationError": "在“{consumer}”内针对告警类型“{alertType}”的导航已注册。", - "xpack.alerting.alertsClient.invalidDate": "参数 {field} 的日期无效:“{dateValue}”", - "xpack.alerting.alertsClient.validateActions.invalidGroups": "无效操作组:{groups}", + "xpack.alerting.rulesClient.invalidDate": "参数 {field} 的日期无效:“{dateValue}”", + "xpack.alerting.rulesClient.validateActions.invalidGroups": "无效操作组:{groups}", "xpack.alerting.alertTypeRegistry.get.missingAlertTypeError": "未注册告警类型“{id}”。", "xpack.alerting.alertTypeRegistry.register.customRecoveryActionGroupUsageError": "无法注册告警类型 [id=\"{id}\"]。操作组 [{actionGroup}] 无法同时用作恢复和活动操作组。", "xpack.alerting.alertTypeRegistry.register.duplicateAlertTypeError": "已注册告警类型“{id}”。", diff --git a/x-pack/plugins/uptime/server/lib/requests/get_monitor_details.ts b/x-pack/plugins/uptime/server/lib/requests/get_monitor_details.ts index 03587e9ed622e..14f0404a02185 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_monitor_details.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_monitor_details.ts @@ -14,16 +14,16 @@ export interface GetMonitorDetailsParams { monitorId: string; dateStart: string; dateEnd: string; - alertsClient: any; + rulesClient: any; } const getMonitorAlerts = async ({ uptimeEsClient, - alertsClient, + rulesClient, monitorId, }: { uptimeEsClient: UptimeESClient; - alertsClient: any; + rulesClient: any; monitorId: string; }) => { const options: any = { @@ -34,7 +34,7 @@ const getMonitorAlerts = async ({ sortField: 'name.keyword', }; - const { data } = await alertsClient.find({ options }); + const { data } = await rulesClient.find({ options }); const monitorAlerts = []; for (let i = 0; i < data.length; i++) { const currAlert = data[i]; @@ -85,7 +85,7 @@ const getMonitorAlerts = async ({ export const getMonitorDetails: UMElasticsearchQueryFn< GetMonitorDetailsParams, MonitorDetails -> = async ({ uptimeEsClient, monitorId, dateStart, dateEnd, alertsClient }) => { +> = async ({ uptimeEsClient, monitorId, dateStart, dateEnd, rulesClient }) => { const queryFilters: any = [ { range: { @@ -133,7 +133,7 @@ export const getMonitorDetails: UMElasticsearchQueryFn< const errorTimestamp: string | undefined = data?.['@timestamp']; const monAlerts = await getMonitorAlerts({ uptimeEsClient, - alertsClient, + rulesClient, monitorId, }); diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts index eefde90677312..50712153a5fea 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts @@ -24,14 +24,14 @@ export const createGetMonitorDetailsRoute: UMRestApiRouteFactory = (libs: UMServ handler: async ({ uptimeEsClient, context, request }): Promise => { const { monitorId, dateStart, dateEnd } = request.query; - const alertsClient = context.alerting?.getAlertsClient(); + const rulesClient = context.alerting?.getRulesClient(); return await libs.requests.getMonitorDetails({ uptimeEsClient, monitorId, dateStart, dateEnd, - alertsClient, + rulesClient, }); }, }); From 8a93d90bf5d9378fb8b60fd77c04d094c3107599 Mon Sep 17 00:00:00 2001 From: Yuliia Naumenko Date: Wed, 21 Jul 2021 15:06:43 +0300 Subject: [PATCH 2/4] fixed path --- .../alerting/server/rules_client_conflict_retries.test.ts | 2 +- x-pack/plugins/alerting/server/rules_client_factory.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts index deded9eee81cf..6c82fa6798107 100644 --- a/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts @@ -18,7 +18,7 @@ import { AlertingAuthorization } from './authorization/alerting_authorization'; import { ActionsAuthorization } from '../../actions/server'; import { SavedObjectsErrorHelpers } from '../../../../src/core/server'; import { RetryForConflictsAttempts } from './lib/retry_if_conflicts'; -import { TaskStatus } from '../../../plugins/task_manager/server/task'; +import { TaskStatus } from '../../task_manager/server/task'; import { RecoveredActionGroup } from '../common'; let rulesClient: RulesClient; diff --git a/x-pack/plugins/alerting/server/rules_client_factory.test.ts b/x-pack/plugins/alerting/server/rules_client_factory.test.ts index 0c259d8080761..17f26929c4a99 100644 --- a/x-pack/plugins/alerting/server/rules_client_factory.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.test.ts @@ -16,7 +16,7 @@ import { loggingSystemMock, } from '../../../../src/core/server/mocks'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; -import { AuthenticatedUser } from '../../../plugins/security/common/model'; +import { AuthenticatedUser } from '../../security/common/model'; import { securityMock } from '../../security/server/mocks'; import { PluginStartContract as ActionsStartContract } from '../../actions/server'; import { actionsMock, actionsAuthorizationMock } from '../../actions/server/mocks'; From 771f6c40ca0d13de9db677c92b5b473f23c60912 Mon Sep 17 00:00:00 2001 From: Yuliia Naumenko Date: Wed, 21 Jul 2021 17:34:47 +0300 Subject: [PATCH 3/4] fixed type checks --- .../server/rules_client/tests/create.test.ts | 4 ++-- .../server/rules_client/tests/get.test.ts | 8 ++++---- .../server/rules_client/tests/update.test.ts | 2 +- .../server/task_runner/task_runner.test.ts | 18 +++++++++--------- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts index 5b0e157d40cb8..1a5032e14214e 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts @@ -900,7 +900,7 @@ describe('create()', () => { }, references: [], }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(extractReferencesFn).toHaveBeenCalledWith(ruleParams); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( @@ -1077,7 +1077,7 @@ describe('create()', () => { }, references: [], }); - const result = await alertsClient.create({ data }); + const result = await rulesClient.create({ data }); expect(extractReferencesFn).toHaveBeenCalledWith(ruleParams); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts index dce9a654f5ce3..22e8631f6f181 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts @@ -139,7 +139,7 @@ describe('get()', () => { injectReferences: injectReferencesFn, }, })); - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -176,7 +176,7 @@ describe('get()', () => { }, ], }); - const result = await alertsClient.get({ id: '1' }); + const result = await rulesClient.get({ id: '1' }); expect(injectReferencesFn).toHaveBeenCalledWith( { @@ -259,7 +259,7 @@ describe('get()', () => { injectReferences: injectReferencesFn, }, })); - const alertsClient = new AlertsClient(alertsClientParams); + const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -296,7 +296,7 @@ describe('get()', () => { }, ], }); - await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(rulesClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Error injecting reference into rule params for rule id 1 - something went wrong!"` ); }); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts index 9e1054d25b811..8880b4e2cd0c8 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts @@ -482,7 +482,7 @@ describe('update()', () => { }, ], }); - const result = await alertsClient.update({ + const result = await rulesClient.update({ id: '1', data: { schedule: { interval: '10s' }, diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts index 0a78a921f7528..84e37f7e681fa 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts @@ -373,7 +373,7 @@ describe('Task Runner', () => { mockedTaskInstance, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -808,7 +808,7 @@ describe('Task Runner', () => { mockedTaskInstance, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, mutedInstanceIds: ['2'], }); @@ -1055,7 +1055,7 @@ describe('Task Runner', () => { }, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', }); @@ -1122,7 +1122,7 @@ describe('Task Runner', () => { }, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, notifyWhen: 'onActionGroupChange', }); @@ -1170,7 +1170,7 @@ describe('Task Runner', () => { mockedTaskInstance, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -1480,7 +1480,7 @@ describe('Task Runner', () => { }, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', @@ -1839,7 +1839,7 @@ describe('Task Runner', () => { }, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: alertId, type: 'alert', @@ -1940,7 +1940,7 @@ describe('Task Runner', () => { }, customTaskRunnerFactoryInitializerParams ); - rulesClient.get.mockResolvedValue({ + rulesClient.get.mockResolvedValue({ ...mockedAlertTypeSavedObject, actions: [ { @@ -4220,7 +4220,7 @@ describe('Task Runner', () => { supportsEphemeralTasks: true, } ); - alertsClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ id: '1', type: 'alert', From 8bcda1520c5c62ccaed4b9ec393f64e663520cf3 Mon Sep 17 00:00:00 2001 From: Yuliia Naumenko Date: Thu, 22 Jul 2021 10:06:11 +0300 Subject: [PATCH 4/4] fixed type checks --- .../alerting/server/rules_client/tests/find.test.ts | 8 ++++---- .../routes/rules/add_prepackaged_rules_route.test.ts | 4 ++-- .../routes/rules/add_prepackaged_rules_route.ts | 1 + 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts index 7f1b6223cec99..39ce62a85127a 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts @@ -319,8 +319,8 @@ describe('find()', () => { }, ], }); - const alertsClient = new AlertsClient(alertsClientParams); - const result = await alertsClient.find({ options: {} }); + const rulesClient = new RulesClient(rulesClientParams); + const result = await rulesClient.find({ options: {} }); expect(injectReferencesFn).toHaveBeenCalledTimes(1); expect(injectReferencesFn).toHaveBeenCalledWith( @@ -514,8 +514,8 @@ describe('find()', () => { }, ], }); - const alertsClient = new AlertsClient(alertsClientParams); - await expect(alertsClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot( + const rulesClient = new RulesClient(rulesClientParams); + await expect(rulesClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot( `"Error injecting reference into rule params for rule id 2 - something went wrong!"` ); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts index c551eaddc3e62..102d799984d15 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts @@ -107,14 +107,14 @@ describe('add_prepackaged_rules_route', () => { }); describe('status codes', () => { - test('returns 200 when creating with a valid actionClient and alertClient', async () => { + test('returns 200 when creating with a valid actionClient and rulesClient', async () => { const request = addPrepackagedRulesRequest(); const response = await server.inject(request, context); expect(response.status).toEqual(200); }); - test('returns 404 if alertClient is not available on the route', async () => { + test('returns 404 if rulesClient is not available on the route', async () => { context.alerting!.getRulesClient = jest.fn(); const request = addPrepackagedRulesRequest(); const response = await server.inject(request, context); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 37726a3361ce5..48a847474eeed 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -130,6 +130,7 @@ export const createPrepackagedRules = async ( prebuiltRulesFromFileSystem, prebuiltRulesFromSavedObjects ); + const prepackagedRules = await getExistingPrepackagedRules({ rulesClient }); const rulesToInstall = getRulesToInstall(latestPrepackagedRules, prepackagedRules); const rulesToUpdate = getRulesToUpdate(latestPrepackagedRules, prepackagedRules); const signalsIndex = siemClient.getSignalsIndex();