From 74b1e12674dfb181507ddaa6a50f5449c2f6af41 Mon Sep 17 00:00:00 2001 From: Ying Mao Date: Mon, 18 Dec 2023 10:07:17 -0500 Subject: [PATCH] [Response Ops][Alerting] Refactoring rule SO const and `partiallyUpdateAlert` -> `partiallyUpdateRule` (#172859) Towards https://github.com/elastic/kibana/issues/168861 ## Summary * Adding `RULE_SAVED_OBJECT_TYPE = 'alert'` and using it everywhere * Rename `partiallyUpdateAlert` fn to `partiallyUpdateRule` Using this const in place of `alert` changed so many files that I limited this PR to just these changes. --------- Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> --- .../methods/aggregate/aggregate_rules.test.ts | 5 +- .../bulk_delete/bulk_delete_rules.test.ts | 57 +++---- .../methods/bulk_delete/bulk_delete_rules.ts | 5 +- .../bulk_disable/bulk_disable_rules.test.ts | 9 +- .../bulk_disable/bulk_disable_rules.ts | 5 +- .../methods/bulk_edit/bulk_edit_rules.test.ts | 71 ++++----- .../rule/methods/bulk_edit/bulk_edit_rules.ts | 3 +- .../rule/methods/create/create_rule.test.ts | 101 ++++++------- .../rule/methods/create/create_rule.ts | 3 +- .../get_schedule_frequency.ts | 3 +- .../rule/methods/mute_alert/mute_instance.ts | 7 +- .../rule/methods/resolve/resolve_rule.ts | 5 +- .../rule/methods/snooze/snooze_rule.ts | 5 +- .../rule/methods/tags/get_rule_tags.test.ts | 3 +- .../rule/methods/unsnooze/unsnooze_rule.ts | 5 +- .../data/rule/methods/bulk_delete_rules_so.ts | 3 +- .../data/rule/methods/create_rule_so.ts | 7 +- .../data/rule/methods/delete_rule_so.ts | 3 +- .../server/data/rule/methods/find_rules_so.ts | 3 +- .../server/data/rule/methods/get_rule_so.ts | 3 +- .../data/rule/methods/resolve_rule_so.ts | 3 +- .../data/rule/methods/update_rule_so.ts | 3 +- .../alerting/server/health/get_health.test.ts | 11 +- .../alerting/server/health/get_health.ts | 13 +- x-pack/plugins/alerting/server/index.ts | 1 + .../alerting_event_logger.ts | 9 +- .../server/lib/is_alerting_error.test.ts | 8 +- .../server/lib/retry_if_conflicts.test.ts | 7 +- x-pack/plugins/alerting/server/plugin.ts | 18 ++- .../routes/get_action_error_log.test.ts | 5 +- .../routes/get_rule_alert_summary.test.ts | 5 +- .../routes/get_rule_execution_kpi.test.ts | 5 +- .../server/routes/get_rule_state.test.ts | 5 +- .../legacy/get_alert_instance_summary.test.ts | 5 +- .../routes/legacy/get_alert_state.test.ts | 5 +- .../rules_client/common/audit_events.test.ts | 7 +- .../retry_if_bulk_edit_conflicts.test.ts | 17 ++- .../common/retry_if_bulk_edit_conflicts.ts | 3 +- .../common/validate_attributes.ts | 6 +- .../lib/check_authorization_and_get_total.ts | 3 +- .../lib/create_rule_saved_object.ts | 3 +- .../rules_client/lib/get_rule_saved_object.ts | 3 +- .../lib/increment_revision.test.ts | 3 +- .../lib/resolve_rule_saved_object.ts | 3 +- .../format_legacy_actions.test.ts | 19 +-- .../format_legacy_actions.ts | 5 +- .../retrieve_migrated_legacy_actions.mock.ts | 11 +- .../retrieve_migrated_legacy_actions.ts | 5 +- .../transform_legacy_actions.test.ts | 3 +- .../rules_client/lib/untrack_rule_alerts.ts | 3 +- .../rules_client/methods/bulk_enable.ts | 5 +- .../methods/clear_expired_snoozes.ts | 4 +- .../server/rules_client/methods/clone.ts | 17 ++- .../server/rules_client/methods/delete.ts | 22 ++- .../server/rules_client/methods/disable.ts | 22 ++- .../server/rules_client/methods/enable.ts | 35 +++-- .../server/rules_client/methods/find.ts | 7 +- .../server/rules_client/methods/get.ts | 7 +- .../methods/get_action_error_log.ts | 11 +- .../rules_client/methods/get_alert_summary.ts | 5 +- .../rules_client/methods/get_execution_kpi.ts | 9 +- .../rules_client/methods/get_execution_log.ts | 9 +- .../server/rules_client/methods/mute_all.ts | 10 +- .../server/rules_client/methods/run_soon.ts | 10 +- .../server/rules_client/methods/unmute_all.ts | 10 +- .../rules_client/methods/unmute_instance.ts | 9 +- .../server/rules_client/methods/update.ts | 22 ++- .../rules_client/methods/update_api_key.ts | 24 ++- .../rules_client/tests/bulk_enable.test.ts | 5 +- .../tests/clear_expired_snoozes.test.ts | 7 +- .../server/rules_client/tests/delete.test.ts | 23 +-- .../server/rules_client/tests/disable.test.ts | 85 +++++++---- .../server/rules_client/tests/enable.test.ts | 141 ++++++++++++------ .../server/rules_client/tests/find.test.ts | 23 +-- .../server/rules_client/tests/get.test.ts | 23 +-- .../tests/get_action_error_log.test.ts | 21 +-- .../tests/get_alert_state.test.ts | 7 +- .../tests/get_alert_summary.test.ts | 3 +- .../tests/get_execution_log.test.ts | 15 +- .../alerting/server/rules_client/tests/lib.ts | 3 +- .../rules_client/tests/mute_all.test.ts | 15 +- .../rules_client/tests/mute_instance.test.ts | 19 +-- .../server/rules_client/tests/resolve.test.ts | 21 +-- .../rules_client/tests/run_soon.test.ts | 7 +- .../server/rules_client/tests/test_helpers.ts | 5 +- .../rules_client/tests/unmute_all.test.ts | 15 +- .../tests/unmute_instance.test.ts | 19 +-- .../server/rules_client/tests/update.test.ts | 103 +++++++------ .../rules_client/tests/update_api_key.test.ts | 57 ++++--- .../rules_client_conflict_retries.test.ts | 23 +-- .../server/rules_client_factory.test.ts | 5 +- .../alerting/server/rules_client_factory.ts | 3 +- .../saved_objects/get_import_warnings.test.ts | 5 +- .../alerting/server/saved_objects/index.ts | 18 ++- .../saved_objects/is_rule_exportable.test.ts | 7 +- .../saved_objects/migrations/7.16/index.ts | 5 +- .../saved_objects/migrations/index.test.ts | 19 +-- ....test.ts => partially_update_rule.test.ts} | 68 ++++++--- ...date_alert.ts => partially_update_rule.ts} | 29 ++-- .../transform_rule_for_export.test.ts | 5 +- .../task_runner/execution_handler.test.ts | 11 +- .../server/task_runner/execution_handler.ts | 5 +- .../alerting/server/task_runner/fixtures.ts | 9 +- .../server/task_runner/rule_loader.test.ts | 5 +- .../server/task_runner/rule_loader.ts | 3 +- .../task_runner/running_handler.test.ts | 26 ++-- .../server/task_runner/running_handler.ts | 4 +- .../server/task_runner/task_runner.test.ts | 6 +- .../server/task_runner/task_runner.ts | 6 +- .../task_runner/task_runner_cancel.test.ts | 3 +- x-pack/plugins/alerting/server/usage/task.ts | 3 +- .../common/plugins/aad/server/plugin.ts | 3 +- .../common/plugins/alerts/server/plugin.ts | 5 +- .../common/plugins/alerts/server/routes.ts | 21 +-- .../alerts_restricted/server/plugin.ts | 3 +- .../group1/tests/alerting/create.ts | 3 +- .../group1/tests/alerting/disable.ts | 3 +- .../group1/tests/alerting/enable.ts | 5 +- .../group2/tests/actions/get_all.ts | 3 +- .../group2/tests/alerting/mute_all.ts | 9 +- .../group2/tests/alerting/mute_instance.ts | 9 +- .../group2/tests/alerting/rbac_legacy.ts | 11 +- .../group2/tests/alerting/unmute_all.ts | 9 +- .../group2/tests/alerting/unmute_instance.ts | 9 +- .../group2/tests/alerting/update.ts | 11 +- .../group2/tests/alerting/update_api_key.ts | 11 +- .../group3/tests/alerting/bulk_edit.ts | 3 +- .../group3/tests/alerting/clone.ts | 3 +- .../tests/alerting/user_managed_api_key.ts | 25 ++-- .../group4/tests/alerting/alerts.ts | 3 +- .../group4/tests/alerting/event_log.ts | 5 +- .../group4/tests/alerting/snooze.ts | 11 +- .../group4/tests/alerting/unsnooze.ts | 9 +- .../tests/alerting/group1/create.ts | 11 +- .../tests/alerting/group1/disable.ts | 14 +- .../tests/alerting/group1/enable.ts | 5 +- .../tests/alerting/group1/event_log.ts | 29 +++- .../tests/alerting/group2/execution_status.ts | 9 +- .../tests/alerting/group2/mute_all.ts | 5 +- .../tests/alerting/group2/mute_instance.ts | 5 +- .../tests/alerting/group2/unmute_all.ts | 5 +- .../tests/alerting/group2/unmute_instance.ts | 5 +- .../tests/alerting/group2/update.ts | 5 +- .../tests/alerting/group2/update_api_key.ts | 5 +- .../tests/alerting/group4/bulk_edit.ts | 13 +- .../tests/alerting/group4/migrations.ts | 3 +- .../tests/alerting/group4/snooze.ts | 7 +- .../tests/alerting/group4/unsnooze.ts | 3 +- .../test_suites/common/alerting/rules.ts | 3 +- x-pack/test_serverless/tsconfig.json | 1 + 150 files changed, 1163 insertions(+), 765 deletions(-) rename x-pack/plugins/alerting/server/saved_objects/{partially_update_alert.test.ts => partially_update_rule.test.ts} (61%) rename x-pack/plugins/alerting/server/saved_objects/{partially_update_alert.ts => partially_update_rule.ts} (63%) diff --git a/x-pack/plugins/alerting/server/application/rule/methods/aggregate/aggregate_rules.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/aggregate/aggregate_rules.test.ts index 31df2212bb5b5..d230f18f7ea60 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/aggregate/aggregate_rules.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/aggregate/aggregate_rules.test.ts @@ -26,6 +26,7 @@ import { fromKueryExpression, nodeTypes } from '@kbn/es-query'; import { RecoveredActionGroup } from '../../../../../common'; import { DefaultRuleAggregationResult } from '../../../../routes/rule/apis/aggregate/types'; import { defaultRuleAggregationFactory } from '.'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -289,7 +290,7 @@ describe('aggregate()', () => { filter: undefined, page: 1, perPage: 0, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, aggs: { status: { terms: { field: 'alert.attributes.executionStatus.status' }, @@ -350,7 +351,7 @@ describe('aggregate()', () => { ]), page: 1, perPage: 0, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, aggs: { status: { terms: { field: 'alert.attributes.executionStatus.status' }, diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.test.ts index d5f18db2f1065..c3cbfd340984c 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.test.ts @@ -30,6 +30,7 @@ import { siemRuleForBulkOps1, } from '../../../../rules_client/tests/test_helpers'; import { migrateLegacyActions } from '../../../../rules_client/lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; jest.mock('../../../../rules_client/lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -85,7 +86,7 @@ const rulesClientParams: jest.Mocked = { const getBulkOperationStatusErrorResponse = (statusCode: number) => ({ id: 'id2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, success: false, error: { error: '', @@ -164,9 +165,9 @@ describe('bulkDelete', () => { test('should try to delete rules, two successful and one with 500 error', async () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, getBulkOperationStatusErrorResponse(500), - { id: 'id3', type: 'alert', success: true }, + { id: 'id3', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); @@ -176,7 +177,7 @@ describe('bulkDelete', () => { expect(unsecuredSavedObjectsClient.bulkDelete).toHaveBeenCalledWith( [enabledRuleForBulkOps1, enabledRuleForBulkOps2, enabledRuleForBulkOps3].map(({ id }) => ({ id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, })), undefined ); @@ -201,7 +202,7 @@ describe('bulkDelete', () => { unsecuredSavedObjectsClient.bulkDelete .mockResolvedValueOnce({ statuses: [ - { id: 'id1', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, getBulkOperationStatusErrorResponse(409), ], }) @@ -265,7 +266,7 @@ describe('bulkDelete', () => { unsecuredSavedObjectsClient.bulkDelete .mockResolvedValueOnce({ statuses: [ - { id: 'id1', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, getBulkOperationStatusErrorResponse(409), ], }) @@ -273,7 +274,7 @@ describe('bulkDelete', () => { statuses: [ { id: 'id2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, success: true, }, ], @@ -356,9 +357,9 @@ describe('bulkDelete', () => { test('should not mark API keys for invalidation if the user is authenticated using an api key', async () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id3', type: 'alert', success: true }, - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: true }, + { id: 'id3', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); @@ -376,15 +377,15 @@ describe('bulkDelete', () => { test('should return task id if deleting task failed', async () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); taskManager.bulkRemove.mockImplementation(async () => ({ statuses: [ { id: 'id1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, success: true, }, getBulkOperationStatusErrorResponse(500), @@ -404,8 +405,8 @@ describe('bulkDelete', () => { test('should not throw an error if taskManager throw an error', async () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); taskManager.bulkRemove.mockImplementation(() => { @@ -424,20 +425,20 @@ describe('bulkDelete', () => { mockCreatePointInTimeFinderAsInternalUser(); unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); taskManager.bulkRemove.mockImplementation(async () => ({ statuses: [ { id: 'id1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, success: true, }, { id: 'id2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, success: true, }, ], @@ -468,9 +469,9 @@ describe('bulkDelete', () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: enabledRuleForBulkOps1.id, type: 'alert', success: true }, - { id: enabledRuleForBulkOps2.id, type: 'alert', success: true }, - { id: siemRuleForBulkOps1.id, type: 'alert', success: true }, + { id: enabledRuleForBulkOps1.id, type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: enabledRuleForBulkOps2.id, type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: siemRuleForBulkOps1.id, type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); @@ -501,8 +502,8 @@ describe('bulkDelete', () => { test('logs audit event when deleting rules', async () => { unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: true }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: true }, ], }); @@ -511,12 +512,12 @@ describe('bulkDelete', () => { expect(auditLogger.log.mock.calls[0][0]?.event?.action).toEqual('rule_delete'); expect(auditLogger.log.mock.calls[0][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[0][0]?.kibana).toEqual({ - saved_object: { id: 'id1', type: 'alert' }, + saved_object: { id: 'id1', type: RULE_SAVED_OBJECT_TYPE }, }); expect(auditLogger.log.mock.calls[1][0]?.event?.action).toEqual('rule_delete'); expect(auditLogger.log.mock.calls[1][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[1][0]?.kibana).toEqual({ - saved_object: { id: 'id2', type: 'alert' }, + saved_object: { id: 'id2', type: RULE_SAVED_OBJECT_TYPE }, }); }); @@ -525,7 +526,7 @@ describe('bulkDelete', () => { throw new Error('Unauthorized'); }); unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ - statuses: [{ id: 'id1', type: 'alert', success: true }], + statuses: [{ id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }], }); await expect(rulesClient.bulkDeleteRules({ filter: 'fake_filter' })).rejects.toThrowError( @@ -541,7 +542,7 @@ describe('bulkDelete', () => { throw new Error('Error'); }); unsecuredSavedObjectsClient.bulkDelete.mockResolvedValue({ - statuses: [{ id: 'id1', type: 'alert', success: true }], + statuses: [{ id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }], }); await expect(rulesClient.bulkDeleteRules({ filter: 'fake_filter' })).rejects.toThrowError( diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.ts index 33da0fd6b2e07..429afed34926c 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_delete/bulk_delete_rules.ts @@ -9,6 +9,7 @@ import Boom from '@hapi/boom'; import { KueryNode, nodeBuilder } from '@kbn/es-query'; import { SavedObjectsBulkUpdateObject } from '@kbn/core/server'; import { withSpan } from '@kbn/apm-utils'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { convertRuleIdsToKueryNode } from '../../../../lib'; import { bulkMarkApiKeysForInvalidation } from '../../../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation'; import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events'; @@ -136,7 +137,7 @@ const bulkDeleteWithOCC = async ( context.encryptedSavedObjectsClient.createPointInTimeFinderDecryptedAsInternalUser( { filter, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, perPage: 100, ...(context.namespace ? { namespaces: [context.namespace] } : undefined), } @@ -168,7 +169,7 @@ const bulkDeleteWithOCC = async ( ruleAuditEvent({ action: RuleAuditAction.DELETE, outcome: 'unknown', - savedObject: { type: 'alert', id: rule.id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: rule.id }, }) ); } diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.test.ts index f7e8eff33591f..2b7c72fd4c51b 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.test.ts @@ -35,6 +35,7 @@ import { siemRuleForBulkOps2, } from '../../../../rules_client/tests/test_helpers'; import { migrateLegacyActions } from '../../../../rules_client/lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; jest.mock('../../../../task_runner/alert_task_instance', () => ({ taskInstanceToAlertTaskInstance: jest.fn(), @@ -428,8 +429,8 @@ describe('bulkDisableRules', () => { taskManager.bulkRemove.mockResolvedValue({ statuses: [ - { id: 'id1', type: 'alert', success: true }, - { id: 'id2', type: 'alert', success: false }, + { id: 'id1', type: RULE_SAVED_OBJECT_TYPE, success: true }, + { id: 'id2', type: RULE_SAVED_OBJECT_TYPE, success: false }, ], }); @@ -543,12 +544,12 @@ describe('bulkDisableRules', () => { expect(auditLogger.log.mock.calls[0][0]?.event?.action).toEqual('rule_disable'); expect(auditLogger.log.mock.calls[0][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[0][0]?.kibana).toEqual({ - saved_object: { id: 'id1', type: 'alert' }, + saved_object: { id: 'id1', type: RULE_SAVED_OBJECT_TYPE }, }); expect(auditLogger.log.mock.calls[1][0]?.event?.action).toEqual('rule_disable'); expect(auditLogger.log.mock.calls[1][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[1][0]?.kibana).toEqual({ - saved_object: { id: 'id2', type: 'alert' }, + saved_object: { id: 'id2', type: RULE_SAVED_OBJECT_TYPE }, }); }); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.ts index e981a30181a49..0ac84ce2ef6d7 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_disable/bulk_disable_rules.ts @@ -11,6 +11,7 @@ import { withSpan } from '@kbn/apm-utils'; import pMap from 'p-map'; import { Logger } from '@kbn/core/server'; import { TaskManagerStartContract } from '@kbn/task-manager-plugin/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import type { RawRule, SanitizedRule, RawRuleAction } from '../../../../types'; import { convertRuleIdsToKueryNode } from '../../../../lib'; import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events'; @@ -132,7 +133,7 @@ const bulkDisableRulesWithOCC = async ( context.encryptedSavedObjectsClient.createPointInTimeFinderDecryptedAsInternalUser( { filter: filter ? nodeBuilder.and([filter, additionalFilter]) : additionalFilter, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, perPage: 100, ...(context.namespace ? { namespaces: [context.namespace] } : undefined), } @@ -200,7 +201,7 @@ const bulkDisableRulesWithOCC = async ( ruleAuditEvent({ action: RuleAuditAction.DISABLE, outcome: 'unknown', - savedObject: { type: 'alert', id: rule.id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: rule.id }, }) ); } catch (error) { diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.test.ts index 38a04fbd76c76..dbd056bb1df30 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.test.ts @@ -35,6 +35,7 @@ import { } from '../../../../rules_client/tests/test_helpers'; import { migrateLegacyActions } from '../../../../rules_client/lib'; import { migrateLegacyActionsMock } from '../../../../rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; jest.mock('../../../../rules_client/lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -121,7 +122,7 @@ describe('bulkEdit()', () => { let actionsClient: jest.Mocked; const existingRule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, tags: ['foo'], @@ -269,7 +270,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo', 'test-1'], @@ -314,7 +315,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: ['foo', 'test-1'], revision: 1, @@ -330,7 +331,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: [], @@ -371,7 +372,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: [], revision: 1, @@ -387,7 +388,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['test-1', 'test-2'], @@ -429,7 +430,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: ['test-1', 'test-2'], revision: 1, @@ -931,7 +932,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -982,7 +983,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ params: expect.objectContaining({ index: ['test-1', 'test-2', 'test-4', 'test-5'], @@ -1000,7 +1001,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -1046,7 +1047,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ params: expect.objectContaining({ index: ['test-1'], @@ -1104,7 +1105,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo', 'test-1'], @@ -1149,7 +1150,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ snoozeSchedule: [snoozePayload], revision: 0, @@ -1180,7 +1181,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ revision: 0, snoozeSchedule: [snoozePayload], @@ -1226,7 +1227,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ revision: 0, snoozeSchedule: [...existingSnooze, snoozePayload], @@ -1271,7 +1272,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ muteAll: true, revision: 0, @@ -1316,7 +1317,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ revision: 0, snoozeSchedule: [existingSnooze[1], existingSnooze[2]], @@ -1361,7 +1362,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ revision: 0, snoozeSchedule: [], @@ -1406,7 +1407,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ revision: 0, snoozeSchedule: [existingSnooze[0]], @@ -1525,7 +1526,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo', 'test-1'], @@ -1578,7 +1579,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: ['foo', 'test-1'], params: { @@ -1597,7 +1598,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo', 'test-1'], @@ -1651,7 +1652,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: ['foo', 'test-1'], params: { @@ -1670,7 +1671,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -1724,7 +1725,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ tags: ['foo'], params: { @@ -1814,7 +1815,7 @@ describe('bulkEdit()', () => { }, page: 1, perPage: 0, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); }); test('should call unsecuredSavedObjectsClient.find for aggregations when called with ids options', async () => { @@ -1884,7 +1885,7 @@ describe('bulkEdit()', () => { }, page: 1, perPage: 0, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); }); test('should throw if number of matched rules greater than 10_000', async () => { @@ -2032,7 +2033,7 @@ describe('bulkEdit()', () => { type: 'function', }, perPage: 100, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, namespaces: ['default'], }); }); @@ -2087,7 +2088,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -2228,7 +2229,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -2489,7 +2490,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo', 'test-1'], @@ -2551,7 +2552,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -2593,7 +2594,7 @@ describe('bulkEdit()', () => { [ expect.objectContaining({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: expect.objectContaining({ params: expect.objectContaining({ index: ['test-index-*'], @@ -2632,7 +2633,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -2675,7 +2676,7 @@ describe('bulkEdit()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], diff --git a/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.ts b/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.ts index 996f67448c7f8..d9ff12bf9d3f3 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/bulk_edit/bulk_edit_rules.ts @@ -15,6 +15,7 @@ import { SavedObjectsFindResult, SavedObjectsUpdateResponse, } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { BulkActionSkipResult } from '../../../../../common/bulk_edit'; import { RuleTypeRegistry } from '../../../../types'; import { @@ -279,7 +280,7 @@ async function bulkEditRulesOcc( await context.encryptedSavedObjectsClient.createPointInTimeFinderDecryptedAsInternalUser( { filter, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, perPage: 100, ...(context.namespace ? { namespaces: [context.namespace] } : undefined), } diff --git a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts index 4fcb2b0d55716..ca2ccc98ea292 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts @@ -27,6 +27,7 @@ import { getBeforeSetup, setGlobalDate } from '../../../../rules_client/tests/li import { RecoveredActionGroup } from '../../../../../common'; import { bulkMarkApiKeysForInvalidation } from '../../../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation'; import { getRuleExecutionStatusPending, getDefaultMonitoring } from '../../../../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; jest.mock('../../../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation', () => ({ bulkMarkApiKeysForInvalidation: jest.fn(), @@ -174,7 +175,7 @@ describe('create()', () => { ): Promise { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -206,7 +207,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -270,7 +271,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { ...data, executionStatus: getRuleExecutionStatusPending('2019-02-12T21:01:22.479Z'), @@ -285,7 +286,7 @@ describe('create()', () => { action: 'rule_create', outcome: 'unknown', }), - kibana: { saved_object: { id: 'mock-saved-object-id', type: 'alert' } }, + kibana: { saved_object: { id: 'mock-saved-object-id', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -310,7 +311,7 @@ describe('create()', () => { kibana: { saved_object: { id: 'mock-saved-object-id', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -351,7 +352,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { ...createdAttributes, running: false, @@ -367,7 +368,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { ...createdAttributes, running: false, @@ -433,7 +434,7 @@ describe('create()', () => { `); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -543,7 +544,7 @@ describe('create()', () => { `); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(4); - expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1'); expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` Object { @@ -582,7 +583,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { ...createdAttributes, running: false, @@ -646,7 +647,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { ...createdAttributes, running: false, @@ -798,7 +799,7 @@ describe('create()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { running: false, executionStatus: getRuleExecutionStatusPending('2019-02-12T21:01:22.479Z'), @@ -857,7 +858,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -1000,7 +1001,7 @@ describe('create()', () => { actionsClient.isPreconfigured.mockReturnValueOnce(false); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { executionStatus: getRuleExecutionStatusPending('2019-02-12T21:01:22.479Z'), alertTypeId: '123', @@ -1054,7 +1055,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -1110,7 +1111,7 @@ describe('create()', () => { } `); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -1261,7 +1262,7 @@ describe('create()', () => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { executionStatus: getRuleExecutionStatusPending('2019-02-12T21:01:22.479Z'), alertTypeId: '123', @@ -1314,7 +1315,7 @@ describe('create()', () => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -1371,7 +1372,7 @@ describe('create()', () => { `); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -1444,7 +1445,7 @@ describe('create()', () => { const data = getMockData({ enabled: false }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, alertTypeId: '123', @@ -1561,7 +1562,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -1600,7 +1601,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -1611,7 +1612,7 @@ describe('create()', () => { expect(extractReferencesFn).toHaveBeenCalledWith(ruleParams); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -1750,7 +1751,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -1789,7 +1790,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -1800,7 +1801,7 @@ describe('create()', () => { expect(extractReferencesFn).toHaveBeenCalledWith(ruleParams); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -1894,7 +1895,7 @@ describe('create()', () => { const data = getMockData({ name: ' my alert name ' }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, name: ' my alert name ', @@ -1963,7 +1964,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: createdAttributes, references: [ { @@ -1975,7 +1976,7 @@ describe('create()', () => { }); const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -2104,7 +2105,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: createdAttributes, references: [ { @@ -2116,7 +2117,7 @@ describe('create()', () => { }); const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -2245,7 +2246,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: createdAttributes, references: [ { @@ -2257,7 +2258,7 @@ describe('create()', () => { }); const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -2394,7 +2395,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: createdAttributes, references: [ { @@ -2408,7 +2409,7 @@ describe('create()', () => { const result = await rulesClient.create({ data }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { enabled: true, name: 'abc', @@ -2607,7 +2608,7 @@ describe('create()', () => { const data = getMockData(); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -2656,7 +2657,7 @@ describe('create()', () => { const data = getMockData(); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -2703,7 +2704,7 @@ describe('create()', () => { const data = getMockData(); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -2761,7 +2762,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -2791,7 +2792,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -2808,7 +2809,7 @@ describe('create()', () => { expect(rulesClientParams.createAPIKey).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -2866,7 +2867,7 @@ describe('create()', () => { const data = getMockData({ enabled: false }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -2896,7 +2897,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -2913,7 +2914,7 @@ describe('create()', () => { expect(rulesClientParams.createAPIKey).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -3070,7 +3071,7 @@ describe('create()', () => { }; unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: createdAttributes, references: [ { @@ -3534,7 +3535,7 @@ describe('create()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -3576,7 +3577,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -3744,7 +3745,7 @@ describe('create()', () => { rulesClientParams.isAuthenticationTypeAPIKey.mockReturnValueOnce(true); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '1m' }, @@ -3774,7 +3775,7 @@ describe('create()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'task-123', @@ -3792,7 +3793,7 @@ describe('create()', () => { expect(rulesClientParams.isAuthenticationTypeAPIKey).toHaveBeenCalledTimes(1); expect(rulesClientParams.getAuthenticationAPIKey).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { diff --git a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.ts b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.ts index 74dd0775d0c22..bdd11da2483f7 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.ts @@ -8,6 +8,7 @@ import Semver from 'semver'; import Boom from '@hapi/boom'; import { SavedObject, SavedObjectsUtils } from '@kbn/core/server'; import { withSpan } from '@kbn/apm-utils'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { parseDuration, getRuleCircuitBreakerErrorMessage } from '../../../../../common'; import { WriteOperations, AlertingAuthorizationEntity } from '../../../../authorization'; import { @@ -101,7 +102,7 @@ export async function createRule( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.CREATE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/get_schedule_frequency/get_schedule_frequency.ts b/x-pack/plugins/alerting/server/application/rule/methods/get_schedule_frequency/get_schedule_frequency.ts index b670adeccae8a..d30d172113248 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/get_schedule_frequency/get_schedule_frequency.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/get_schedule_frequency/get_schedule_frequency.ts @@ -4,6 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { RulesClientContext } from '../../../../rules_client/types'; import { RuleDomain } from '../../types'; import { convertDurationToFrequency } from '../../../../../common/parse_duration'; @@ -41,7 +42,7 @@ export const getScheduleFrequency = async ( RuleDomain, SchedulesIntervalAggregationResult >({ - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, filter: 'alert.attributes.enabled: true', namespaces: ['*'], aggs: { diff --git a/x-pack/plugins/alerting/server/application/rule/methods/mute_alert/mute_instance.ts b/x-pack/plugins/alerting/server/application/rule/methods/mute_alert/mute_instance.ts index 8adbdf7ae58c9..5758794b550fb 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/mute_alert/mute_instance.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/mute_alert/mute_instance.ts @@ -6,6 +6,7 @@ */ import Boom from '@hapi/boom'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { updateRuleSo } from '../../../../data/rule/methods/update_rule_so'; import { muteAlertParamsSchema } from './schemas'; import type { MuteAlertParams } from './types'; @@ -38,7 +39,7 @@ async function muteInstanceWithOCC( { alertId, alertInstanceId }: MuteAlertParams ) { const { attributes, version } = await context.unsecuredSavedObjectsClient.get( - 'alert', + RULE_SAVED_OBJECT_TYPE, alertId ); @@ -57,7 +58,7 @@ async function muteInstanceWithOCC( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.MUTE_ALERT, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId }, error, }) ); @@ -68,7 +69,7 @@ async function muteInstanceWithOCC( ruleAuditEvent({ action: RuleAuditAction.MUTE_ALERT, outcome: 'unknown', - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId }, }) ); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/resolve/resolve_rule.ts b/x-pack/plugins/alerting/server/application/rule/methods/resolve/resolve_rule.ts index cbde52a44b1fe..de9f421a95924 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/resolve/resolve_rule.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/resolve/resolve_rule.ts @@ -7,6 +7,7 @@ import Boom from '@hapi/boom'; import { withSpan } from '@kbn/apm-utils'; import { AlertConsumers } from '@kbn/rule-data-utils'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { resolveRuleSavedObject } from '../../../../rules_client/lib'; import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events'; import { RuleTypeParams } from '../../../../types'; @@ -52,7 +53,7 @@ Promise> { context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.RESOLVE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -61,7 +62,7 @@ Promise> { context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.RESOLVE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/snooze/snooze_rule.ts b/x-pack/plugins/alerting/server/application/rule/methods/snooze/snooze_rule.ts index b10df195e5b77..162fe98d31f04 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/snooze/snooze_rule.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/snooze/snooze_rule.ts @@ -7,6 +7,7 @@ import Boom from '@hapi/boom'; import { withSpan } from '@kbn/apm-utils'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { getRuleSavedObject } from '../../../../rules_client/lib'; import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events'; import { WriteOperations, AlertingAuthorizationEntity } from '../../../../authorization'; @@ -71,7 +72,7 @@ async function snoozeWithOCC( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.SNOOZE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -82,7 +83,7 @@ async function snoozeWithOCC( ruleAuditEvent({ action: RuleAuditAction.SNOOZE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/tags/get_rule_tags.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/tags/get_rule_tags.test.ts index dd1f3150d0a08..28e9fc08c3b8a 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/tags/get_rule_tags.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/tags/get_rule_tags.test.ts @@ -22,6 +22,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup } from '../../../../rules_client/tests/lib'; import { RecoveredActionGroup } from '../../../../../common'; import { RegistryRuleType } from '../../../../rule_type_registry'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -147,7 +148,7 @@ describe('getTags()', () => { tags: { terms: { field: 'alert.attributes.tags', order: { _key: 'asc' }, size: 10000 } }, }, filter: undefined, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); expect(result.data).toEqual(['a', 'b', 'c']); diff --git a/x-pack/plugins/alerting/server/application/rule/methods/unsnooze/unsnooze_rule.ts b/x-pack/plugins/alerting/server/application/rule/methods/unsnooze/unsnooze_rule.ts index c47b39f28aedb..b5cb6f8f29e33 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/unsnooze/unsnooze_rule.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/unsnooze/unsnooze_rule.ts @@ -7,6 +7,7 @@ import Boom from '@hapi/boom'; import { withSpan } from '@kbn/apm-utils'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects'; import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events'; import { getRuleSavedObject } from '../../../../rules_client/lib'; import { WriteOperations, AlertingAuthorizationEntity } from '../../../../authorization'; @@ -62,7 +63,7 @@ async function unsnoozeWithOCC(context: RulesClientContext, { id, scheduleIds }: context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.UNSNOOZE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -73,7 +74,7 @@ async function unsnoozeWithOCC(context: RulesClientContext, { id, scheduleIds }: ruleAuditEvent({ action: RuleAuditAction.UNSNOOZE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); diff --git a/x-pack/plugins/alerting/server/data/rule/methods/bulk_delete_rules_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/bulk_delete_rules_so.ts index 7f3568f76cf98..15449dc003cd2 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/bulk_delete_rules_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/bulk_delete_rules_so.ts @@ -10,6 +10,7 @@ import { SavedObjectsBulkDeleteOptions, SavedObjectsBulkDeleteResponse, } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; export interface BulkDeleteRulesSoParams { savedObjectsClient: SavedObjectsClientContract; @@ -23,7 +24,7 @@ export const bulkDeleteRulesSo = ( const { savedObjectsClient, ids, savedObjectsBulkDeleteOptions } = params; return savedObjectsClient.bulkDelete( - ids.map((id) => ({ id, type: 'alert' })), + ids.map((id) => ({ id, type: RULE_SAVED_OBJECT_TYPE })), savedObjectsBulkDeleteOptions ); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/create_rule_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/create_rule_so.ts index 7574e9aca1608..b276bb0e2e10d 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/create_rule_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/create_rule_so.ts @@ -10,6 +10,7 @@ import { SavedObjectsCreateOptions, SavedObject, } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAttributes } from '../types'; export interface CreateRuleSoParams { @@ -21,5 +22,9 @@ export interface CreateRuleSoParams { export const createRuleSo = (params: CreateRuleSoParams): Promise> => { const { savedObjectsClient, ruleAttributes, savedObjectsCreateOptions } = params; - return savedObjectsClient.create('alert', ruleAttributes, savedObjectsCreateOptions); + return savedObjectsClient.create( + RULE_SAVED_OBJECT_TYPE, + ruleAttributes, + savedObjectsCreateOptions + ); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/delete_rule_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/delete_rule_so.ts index e3428cfc78f63..7c15fd847303f 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/delete_rule_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/delete_rule_so.ts @@ -6,6 +6,7 @@ */ import { SavedObjectsClientContract, SavedObjectsDeleteOptions } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; export interface DeleteRuleSoParams { savedObjectsClient: SavedObjectsClientContract; @@ -16,5 +17,5 @@ export interface DeleteRuleSoParams { export const deleteRuleSo = (params: DeleteRuleSoParams): Promise<{}> => { const { savedObjectsClient, id, savedObjectsDeleteOptions } = params; - return savedObjectsClient.delete('alert', id, savedObjectsDeleteOptions); + return savedObjectsClient.delete(RULE_SAVED_OBJECT_TYPE, id, savedObjectsDeleteOptions); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/find_rules_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/find_rules_so.ts index 1362c2406dbae..e929ccf019205 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/find_rules_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/find_rules_so.ts @@ -10,6 +10,7 @@ import { SavedObjectsFindOptions, SavedObjectsFindResponse, } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAttributes } from '../types'; export interface FindRulesSoParams { @@ -24,6 +25,6 @@ export const findRulesSo = >( return savedObjectsClient.find({ ...savedObjectsFindOptions, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/get_rule_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/get_rule_so.ts index c8777afef3f78..051644bab56f2 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/get_rule_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/get_rule_so.ts @@ -7,6 +7,7 @@ import { SavedObjectsClientContract, SavedObject } from '@kbn/core/server'; import { SavedObjectsGetOptions } from '@kbn/core-saved-objects-api-server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAttributes } from '../types'; export interface GetRuleSoParams { @@ -18,5 +19,5 @@ export interface GetRuleSoParams { export const getRuleSo = (params: GetRuleSoParams): Promise> => { const { savedObjectsClient, id, savedObjectsGetOptions } = params; - return savedObjectsClient.get('alert', id, savedObjectsGetOptions); + return savedObjectsClient.get(RULE_SAVED_OBJECT_TYPE, id, savedObjectsGetOptions); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/resolve_rule_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/resolve_rule_so.ts index b8061cc6e3c3c..d0429b4166d8e 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/resolve_rule_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/resolve_rule_so.ts @@ -7,6 +7,7 @@ import { SavedObjectsClientContract, SavedObjectsResolveResponse } from '@kbn/core/server'; import { SavedObjectsResolveOptions } from '@kbn/core-saved-objects-api-server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAttributes } from '../types'; export interface ResolveRuleSoParams { @@ -20,5 +21,5 @@ export const resolveRuleSo = ( ): Promise> => { const { savedObjectsClient, id, savedObjectsResolveOptions } = params; - return savedObjectsClient.resolve('alert', id, savedObjectsResolveOptions); + return savedObjectsClient.resolve(RULE_SAVED_OBJECT_TYPE, id, savedObjectsResolveOptions); }; diff --git a/x-pack/plugins/alerting/server/data/rule/methods/update_rule_so.ts b/x-pack/plugins/alerting/server/data/rule/methods/update_rule_so.ts index 8739202c237ea..dfb8b6b5c1e7e 100644 --- a/x-pack/plugins/alerting/server/data/rule/methods/update_rule_so.ts +++ b/x-pack/plugins/alerting/server/data/rule/methods/update_rule_so.ts @@ -10,6 +10,7 @@ import { SavedObjectsUpdateOptions, SavedObjectsUpdateResponse, } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAttributes } from '../types'; export interface UpdateRuleSoParams { @@ -25,7 +26,7 @@ export const updateRuleSo = ( const { savedObjectsClient, id, updateRuleAttributes, savedObjectsUpdateOptions } = params; return savedObjectsClient.update( - 'alert', + RULE_SAVED_OBJECT_TYPE, id, updateRuleAttributes, savedObjectsUpdateOptions diff --git a/x-pack/plugins/alerting/server/health/get_health.test.ts b/x-pack/plugins/alerting/server/health/get_health.test.ts index 3715113c84232..51e03dc890e98 100644 --- a/x-pack/plugins/alerting/server/health/get_health.test.ts +++ b/x-pack/plugins/alerting/server/health/get_health.test.ts @@ -6,6 +6,7 @@ */ import { savedObjectsRepositoryMock, savedObjectsServiceMock } from '@kbn/core/server/mocks'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; import { RuleExecutionStatusErrorReasons, HealthStatus } from '../types'; import { getAlertingHealthStatus, getHealth } from './get_health'; @@ -22,7 +23,7 @@ describe('getHealth()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -80,7 +81,7 @@ describe('getHealth()', () => { saved_objects: [ { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '1s' }, @@ -134,7 +135,7 @@ describe('getHealth()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -185,7 +186,7 @@ describe('getHealth()', () => { saved_objects: [ { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '1s' }, @@ -233,7 +234,7 @@ describe('getAlertingHealthStatus()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, diff --git a/x-pack/plugins/alerting/server/health/get_health.ts b/x-pack/plugins/alerting/server/health/get_health.ts index 5d2c43fe69182..f4b727170a4b9 100644 --- a/x-pack/plugins/alerting/server/health/get_health.ts +++ b/x-pack/plugins/alerting/server/health/get_health.ts @@ -6,6 +6,7 @@ */ import { ISavedObjectsRepository, SavedObjectsServiceStart } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; import { AlertsHealth, HealthStatus, RawRule, RuleExecutionStatusErrorReasons } from '../types'; import type { LatestTaskStateSchema } from './task_state'; @@ -30,7 +31,7 @@ export const getHealth = async ( const { saved_objects: decryptErrorData } = await internalSavedObjectsRepository.find({ filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${RuleExecutionStatusErrorReasons.Decrypt}`, fields: ['executionStatus'], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -48,7 +49,7 @@ export const getHealth = async ( const { saved_objects: executeErrorData } = await internalSavedObjectsRepository.find({ filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${RuleExecutionStatusErrorReasons.Execute}`, fields: ['executionStatus'], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -66,7 +67,7 @@ export const getHealth = async ( const { saved_objects: readErrorData } = await internalSavedObjectsRepository.find({ filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${RuleExecutionStatusErrorReasons.Read}`, fields: ['executionStatus'], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -84,7 +85,7 @@ export const getHealth = async ( const { saved_objects: noErrorData } = await internalSavedObjectsRepository.find({ filter: 'not alert.attributes.executionStatus.status:error', fields: ['executionStatus'], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', namespaces: ['*'], @@ -107,7 +108,9 @@ export const getAlertingHealthStatus = async ( savedObjects: SavedObjectsServiceStart, stateRuns: number ) => { - const alertingHealthStatus = await getHealth(savedObjects.createInternalRepository(['alert'])); + const alertingHealthStatus = await getHealth( + savedObjects.createInternalRepository([RULE_SAVED_OBJECT_TYPE]) + ); const state: LatestTaskStateSchema = { runs: stateRuns + 1, health_status: alertingHealthStatus.decryptionHealth.status, diff --git a/x-pack/plugins/alerting/server/index.ts b/x-pack/plugins/alerting/server/index.ts index 04c48ab77c8aa..5be648354e61f 100644 --- a/x-pack/plugins/alerting/server/index.ts +++ b/x-pack/plugins/alerting/server/index.ts @@ -34,6 +34,7 @@ export type { GetViewInAppRelativeUrlFnOpts, DataStreamAdapter, } from './types'; +export { RULE_SAVED_OBJECT_TYPE } from './saved_objects'; export { RuleNotifyWhen } from '../common'; export { DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT } from './config'; export type { PluginSetupContract, PluginStartContract } from './plugin'; diff --git a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts index f3fdcec752def..680279f5dbac7 100644 --- a/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts +++ b/x-pack/plugins/alerting/server/lib/alerting_event_logger/alerting_event_logger.ts @@ -13,6 +13,7 @@ import { } from '@kbn/event-log-plugin/server'; import { EVENT_LOG_ACTIONS } from '../../plugin'; import { UntypedNormalizedRuleType } from '../../rule_type_registry'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; import { TaskRunnerTimings } from '../../task_runner/task_runner_timer'; import { AlertInstanceState, RuleExecutionStatus } from '../../types'; import { createAlertEventLogRecordObject } from '../create_alert_event_log_record_object'; @@ -259,7 +260,7 @@ export function createAlertRecord(context: RuleContextOpts, alert: AlertOpts) { savedObjects: [ { id: context.ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: context.ruleType.id, relation: SAVED_OBJECT_REL_PRIMARY, }, @@ -286,7 +287,7 @@ export function createActionExecuteRecord(context: RuleContextOpts, action: Acti savedObjects: [ { id: context.ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: context.ruleType.id, relation: SAVED_OBJECT_REL_PRIMARY, }, @@ -319,7 +320,7 @@ export function createExecuteTimeoutRecord(context: RuleContextOpts) { savedObjects: [ { id: context.ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: context.ruleType.id, relation: SAVED_OBJECT_REL_PRIMARY, }, @@ -346,7 +347,7 @@ export function initializeExecuteRecord(context: RuleContext) { savedObjects: [ { id: context.ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: context.ruleType.id, relation: SAVED_OBJECT_REL_PRIMARY, }, diff --git a/x-pack/plugins/alerting/server/lib/is_alerting_error.test.ts b/x-pack/plugins/alerting/server/lib/is_alerting_error.test.ts index 2c4a40efb05f0..f197a8e7424de 100644 --- a/x-pack/plugins/alerting/server/lib/is_alerting_error.test.ts +++ b/x-pack/plugins/alerting/server/lib/is_alerting_error.test.ts @@ -10,10 +10,11 @@ import { ErrorWithReason } from './error_with_reason'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { v4 as uuidv4 } from 'uuid'; import { RuleExecutionStatusErrorReasons } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; describe('isAlertSavedObjectNotFoundError', () => { const id = uuidv4(); - const errorSONF = SavedObjectsErrorHelpers.createGenericNotFoundError('alert', id); + const errorSONF = SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, id); test('identifies SavedObjects Not Found errors', () => { // ensure the error created by SO parses as a string with the format we expect @@ -34,7 +35,10 @@ describe('isAlertSavedObjectNotFoundError', () => { describe('isEsUnavailableError', () => { const id = uuidv4(); - const errorSONF = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError('alert', id); + const errorSONF = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError( + RULE_SAVED_OBJECT_TYPE, + id + ); test('identifies es unavailable errors', () => { // ensure the error created by SO parses as a string with the format we expect diff --git a/x-pack/plugins/alerting/server/lib/retry_if_conflicts.test.ts b/x-pack/plugins/alerting/server/lib/retry_if_conflicts.test.ts index 8cce79e22fe88..d1af51e179233 100644 --- a/x-pack/plugins/alerting/server/lib/retry_if_conflicts.test.ts +++ b/x-pack/plugins/alerting/server/lib/retry_if_conflicts.test.ts @@ -8,6 +8,7 @@ import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { retryIfConflicts, RetryForConflictsAttempts } from './retry_if_conflicts'; import { loggingSystemMock } from '@kbn/core/server/mocks'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; describe('retry_if_conflicts', () => { beforeEach(() => { @@ -47,7 +48,9 @@ describe('retry_if_conflicts', () => { MockOperationName, getOperationConflictsTimes(RetryForConflictsAttempts + 1) ) - ).rejects.toThrowError(SavedObjectsErrorHelpers.createConflictError('alert', MockAlertId)); + ).rejects.toThrowError( + SavedObjectsErrorHelpers.createConflictError(RULE_SAVED_OBJECT_TYPE, MockAlertId) + ); expect(MockLogger.debug).toBeCalledTimes(RetryForConflictsAttempts); expect(MockLogger.warn).toBeCalledTimes(1); expect(MockLogger.warn).toBeCalledWith(`${MockOperationName} conflict, exceeded retries`); @@ -71,7 +74,7 @@ function getOperationConflictsTimes(times: number) { return async function OperationConflictsTimes() { times--; if (times >= 0) { - throw SavedObjectsErrorHelpers.createConflictError('alert', MockAlertId); + throw SavedObjectsErrorHelpers.createConflictError(RULE_SAVED_OBJECT_TYPE, MockAlertId); } return MockResult; diff --git a/x-pack/plugins/alerting/server/plugin.ts b/x-pack/plugins/alerting/server/plugin.ts index 64bc8ca05281f..87f6e4c3a3979 100644 --- a/x-pack/plugins/alerting/server/plugin.ts +++ b/x-pack/plugins/alerting/server/plugin.ts @@ -77,7 +77,7 @@ import { } from './types'; import { registerAlertingUsageCollector } from './usage'; import { initializeAlertingTelemetry, scheduleAlertingTelemetry } from './usage/task'; -import { setupSavedObjects, getLatestRuleVersion } from './saved_objects'; +import { setupSavedObjects, getLatestRuleVersion, RULE_SAVED_OBJECT_TYPE } from './saved_objects'; import { initializeApiKeyInvalidator, scheduleApiKeyInvalidatorTask, @@ -463,7 +463,7 @@ export class AlertingPlugin { licenseState?.setNotifyUsage(plugins.licensing.featureUsage.notifyUsage); const encryptedSavedObjectsClient = plugins.encryptedSavedObjects.getClient({ - includedHiddenTypes: ['alert'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE], }); const spaceIdToNamespace = (spaceId?: string) => { @@ -491,7 +491,9 @@ export class AlertingPlugin { taskManager: plugins.taskManager, securityPluginSetup: security, securityPluginStart: plugins.security, - internalSavedObjectsRepository: core.savedObjects.createInternalRepository(['alert']), + internalSavedObjectsRepository: core.savedObjects.createInternalRepository([ + RULE_SAVED_OBJECT_TYPE, + ]), encryptedSavedObjectsClient, spaceIdToNamespace, getSpaceId(request: KibanaRequest) { @@ -556,7 +558,9 @@ export class AlertingPlugin { encryptedSavedObjectsClient, basePathService: core.http.basePath, eventLogger: this.eventLogger!, - internalSavedObjectsRepository: core.savedObjects.createInternalRepository(['alert']), + internalSavedObjectsRepository: core.savedObjects.createInternalRepository([ + RULE_SAVED_OBJECT_TYPE, + ]), executionContext: core.executionContext, ruleTypeRegistry: this.ruleTypeRegistry!, alertsService: this.alertsService, @@ -571,7 +575,7 @@ export class AlertingPlugin { getMaintenanceWindowClientWithRequest, }); - this.eventLogService!.registerSavedObjectProvider('alert', (request) => { + this.eventLogService!.registerSavedObjectProvider(RULE_SAVED_OBJECT_TYPE, (request) => { const client = getRulesClientWithRequest(request); return (objects?: SavedObjectsBulkGetObject[]) => objects @@ -594,7 +598,7 @@ export class AlertingPlugin { getAlertingAuthorizationWithRequest, getRulesClientWithRequest, getFrameworkHealth: async () => - await getHealth(core.savedObjects.createInternalRepository(['alert'])), + await getHealth(core.savedObjects.createInternalRepository([RULE_SAVED_OBJECT_TYPE])), }; } @@ -621,7 +625,7 @@ export class AlertingPlugin { }, listTypes: ruleTypeRegistry!.list.bind(ruleTypeRegistry!), getFrameworkHealth: async () => - await getHealth(savedObjects.createInternalRepository(['alert'])), + await getHealth(savedObjects.createInternalRepository([RULE_SAVED_OBJECT_TYPE])), areApiKeysEnabled: async () => { const [, { security }] = await core.getStartServices(); return security?.authc.apiKeys.areAPIKeysEnabled() ?? false; diff --git a/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts b/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts index 414d2e8b54122..408ed049044c6 100644 --- a/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts @@ -11,6 +11,7 @@ import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../rules_client.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access', () => ({ @@ -99,7 +100,9 @@ describe('getActionErrorLogRoute', () => { rulesClient.getActionErrorLog = jest .fn() - .mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockRejectedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, 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 f7fe1a3406e9c..5eca11c27a4b2 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 @@ -12,6 +12,7 @@ import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../rules_client.mock'; import { AlertSummary } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access', () => ({ @@ -98,7 +99,9 @@ describe('getRuleAlertSummaryRoute', () => { rulesClient.getAlertSummary = jest .fn() - .mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockRejectedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts index ff15a60623168..e92b54769d329 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts @@ -11,6 +11,7 @@ import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../rules_client.mock'; import { getRuleExecutionKPIRoute } from './get_rule_execution_kpi'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access', () => ({ @@ -83,7 +84,9 @@ describe('getRuleExecutionKPIRoute', () => { rulesClient.getRuleExecutionKPI = jest .fn() - .mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockRejectedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, 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 d84c6fe73b616..b68d751147ebe 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 @@ -11,6 +11,7 @@ import { licenseStateMock } from '../lib/license_state.mock'; import { mockHandlerArguments } from './_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../rules_client.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../lib/license_api_access', () => ({ @@ -124,7 +125,9 @@ describe('getRuleStateRoute', () => { rulesClient.getAlertState = jest .fn() - .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockResolvedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, 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 a78fcd7f86f65..c04aa0b39c022 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 @@ -13,6 +13,7 @@ import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../../rules_client.mock'; import { AlertSummary } from '../../types'; import { trackLegacyRouteUsage } from '../../lib/track_legacy_route_usage'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access', () => ({ @@ -98,7 +99,9 @@ describe('getAlertInstanceSummaryRoute', () => { rulesClient.getAlertSummary = jest .fn() - .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockResolvedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, 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 67fd50a965ea4..eab550ee4b304 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 @@ -12,6 +12,7 @@ import { mockHandlerArguments } from '../_mock_handler_arguments'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { rulesClientMock } from '../../rules_client.mock'; import { trackLegacyRouteUsage } from '../../lib/track_legacy_route_usage'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const rulesClient = rulesClientMock.create(); jest.mock('../../lib/license_api_access', () => ({ @@ -129,7 +130,9 @@ describe('getAlertStateRoute', () => { rulesClient.getAlertState = jest .fn() - .mockResolvedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1')); + .mockResolvedValueOnce( + SavedObjectsErrorHelpers.createGenericNotFoundError(RULE_SAVED_OBJECT_TYPE, '1') + ); const [context, req, res] = mockHandlerArguments( { rulesClient }, diff --git a/x-pack/plugins/alerting/server/rules_client/common/audit_events.test.ts b/x-pack/plugins/alerting/server/rules_client/common/audit_events.test.ts index 781b8fe1f4715..6d42be630ffd1 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/audit_events.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/audit_events.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; import { RuleAuditAction, ruleAuditEvent } from './audit_events'; describe('#ruleAuditEvent', () => { @@ -13,7 +14,7 @@ describe('#ruleAuditEvent', () => { ruleAuditEvent({ action: RuleAuditAction.CREATE, outcome: 'unknown', - savedObject: { type: 'alert', id: 'ALERT_ID' }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: 'ALERT_ID' }, }) ).toMatchInlineSnapshot(` Object { @@ -43,7 +44,7 @@ describe('#ruleAuditEvent', () => { expect( ruleAuditEvent({ action: RuleAuditAction.CREATE, - savedObject: { type: 'alert', id: 'ALERT_ID' }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: 'ALERT_ID' }, }) ).toMatchInlineSnapshot(` Object { @@ -73,7 +74,7 @@ describe('#ruleAuditEvent', () => { expect( ruleAuditEvent({ action: RuleAuditAction.CREATE, - savedObject: { type: 'alert', id: 'ALERT_ID' }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: 'ALERT_ID' }, error: new Error('ERROR_MESSAGE'), }) ).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.test.ts b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.test.ts index c5570a7422d02..d099ba8693c3f 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.test.ts @@ -10,6 +10,7 @@ import { retryIfBulkEditConflicts } from './retry_if_bulk_edit_conflicts'; import { RETRY_IF_CONFLICTS_ATTEMPTS } from './wait_before_next_retry'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { BulkEditSkipReason } from '../../../common/bulk_edit'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const mockFilter: KueryNode = { type: 'function', @@ -21,12 +22,12 @@ const mockLogger = loggingSystemMock.create().get(); const mockSuccessfulResult = { apiKeysToInvalidate: [], rules: [ - { id: '1', type: 'alert', attributes: {} }, - { id: '2', type: 'alert', attributes: { name: 'Test rule 2' } }, + { id: '1', type: RULE_SAVED_OBJECT_TYPE, attributes: {} }, + { id: '2', type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'Test rule 2' } }, ], resultSavedObjects: [ - { id: '1', type: 'alert', attributes: {}, references: [] }, - { id: '2', type: 'alert', attributes: { name: 'Test rule 2' }, references: [] }, + { id: '1', type: RULE_SAVED_OBJECT_TYPE, attributes: {}, references: [] }, + { id: '2', type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'Test rule 2' }, references: [] }, ], errors: [], skipped: [ @@ -50,10 +51,10 @@ function getOperationConflictsTimes(times: number) { return { ...mockSuccessfulResult, resultSavedObjects: [ - { id: '1', type: 'alert', attributes: {}, references: [] }, + { id: '1', type: RULE_SAVED_OBJECT_TYPE, attributes: {}, references: [] }, { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: {}, references: [], error: { @@ -94,7 +95,7 @@ describe('retryIfBulkEditConflicts', () => { attributes: {}, id: '1', references: [], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { attributes: { @@ -102,7 +103,7 @@ describe('retryIfBulkEditConflicts', () => { }, id: '2', references: [], - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); diff --git a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.ts b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.ts index 1a506b1b3fa86..86e3897183849 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_edit_conflicts.ts @@ -14,6 +14,7 @@ import { convertRuleIdsToKueryNode } from '../../lib'; import { BulkOperationError } from '../types'; import { RuleAttributes } from '../../data/rule/types'; import { waitBeforeNextRetry, RETRY_IF_CONFLICTS_ATTEMPTS } from './wait_before_next_retry'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; // max number of failed SO ids in one retry filter const MaxIdsNumberInRetryFilter = 1000; @@ -70,7 +71,7 @@ export const retryIfBulkEditConflicts = async ( const conflictErrorMap = resultSavedObjects.reduce>( (acc, item) => { - if (item.type === 'alert' && item?.error?.statusCode === 409) { + if (item.type === RULE_SAVED_OBJECT_TYPE && item?.error?.statusCode === 409) { return acc.set(item.id, { message: item.error.message }); } return acc; diff --git a/x-pack/plugins/alerting/server/rules_client/common/validate_attributes.ts b/x-pack/plugins/alerting/server/rules_client/common/validate_attributes.ts index 80353ad0f6055..b58cc453d5800 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/validate_attributes.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/validate_attributes.ts @@ -8,6 +8,7 @@ import { KueryNode } from '@kbn/es-query'; import { get, isEmpty } from 'lodash'; import { alertMappings } from '../../../common/saved_objects/rules/mappings'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const astFunctionType = ['is', 'range', 'nested']; @@ -137,7 +138,10 @@ export const validateFilterKueryNode = ({ }: ValidateFilterKueryNodeParams) => { const action = ({ index, fieldName }: IterateActionProps) => { if (index === 0) { - const firstAttribute = getFieldNameAttribute(fieldName, ['alert', 'attributes']); + const firstAttribute = getFieldNameAttribute(fieldName, [ + RULE_SAVED_OBJECT_TYPE, + 'attributes', + ]); if (excludedFieldNames.includes(firstAttribute)) { throw new Error(`Filter is not supported on this field ${fieldName}`); } diff --git a/x-pack/plugins/alerting/server/rules_client/lib/check_authorization_and_get_total.ts b/x-pack/plugins/alerting/server/rules_client/lib/check_authorization_and_get_total.ts index 4327176841ad4..a4e75c58bde4b 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/check_authorization_and_get_total.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/check_authorization_and_get_total.ts @@ -18,6 +18,7 @@ import { } from '../common/constants'; import { RulesClientContext } from '../types'; import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export const checkAuthorizationAndGetTotal = async ( context: RulesClientContext, @@ -54,7 +55,7 @@ export const checkAuthorizationAndGetTotal = async ( filter, page: 1, perPage: 0, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, aggs: { alertTypeId: { multi_terms: { diff --git a/x-pack/plugins/alerting/server/rules_client/lib/create_rule_saved_object.ts b/x-pack/plugins/alerting/server/rules_client/lib/create_rule_saved_object.ts index 14662953ba73b..cc0d6a895dcc0 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/create_rule_saved_object.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/create_rule_saved_object.ts @@ -17,6 +17,7 @@ import { updateMeta } from './update_meta'; import { scheduleTask } from './schedule_task'; import { getAlertFromRaw } from './get_alert_from_raw'; import { createRuleSo, deleteRuleSo, updateRuleSo } from '../../data/rule'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; interface CreateRuleSavedObjectParams { intervalInMs: number; @@ -56,7 +57,7 @@ export async function createRuleSavedObject { const currentRule: SavedObject = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', diff --git a/x-pack/plugins/alerting/server/rules_client/lib/resolve_rule_saved_object.ts b/x-pack/plugins/alerting/server/rules_client/lib/resolve_rule_saved_object.ts index 101f846ae9ba9..f133aea9035a0 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/resolve_rule_saved_object.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/resolve_rule_saved_object.ts @@ -11,6 +11,7 @@ import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; import { resolveRuleSo } from '../../data/rule'; import { RuleAttributes } from '../../data/rule/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; interface ResolveRuleSavedObjectParams { ruleId: string; @@ -26,7 +27,7 @@ export async function resolveRuleSavedObject( ruleAuditEvent({ action: RuleAuditAction.RESOLVE, outcome: 'unknown', - savedObject: { type: 'alert', id: ruleId }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: ruleId }, }) ); diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.test.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.test.ts index 072a1e98cc3de..8830ce96a6c43 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import type { SavedObjectsFindResult, SavedObjectAttribute } from '@kbn/core/server'; import { loggingSystemMock, savedObjectsClientMock } from '@kbn/core/server/mocks'; @@ -37,7 +38,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { test('calls "savedObjectsClient.find" with the expected "hasReferences"', async () => { await legacyGetBulkRuleActionsSavedObject({ alertIds: ['123'], savedObjectsClient, logger }); expect(savedObjectsClient.find).toHaveBeenCalledWith({ - hasReference: [{ id: '123', type: 'alert' }], + hasReference: [{ id: '123', type: RULE_SAVED_OBJECT_TYPE }], perPage: 10000, type: legacyRuleActionsSavedObjectType, }); @@ -70,7 +71,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -134,7 +135,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -163,7 +164,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-456', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -244,7 +245,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -330,7 +331,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -401,7 +402,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', @@ -468,7 +469,7 @@ describe('legacyGetBulkRuleActionsSavedObject', () => { id: '123', type: legacyRuleActionsSavedObjectType, references: [ - // Missing the "alert_0" of { name: 'alert_0', id: 'alert-123', type: 'alert', }, + // Missing the "alert_0" of { name: 'alert_0', id: 'alert-123', type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', id: 'action-123', @@ -539,7 +540,7 @@ describe('formatLegacyActions', () => { { name: 'alert_0', id: 'alert-123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, { name: 'action_0', diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.ts index a0aa3286f1f6d..74a56d1964ada 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/format_legacy_actions.ts @@ -8,6 +8,7 @@ import { chunk } from 'lodash'; import type { SavedObjectsFindOptionsReference, Logger } from '@kbn/core/server'; import pMap from 'p-map'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import { RuleAction, Rule } from '../../../types'; import type { RuleExecutorServices } from '../../..'; import { injectReferencesIntoActions } from '../../common'; @@ -49,7 +50,7 @@ export const legacyGetBulkRuleActionsSavedObject = async ({ }: LegacyGetBulkRuleActionsSavedObject): Promise> => { const references = alertIds.map((alertId) => ({ id: alertId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, })); const errors: unknown[] = []; const results = await pMap( @@ -82,7 +83,7 @@ export const legacyGetBulkRuleActionsSavedObject = async ({ return actionSavedObjects.reduce((acc: { [key: string]: LegacyActionsObj }, savedObject) => { const ruleAlertId = savedObject.references.find((reference) => { // Find the first rule alert and assume that is the one we want since we should only ever have 1. - return reference.type === 'alert'; + return reference.type === RULE_SAVED_OBJECT_TYPE; }); // We check to ensure we have found a "ruleAlertId" and hopefully we have. const ruleAlertIdKey = ruleAlertId != null ? ruleAlertId.id : undefined; diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock.ts index d45c86c3f05a5..6a1a554655a3c 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import type { SavedObjectsFindResponse, SavedObjectsFindResult, @@ -179,7 +180,7 @@ export const legacyGetSiemNotificationRuleNoActionsSOResult = ( ruleThrottle: 'no_actions', alertThrottle: null, }, - references: [{ id: ruleId, type: 'alert', name: 'alert_0' }], + references: [{ id: ruleId, type: RULE_SAVED_OBJECT_TYPE, name: 'alert_0' }], migrationVersion: { 'siem-detection-engine-rule-actions': '7.11.2', }, @@ -214,7 +215,7 @@ export const legacyGetSiemNotificationRuleEveryRunSOResult = ( ruleThrottle: 'rule', alertThrottle: null, }, - references: [{ id: ruleId, type: 'alert', name: 'alert_0' }], + references: [{ id: ruleId, type: RULE_SAVED_OBJECT_TYPE, name: 'alert_0' }], migrationVersion: { 'siem-detection-engine-rule-actions': '7.11.2', }, @@ -251,7 +252,7 @@ export const legacyGetSiemNotificationRuleHourlyActionsSOResult = ( alertThrottle: '1h', }, references: [ - { id: ruleId, type: 'alert', name: 'alert_0' }, + { id: ruleId, type: RULE_SAVED_OBJECT_TYPE, name: 'alert_0' }, { id: connectorId, type: 'action', name: 'action_0' }, ], migrationVersion: { @@ -290,7 +291,7 @@ export const legacyGetSiemNotificationRuleDailyActionsSOResult = ( alertThrottle: '1d', }, references: [ - { id: ruleId, type: 'alert', name: 'alert_0' }, + { id: ruleId, type: RULE_SAVED_OBJECT_TYPE, name: 'alert_0' }, { id: connectorId, type: 'action', name: 'action_0' }, ], migrationVersion: { @@ -329,7 +330,7 @@ export const legacyGetSiemNotificationRuleWeeklyActionsSOResult = ( alertThrottle: '7d', }, references: [ - { id: ruleId, type: 'alert', name: 'alert_0' }, + { id: ruleId, type: RULE_SAVED_OBJECT_TYPE, name: 'alert_0' }, { id: connectorId, type: 'action', name: 'action_0' }, ], migrationVersion: { diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.ts index 9678dff6898c8..fe4bb56713861 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.ts @@ -6,6 +6,7 @@ */ import type { SavedObjectReference } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import type { RulesClientContext } from '../..'; import { RawRuleAction } from '../../../types'; import { find } from '../../methods/find'; @@ -52,7 +53,7 @@ export const retrieveMigratedLegacyActions: RetrieveMigratedLegacyActions = asyn options: { filter: 'alert.attributes.alertTypeId:(siem.notifications)', hasReference: { - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }, }, @@ -60,7 +61,7 @@ export const retrieveMigratedLegacyActions: RetrieveMigratedLegacyActions = asyn unsecuredSavedObjectsClient.find({ type: legacyRuleActionsSavedObjectType, hasReference: { - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }, }), diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.test.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.test.ts index cea32ce3e1913..f7d9a70a3c53c 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '../../../saved_objects'; import type { SavedObjectReference } from '@kbn/core/server'; import { transformFromLegacyActions } from './transform_legacy_actions'; @@ -48,7 +49,7 @@ describe('transformFromLegacyActions', () => { { name: 'alert_0', id: 'alert-1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ]); diff --git a/x-pack/plugins/alerting/server/rules_client/lib/untrack_rule_alerts.ts b/x-pack/plugins/alerting/server/rules_client/lib/untrack_rule_alerts.ts index 17794aeb4ebdf..d69d84c7fd8c7 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/untrack_rule_alerts.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/untrack_rule_alerts.ts @@ -15,6 +15,7 @@ import { EVENT_LOG_ACTIONS } from '../../plugin'; import { createAlertEventLogRecordObject } from '../../lib/create_alert_event_log_record_object'; import { RulesClientContext } from '../types'; import { RuleAttributes } from '../../data/rule/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export const untrackRuleAlerts = async ( context: RulesClientContext, @@ -67,7 +68,7 @@ export const untrackRuleAlerts = async ( savedObjects: [ { id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: attributes.alertTypeId, relation: SAVED_OBJECT_REL_PRIMARY, }, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/bulk_enable.ts b/x-pack/plugins/alerting/server/rules_client/methods/bulk_enable.ts index cac39ccb367d4..0f01e88cfaa12 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/bulk_enable.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/bulk_enable.ts @@ -32,6 +32,7 @@ import { import { RulesClientContext, BulkOperationError, BulkOptions } from '../types'; import { validateScheduleLimit } from '../../application/rule/methods/get_schedule_frequency'; import { RuleAttributes } from '../../data/rule/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const getShouldScheduleTask = async ( context: RulesClientContext, @@ -118,7 +119,7 @@ const bulkEnableRulesWithOCC = async ( await context.encryptedSavedObjectsClient.createPointInTimeFinderDecryptedAsInternalUser( { filter: filter ? nodeBuilder.and([filter, additionalFilter]) : additionalFilter, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, perPage: 100, ...(context.namespace ? { namespaces: [context.namespace] } : undefined), } @@ -241,7 +242,7 @@ const bulkEnableRulesWithOCC = async ( ruleAuditEvent({ action: RuleAuditAction.ENABLE, outcome: 'unknown', - savedObject: { type: 'alert', id: rule.id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: rule.id }, }) ); } catch (error) { diff --git a/x-pack/plugins/alerting/server/rules_client/methods/clear_expired_snoozes.ts b/x-pack/plugins/alerting/server/rules_client/methods/clear_expired_snoozes.ts index 90156246331f0..70f0e8a29eac2 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/clear_expired_snoozes.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/clear_expired_snoozes.ts @@ -6,7 +6,7 @@ */ import { RuleTypeParams, SanitizedRule } from '../../../common'; -import { partiallyUpdateAlert } from '../../saved_objects'; +import { partiallyUpdateRule } from '../../saved_objects'; import { isSnoozeExpired } from '../../lib'; import { RulesClientContext } from '../types'; import { updateMeta } from '../lib'; @@ -39,7 +39,7 @@ export async function clearExpiredSnoozes( const updateOptions = { version, refresh: false }; - await partiallyUpdateAlert( + await partiallyUpdateRule( context.unsecuredSavedObjectsClient, rule.id, updateAttributes, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/clone.ts b/x-pack/plugins/alerting/server/rules_client/methods/clone.ts index f11b5c69012c4..acc8b66d6fde8 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/clone.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/clone.ts @@ -19,6 +19,7 @@ import { getRuleExecutionStatusPendingAttributes } from '../../lib/rule_executio import { isDetectionEngineAADRuleType } from '../../saved_objects/migrations/utils'; import { createNewAPIKeySet, createRuleSavedObject } from '../lib'; import { RulesClientContext } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export type CloneArguments = [string, { newId?: string }]; @@ -33,9 +34,13 @@ export async function clone( ruleSavedObject = await withSpan( { name: 'encryptedSavedObjectsClient.getDecryptedAsInternalUser', type: 'rules' }, () => - context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }) + context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ) ); } catch (e) { // We'll skip invalidating the API key since we failed to load the decrypted saved object @@ -45,7 +50,7 @@ export async function clone( // Still attempt to load the object using SOC ruleSavedObject = await withSpan( { name: 'unsecuredSavedObjectsClient.get', type: 'rules' }, - () => context.unsecuredSavedObjectsClient.get('alert', id) + () => context.unsecuredSavedObjectsClient.get(RULE_SAVED_OBJECT_TYPE, id) ); } @@ -80,7 +85,7 @@ export async function clone( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.CREATE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -125,7 +130,7 @@ export async function clone( ruleAuditEvent({ action: RuleAuditAction.CREATE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); diff --git a/x-pack/plugins/alerting/server/rules_client/methods/delete.ts b/x-pack/plugins/alerting/server/rules_client/methods/delete.ts index 566945f0357fc..53baa548d783c 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/delete.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/delete.ts @@ -14,6 +14,7 @@ import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; import { untrackRuleAlerts, migrateLegacyActions } from '../lib'; import { RuleAttributes } from '../../data/rule/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function deleteRule(context: RulesClientContext, { id }: { id: string }) { return await retryIfConflicts( @@ -31,9 +32,13 @@ async function deleteWithOCC(context: RulesClientContext, { id }: { id: string } try { const decryptedAlert = - await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }); + await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; apiKeyCreatedByUser = decryptedAlert.attributes.apiKeyCreatedByUser; taskIdToRemove = decryptedAlert.attributes.scheduledTaskId; @@ -44,7 +49,10 @@ async function deleteWithOCC(context: RulesClientContext, { id }: { id: string } `delete(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the scheduledTaskId using SOC - const alert = await context.unsecuredSavedObjectsClient.get('alert', id); + const alert = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); taskIdToRemove = alert.attributes.scheduledTaskId; attributes = alert.attributes; } @@ -60,7 +68,7 @@ async function deleteWithOCC(context: RulesClientContext, { id }: { id: string } context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.DELETE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -78,10 +86,10 @@ async function deleteWithOCC(context: RulesClientContext, { id }: { id: string } ruleAuditEvent({ action: RuleAuditAction.DELETE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); - const removeResult = await context.unsecuredSavedObjectsClient.delete('alert', id); + const removeResult = await context.unsecuredSavedObjectsClient.delete(RULE_SAVED_OBJECT_TYPE, id); await Promise.all([ taskIdToRemove ? context.taskManager.removeIfExists(taskIdToRemove) : null, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/disable.ts b/x-pack/plugins/alerting/server/rules_client/methods/disable.ts index d51a5793371f0..38b0dcc7e17d6 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/disable.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/disable.ts @@ -13,6 +13,7 @@ import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; import { untrackRuleAlerts, updateMeta, migrateLegacyActions } from '../lib'; import { RuleAttributes } from '../../data/rule/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function disable(context: RulesClientContext, { id }: { id: string }): Promise { return await retryIfConflicts( @@ -29,16 +30,23 @@ async function disableWithOCC(context: RulesClientContext, { id }: { id: string try { const decryptedAlert = - await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }); + await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ); attributes = decryptedAlert.attributes; version = decryptedAlert.version; references = decryptedAlert.references; } catch (e) { context.logger.error(`disable(): Failed to load API key of alert ${id}: ${e.message}`); // Still attempt to load the attributes and version using SOC - const alert = await context.unsecuredSavedObjectsClient.get('alert', id); + const alert = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); attributes = alert.attributes; version = alert.version; references = alert.references; @@ -55,7 +63,7 @@ async function disableWithOCC(context: RulesClientContext, { id }: { id: string context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.DISABLE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -68,7 +76,7 @@ async function disableWithOCC(context: RulesClientContext, { id }: { id: string ruleAuditEvent({ action: RuleAuditAction.DISABLE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -83,7 +91,7 @@ async function disableWithOCC(context: RulesClientContext, { id }: { id: string }); await context.unsecuredSavedObjectsClient.update( - 'alert', + RULE_SAVED_OBJECT_TYPE, id, updateMeta(context, { ...attributes, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/enable.ts b/x-pack/plugins/alerting/server/rules_client/methods/enable.ts index 53df42f012ad8..995e989121802 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/enable.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/enable.ts @@ -16,6 +16,7 @@ import { RulesClientContext } from '../types'; import { updateMeta, createNewAPIKeySet, scheduleTask, migrateLegacyActions } from '../lib'; import { validateScheduleLimit } from '../../application/rule/methods/get_schedule_frequency'; import { getRuleCircuitBreakerErrorMessage } from '../../../common'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function enable(context: RulesClientContext, { id }: { id: string }): Promise { return await retryIfConflicts( @@ -33,9 +34,13 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } try { const decryptedAlert = - await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }); + await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ); existingApiKey = decryptedAlert.attributes.apiKey; attributes = decryptedAlert.attributes; version = decryptedAlert.version; @@ -43,7 +48,10 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } } catch (e) { context.logger.error(`enable(): Failed to load API key of alert ${id}: ${e.message}`); // Still attempt to load the attributes and version using SOC - const alert = await context.unsecuredSavedObjectsClient.get('alert', id); + const alert = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); attributes = alert.attributes; version = alert.version; references = alert.references; @@ -80,7 +88,7 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.ENABLE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -91,7 +99,7 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } ruleAuditEvent({ action: RuleAuditAction.ENABLE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -140,7 +148,7 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } // we call create with overwrite=true if (migratedActions.hasLegacyActions) { await context.unsecuredSavedObjectsClient.create( - 'alert', + RULE_SAVED_OBJECT_TYPE, { ...updateAttributes, actions: migratedActions.resultedActions, @@ -155,9 +163,14 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } } ); } else { - await context.unsecuredSavedObjectsClient.update('alert', id, updateAttributes, { - version, - }); + await context.unsecuredSavedObjectsClient.update( + RULE_SAVED_OBJECT_TYPE, + id, + updateAttributes, + { + version, + } + ); } } catch (e) { throw e; @@ -193,7 +206,7 @@ async function enableWithOCC(context: RulesClientContext, { id }: { id: string } schedule: attributes.schedule as IntervalSchedule, throwOnConflict: false, }); - await context.unsecuredSavedObjectsClient.update('alert', id, { + await context.unsecuredSavedObjectsClient.update(RULE_SAVED_OBJECT_TYPE, id, { scheduledTaskId: scheduledTask.id, }); } else { diff --git a/x-pack/plugins/alerting/server/rules_client/methods/find.ts b/x-pack/plugins/alerting/server/rules_client/methods/find.ts index 537dfef55aff0..7ca51bcb16f19 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/find.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/find.ts @@ -29,6 +29,7 @@ import { alertingAuthorizationFilterOpts } from '../common/constants'; import { getAlertFromRaw } from '../lib/get_alert_from_raw'; import type { IndexType, RulesClientContext } from '../types'; import { formatLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export interface FindParams { options?: FindOptions; @@ -133,7 +134,7 @@ export async function find( ? nodeBuilder.and([filterKueryNode, authorizationFilter as KueryNode]) : authorizationFilter) ?? filterKueryNode, fields: fields ? includeFieldsRequiredForAuthentication(fields) : fields, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); const siemRules: Rule[] = []; @@ -149,7 +150,7 @@ export async function find( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.FIND, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -179,7 +180,7 @@ export async function find( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.FIND, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ) ); diff --git a/x-pack/plugins/alerting/server/rules_client/methods/get.ts b/x-pack/plugins/alerting/server/rules_client/methods/get.ts index 8b25f990d3cf1..3fb3a9e2e43c6 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/get.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/get.ts @@ -12,6 +12,7 @@ import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { getAlertFromRaw } from '../lib/get_alert_from_raw'; import { RulesClientContext } from '../types'; import { formatLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export interface GetParams { id: string; @@ -29,7 +30,7 @@ export async function get( excludeFromPublicApi = false, }: GetParams ): Promise | SanitizedRuleWithLegacyId> { - const result = await context.unsecuredSavedObjectsClient.get('alert', id); + const result = await context.unsecuredSavedObjectsClient.get(RULE_SAVED_OBJECT_TYPE, id); try { await context.authorization.ensureAuthorized({ ruleTypeId: result.attributes.alertTypeId, @@ -41,7 +42,7 @@ export async function get( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -50,7 +51,7 @@ export async function get( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); const rule = getAlertFromRaw( diff --git a/x-pack/plugins/alerting/server/rules_client/methods/get_action_error_log.ts b/x-pack/plugins/alerting/server/rules_client/methods/get_action_error_log.ts index ebd1862d6b3f6..9ff65893da3a0 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/get_action_error_log.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/get_action_error_log.ts @@ -20,6 +20,7 @@ import { formatExecutionErrorsResult } from '../../lib/format_execution_log_erro import { parseDate } from '../common'; import { RulesClientContext } from '../types'; import { get } from './get'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const actionErrorLogDefaultFilter = 'event.provider:actions AND ((event.action:execute AND (event.outcome:failure OR kibana.alerting.status:warning)) OR (event.action:execute-timeout))'; @@ -53,7 +54,7 @@ export async function getActionErrorLog( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_ACTION_ERROR_LOG, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -63,7 +64,7 @@ export async function getActionErrorLog( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_ACTION_ERROR_LOG, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -76,7 +77,7 @@ export async function getActionErrorLog( try { const errorResult = await eventLogClient.findEventsBySavedObjectIds( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], { start: parsedDateStart.toISOString(), @@ -130,7 +131,7 @@ export async function getActionErrorLogWithAuth( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_ACTION_ERROR_LOG, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -143,7 +144,7 @@ export async function getActionErrorLogWithAuth( try { const errorResult = await eventLogClient.findEventsWithAuthFilter( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], authorizationTuple.filter as KueryNode, namespace, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/get_alert_summary.ts b/x-pack/plugins/alerting/server/rules_client/methods/get_alert_summary.ts index 8d194b850816b..7739b03372007 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/get_alert_summary.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/get_alert_summary.ts @@ -13,6 +13,7 @@ import { parseDuration } from '../../../common/parse_duration'; import { parseDate } from '../common'; import { RulesClientContext } from '../types'; import { get } from './get'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export interface GetAlertSummaryParams { id: string; @@ -48,7 +49,7 @@ export async function getAlertSummary( try { const [queryResults, executionResults] = await Promise.all([ eventLogClient.findEventsBySavedObjectIds( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], { page: 1, @@ -62,7 +63,7 @@ export async function getAlertSummary( rule.legacyId !== null ? [rule.legacyId] : undefined ), eventLogClient.findEventsBySavedObjectIds( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], { page: 1, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/get_execution_kpi.ts b/x-pack/plugins/alerting/server/rules_client/methods/get_execution_kpi.ts index 734df53c9cb29..c063b8f90c614 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/get_execution_kpi.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/get_execution_kpi.ts @@ -20,6 +20,7 @@ import { import { RulesClientContext } from '../types'; import { parseDate } from '../common'; import { get } from './get'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export interface GetRuleExecutionKPIParams { id: string; @@ -54,7 +55,7 @@ export async function getRuleExecutionKPI( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_RULE_EXECUTION_KPI, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -64,7 +65,7 @@ export async function getRuleExecutionKPI( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_RULE_EXECUTION_KPI, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -77,7 +78,7 @@ export async function getRuleExecutionKPI( try { const aggResult = await eventLogClient.aggregateEventsBySavedObjectIds( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], { start: parsedDateStart.toISOString(), @@ -138,7 +139,7 @@ export async function getGlobalExecutionKpiWithAuth( try { const aggResult = await eventLogClient.aggregateEventsWithAuthFilter( - 'alert', + RULE_SAVED_OBJECT_TYPE, authorizationTuple.filter as KueryNode, { start: parsedDateStart.toISOString(), diff --git a/x-pack/plugins/alerting/server/rules_client/methods/get_execution_log.ts b/x-pack/plugins/alerting/server/rules_client/methods/get_execution_log.ts index 006109d71b4b5..f240b257bae6e 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/get_execution_log.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/get_execution_log.ts @@ -22,6 +22,7 @@ import { IExecutionLogResult } from '../../../common'; import { parseDate } from '../common'; import { RulesClientContext } from '../types'; import { get } from './get'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export interface GetExecutionLogByIdParams { id: string; @@ -62,7 +63,7 @@ export async function getExecutionLogForRule( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_EXECUTION_LOG, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -72,7 +73,7 @@ export async function getExecutionLogForRule( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.GET_EXECUTION_LOG, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -85,7 +86,7 @@ export async function getExecutionLogForRule( try { const aggResult = await eventLogClient.aggregateEventsBySavedObjectIds( - 'alert', + RULE_SAVED_OBJECT_TYPE, [id], { start: parsedDateStart.toISOString(), @@ -151,7 +152,7 @@ export async function getGlobalExecutionLogWithAuth( try { const aggResult = await eventLogClient.aggregateEventsWithAuthFilter( - 'alert', + RULE_SAVED_OBJECT_TYPE, authorizationTuple.filter as KueryNode, { start: parsedDateStart.toISOString(), diff --git a/x-pack/plugins/alerting/server/rules_client/methods/mute_all.ts b/x-pack/plugins/alerting/server/rules_client/methods/mute_all.ts index 72a693aace7ac..273d794a52dc8 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/mute_all.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/mute_all.ts @@ -8,7 +8,7 @@ import { RawRule } from '../../types'; import { WriteOperations, AlertingAuthorizationEntity } from '../../authorization'; import { retryIfConflicts } from '../../lib/retry_if_conflicts'; -import { partiallyUpdateAlert } from '../../saved_objects'; +import { partiallyUpdateRule, RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; import { updateMetaAttributes } from '../lib'; @@ -25,7 +25,7 @@ export async function muteAll(context: RulesClientContext, { id }: { id: string async function muteAllWithOCC(context: RulesClientContext, { id }: { id: string }) { const { attributes, version } = await context.unsecuredSavedObjectsClient.get( - 'alert', + RULE_SAVED_OBJECT_TYPE, id ); @@ -44,7 +44,7 @@ async function muteAllWithOCC(context: RulesClientContext, { id }: { id: string context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.MUTE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -55,7 +55,7 @@ async function muteAllWithOCC(context: RulesClientContext, { id }: { id: string ruleAuditEvent({ action: RuleAuditAction.MUTE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -70,7 +70,7 @@ async function muteAllWithOCC(context: RulesClientContext, { id }: { id: string }); const updateOptions = { version }; - await partiallyUpdateAlert( + await partiallyUpdateRule( context.unsecuredSavedObjectsClient, id, updateAttributes, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/run_soon.ts b/x-pack/plugins/alerting/server/rules_client/methods/run_soon.ts index 106f12ef50f6f..8f2d605f500dc 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/run_soon.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/run_soon.ts @@ -11,9 +11,13 @@ import { Rule } from '../../types'; import { ReadOperations, AlertingAuthorizationEntity } from '../../authorization'; import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function runSoon(context: RulesClientContext, { id }: { id: string }) { - const { attributes } = await context.unsecuredSavedObjectsClient.get('alert', id); + const { attributes } = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); try { await context.authorization.ensureAuthorized({ ruleTypeId: attributes.alertTypeId, @@ -29,7 +33,7 @@ export async function runSoon(context: RulesClientContext, { id }: { id: string context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.RUN_SOON, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -40,7 +44,7 @@ export async function runSoon(context: RulesClientContext, { id }: { id: string ruleAuditEvent({ action: RuleAuditAction.RUN_SOON, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); diff --git a/x-pack/plugins/alerting/server/rules_client/methods/unmute_all.ts b/x-pack/plugins/alerting/server/rules_client/methods/unmute_all.ts index 52403e2d8f70e..675387e0a600a 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/unmute_all.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/unmute_all.ts @@ -8,7 +8,7 @@ import { RawRule } from '../../types'; import { WriteOperations, AlertingAuthorizationEntity } from '../../authorization'; import { retryIfConflicts } from '../../lib/retry_if_conflicts'; -import { partiallyUpdateAlert } from '../../saved_objects'; +import { partiallyUpdateRule, RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { RulesClientContext } from '../types'; import { updateMetaAttributes } from '../lib'; @@ -28,7 +28,7 @@ export async function unmuteAll( async function unmuteAllWithOCC(context: RulesClientContext, { id }: { id: string }) { const { attributes, version } = await context.unsecuredSavedObjectsClient.get( - 'alert', + RULE_SAVED_OBJECT_TYPE, id ); @@ -47,7 +47,7 @@ async function unmuteAllWithOCC(context: RulesClientContext, { id }: { id: strin context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.UNMUTE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -58,7 +58,7 @@ async function unmuteAllWithOCC(context: RulesClientContext, { id }: { id: strin ruleAuditEvent({ action: RuleAuditAction.UNMUTE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -73,7 +73,7 @@ async function unmuteAllWithOCC(context: RulesClientContext, { id }: { id: strin }); const updateOptions = { version }; - await partiallyUpdateAlert( + await partiallyUpdateRule( context.unsecuredSavedObjectsClient, id, updateAttributes, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/unmute_instance.ts b/x-pack/plugins/alerting/server/rules_client/methods/unmute_instance.ts index 86c894a7babd0..0b8e422f1a946 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/unmute_instance.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/unmute_instance.ts @@ -12,6 +12,7 @@ import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { MuteOptions } from '../types'; import { RulesClientContext } from '../types'; import { updateMeta } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function unmuteInstance( context: RulesClientContext, @@ -35,7 +36,7 @@ async function unmuteInstanceWithOCC( } ) { const { attributes, version } = await context.unsecuredSavedObjectsClient.get( - 'alert', + RULE_SAVED_OBJECT_TYPE, alertId ); @@ -53,7 +54,7 @@ async function unmuteInstanceWithOCC( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.UNMUTE_ALERT, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId }, error, }) ); @@ -64,7 +65,7 @@ async function unmuteInstanceWithOCC( ruleAuditEvent({ action: RuleAuditAction.UNMUTE_ALERT, outcome: 'unknown', - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId }, }) ); @@ -73,7 +74,7 @@ async function unmuteInstanceWithOCC( const mutedInstanceIds = attributes.mutedInstanceIds || []; if (!attributes.muteAll && mutedInstanceIds.includes(alertInstanceId)) { await context.unsecuredSavedObjectsClient.update( - 'alert', + RULE_SAVED_OBJECT_TYPE, alertId, updateMeta(context, { updatedBy: await context.getUserName(), diff --git a/x-pack/plugins/alerting/server/rules_client/methods/update.ts b/x-pack/plugins/alerting/server/rules_client/methods/update.ts index e302b02a0e163..8fb0de5f3519c 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/update.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/update.ts @@ -37,6 +37,7 @@ import { validateScheduleLimit, ValidateScheduleLimitResult, } from '../../application/rule/methods/get_schedule_frequency'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; type ShouldIncrementRevision = (params?: RuleTypeParams) => boolean; @@ -80,16 +81,23 @@ async function updateWithOCC( try { alertSavedObject = - await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }); + await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ); } catch (e) { // We'll skip invalidating the API key since we failed to load the decrypted saved object context.logger.error( `update(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the object using SOC - alertSavedObject = await context.unsecuredSavedObjectsClient.get('alert', id); + alertSavedObject = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); } const { @@ -127,7 +135,7 @@ async function updateWithOCC( context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.UPDATE, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -138,7 +146,7 @@ async function updateWithOCC( ruleAuditEvent({ action: RuleAuditAction.UPDATE, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); @@ -277,7 +285,7 @@ async function updateAlert( try { updatedObject = await context.unsecuredSavedObjectsClient.create( - 'alert', + RULE_SAVED_OBJECT_TYPE, createAttributes, { id, diff --git a/x-pack/plugins/alerting/server/rules_client/methods/update_api_key.ts b/x-pack/plugins/alerting/server/rules_client/methods/update_api_key.ts index d8d78264c448b..ae9367b13963d 100644 --- a/x-pack/plugins/alerting/server/rules_client/methods/update_api_key.ts +++ b/x-pack/plugins/alerting/server/rules_client/methods/update_api_key.ts @@ -12,6 +12,7 @@ import { bulkMarkApiKeysForInvalidation } from '../../invalidate_pending_api_key import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events'; import { createNewAPIKeySet, updateMeta } from '../lib'; import { RulesClientContext } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export async function updateApiKey( context: RulesClientContext, @@ -32,9 +33,13 @@ async function updateApiKeyWithOCC(context: RulesClientContext, { id }: { id: st try { const decryptedAlert = - await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { - namespace: context.namespace, - }); + await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( + RULE_SAVED_OBJECT_TYPE, + id, + { + namespace: context.namespace, + } + ); oldApiKeyToInvalidate = decryptedAlert.attributes.apiKey; oldApiKeyCreatedByUser = decryptedAlert.attributes.apiKeyCreatedByUser; attributes = decryptedAlert.attributes; @@ -45,7 +50,10 @@ async function updateApiKeyWithOCC(context: RulesClientContext, { id }: { id: st `updateApiKey(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await context.unsecuredSavedObjectsClient.get('alert', id); + const alert = await context.unsecuredSavedObjectsClient.get( + RULE_SAVED_OBJECT_TYPE, + id + ); attributes = alert.attributes; version = alert.version; } @@ -64,7 +72,7 @@ async function updateApiKeyWithOCC(context: RulesClientContext, { id }: { id: st context.auditLogger?.log( ruleAuditEvent({ action: RuleAuditAction.UPDATE_API_KEY, - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, error, }) ); @@ -92,14 +100,16 @@ async function updateApiKeyWithOCC(context: RulesClientContext, { id }: { id: st ruleAuditEvent({ action: RuleAuditAction.UPDATE_API_KEY, outcome: 'unknown', - savedObject: { type: 'alert', id }, + savedObject: { type: RULE_SAVED_OBJECT_TYPE, id }, }) ); context.ruleTypeRegistry.ensureRuleTypeEnabled(attributes.alertTypeId); try { - await context.unsecuredSavedObjectsClient.update('alert', id, updateAttributes, { version }); + await context.unsecuredSavedObjectsClient.update(RULE_SAVED_OBJECT_TYPE, id, updateAttributes, { + version, + }); } catch (e) { // Avoid unused API key await bulkMarkApiKeysForInvalidation( diff --git a/x-pack/plugins/alerting/server/rules_client/tests/bulk_enable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/bulk_enable.test.ts index af03c5908daff..e9317972474cd 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/bulk_enable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/bulk_enable.test.ts @@ -34,6 +34,7 @@ import { } from './test_helpers'; import { TaskStatus } from '@kbn/task-manager-plugin/server'; import { migrateLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -767,12 +768,12 @@ describe('bulkEnableRules', () => { expect(auditLogger.log.mock.calls[0][0]?.event?.action).toEqual('rule_enable'); expect(auditLogger.log.mock.calls[0][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[0][0]?.kibana).toEqual({ - saved_object: { id: 'id1', type: 'alert' }, + saved_object: { id: 'id1', type: RULE_SAVED_OBJECT_TYPE }, }); expect(auditLogger.log.mock.calls[1][0]?.event?.action).toEqual('rule_enable'); expect(auditLogger.log.mock.calls[1][0]?.event?.outcome).toEqual('unknown'); expect(auditLogger.log.mock.calls[1][0]?.kibana).toEqual({ - saved_object: { id: 'id2', type: 'alert' }, + saved_object: { id: 'id2', type: RULE_SAVED_OBJECT_TYPE }, }); }); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/clear_expired_snoozes.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/clear_expired_snoozes.test.ts index b64f192045511..59dbfd8c87998 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/clear_expired_snoozes.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/clear_expired_snoozes.test.ts @@ -25,6 +25,7 @@ import { getBeforeSetup, mockedDateString } from './lib'; import { eventLoggerMock } from '@kbn/event-log-plugin/server/event_logger.mock'; import { TaskStatus } from '@kbn/task-manager-plugin/server'; import { RuleSnooze } from '../../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation', () => ({ bulkMarkApiKeysForInvalidation: jest.fn(), @@ -113,7 +114,7 @@ describe('clearExpiredSnoozes()', () => { ]); await rulesClient.clearExpiredSnoozes({ rule: { ...attributes, id } }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { updatedAt: '2019-02-12T21:01:22.479Z', @@ -158,7 +159,7 @@ describe('clearExpiredSnoozes()', () => { ]); await rulesClient.clearExpiredSnoozes({ rule: { ...attributes, id } }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { updatedAt: '2019-02-12T21:01:22.479Z', @@ -208,7 +209,7 @@ describe('clearExpiredSnoozes()', () => { function setupTestWithSnoozeSchedule(snoozeSchedule: RuleSnooze) { const rule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'name', consumer: 'myApp', diff --git a/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts index a4e581414744a..dbdfea132e2ef 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts @@ -24,6 +24,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup } from './lib'; import { bulkMarkApiKeysForInvalidation } from '../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation'; import { migrateLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -84,7 +85,7 @@ describe('delete()', () => { let rulesClient: RulesClient; const existingAlert = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', consumer: 'myApp', @@ -132,7 +133,7 @@ describe('delete()', () => { test('successfully removes an alert', async () => { const result = await rulesClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); - expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); expect(bulkMarkApiKeysForInvalidation).toHaveBeenCalledTimes(1); expect(bulkMarkApiKeysForInvalidation).toHaveBeenCalledWith( @@ -140,9 +141,13 @@ describe('delete()', () => { expect.any(Object), expect.any(Object) ); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); }); @@ -151,10 +156,10 @@ describe('delete()', () => { const result = await rulesClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); - expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); - expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'delete(): Failed to load API key to invalidate on alert 1: Fail' ); @@ -298,7 +303,7 @@ describe('delete()', () => { action: 'rule_delete', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -316,7 +321,7 @@ describe('delete()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts index ca6c242539a9a..01b9d551174cf 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts @@ -25,6 +25,7 @@ import { eventLoggerMock } from '@kbn/event-log-plugin/server/event_logger.mock' import { TaskStatus } from '@kbn/task-manager-plugin/server'; import { migrateLegacyActions } from '../lib'; import { migrateLegacyActionsMock } from '../lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -103,7 +104,7 @@ describe('disable()', () => { let rulesClient: RulesClient; const existingRule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { consumer: 'myApp', schedule: { interval: '10s' }, @@ -187,7 +188,7 @@ describe('disable()', () => { action: 'rule_disable', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -205,7 +206,7 @@ describe('disable()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -220,11 +221,15 @@ describe('disable()', () => { test('disables an rule', async () => { await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', @@ -294,11 +299,15 @@ describe('disable()', () => { }); await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', @@ -339,7 +348,7 @@ describe('disable()', () => { event: { action: 'untracked-instance', category: ['alerts'], - kind: 'alert', + kind: RULE_SAVED_OBJECT_TYPE, }, kibana: { alert: { @@ -359,7 +368,7 @@ describe('disable()', () => { id: '1', namespace: 'default', rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, type_id: 'myType', }, ], @@ -379,11 +388,15 @@ describe('disable()', () => { taskManager.get.mockRejectedValueOnce(new Error('Fail')); await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', @@ -428,12 +441,16 @@ describe('disable()', () => { test('falls back when getDecryptedAsInternalUser throws an error', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await rulesClient.disable({ id: '1' }); - expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', @@ -522,11 +539,15 @@ describe('disable()', () => { }); await rulesClient.disable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', @@ -571,11 +592,15 @@ describe('disable()', () => { `"Failed to remove task"` ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { consumer: 'myApp', diff --git a/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts index 9ab3a919f01a5..aa587dfb99bfa 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts @@ -24,6 +24,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; import { migrateLegacyActions } from '../lib'; import { migrateLegacyActionsMock } from '../lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -81,7 +82,7 @@ describe('enable()', () => { const existingRule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'name', consumer: 'myApp', @@ -191,7 +192,7 @@ describe('enable()', () => { action: 'rule_enable', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -209,7 +210,7 @@ describe('enable()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -224,12 +225,16 @@ describe('enable()', () => { test('enables a rule', async () => { await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.create).not.toBeCalledWith('api_key_pending_invalidation'); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { name: 'name', @@ -280,13 +285,17 @@ describe('enable()', () => { }); await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.create).not.toBeCalledWith('api_key_pending_invalidation'); expect(rulesClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: myType/name'); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { name: 'name', @@ -353,7 +362,7 @@ describe('enable()', () => { await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { name: 'name', @@ -412,7 +421,7 @@ describe('enable()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); await rulesClient.enable({ id: '1' }); - expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'enable(): Failed to load API key of alert 1: Fail' ); @@ -451,9 +460,13 @@ describe('enable()', () => { test('enables task when scheduledTaskId is defined and task exists', async () => { await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); expect(taskManager.bulkEnable).toHaveBeenCalledWith(['task-123']); }); @@ -464,9 +477,13 @@ describe('enable()', () => { `"Failed to enable task"` ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); }); @@ -487,9 +504,13 @@ describe('enable()', () => { taskManager.get.mockRejectedValueOnce(new Error('Failed to get task!')); await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.bulkEnable).not.toHaveBeenCalled(); expect(taskManager.schedule).toHaveBeenCalledWith({ @@ -511,9 +532,14 @@ describe('enable()', () => { }, scope: ['alerting'], }); - expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith(2, 'alert', '1', { - scheduledTaskId: '1', - }); + expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith( + 2, + RULE_SAVED_OBJECT_TYPE, + '1', + { + scheduledTaskId: '1', + } + ); }); test('schedules task when scheduledTaskId is not defined', async () => { @@ -536,9 +562,13 @@ describe('enable()', () => { }); await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.bulkEnable).not.toHaveBeenCalled(); expect(taskManager.schedule).toHaveBeenCalledWith({ @@ -560,9 +590,14 @@ describe('enable()', () => { }, scope: ['alerting'], }); - expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith(2, 'alert', '1', { - scheduledTaskId: '1', - }); + expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith( + 2, + RULE_SAVED_OBJECT_TYPE, + '1', + { + scheduledTaskId: '1', + } + ); }); test('schedules task when task with scheduledTaskId exists but is unrecognized', async () => { @@ -582,9 +617,13 @@ describe('enable()', () => { taskManager.get.mockResolvedValue({ ...mockTask, status: TaskStatus.Unrecognized }); await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.bulkEnable).not.toHaveBeenCalled(); expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); @@ -607,9 +646,14 @@ describe('enable()', () => { }, scope: ['alerting'], }); - expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith(2, 'alert', '1', { - scheduledTaskId: '1', - }); + expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith( + 2, + RULE_SAVED_OBJECT_TYPE, + '1', + { + scheduledTaskId: '1', + } + ); }); test('throws error when scheduling task fails', async () => { @@ -637,9 +681,13 @@ describe('enable()', () => { ); await rulesClient.enable({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.bulkEnable).not.toHaveBeenCalled(); expect(taskManager.schedule).toHaveBeenCalled(); @@ -681,9 +729,14 @@ describe('enable()', () => { expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.schedule).toHaveBeenCalled(); expect(taskManager.bulkEnable).not.toHaveBeenCalled(); - expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith(2, 'alert', '1', { - scheduledTaskId: '1', - }); + expect(unsecuredSavedObjectsClient.update).toHaveBeenNthCalledWith( + 2, + RULE_SAVED_OBJECT_TYPE, + '1', + { + scheduledTaskId: '1', + } + ); }); describe('legacy actions migration for SIEM', () => { @@ -722,7 +775,7 @@ describe('enable()', () => { }); // to mitigate AAD issues, we call create with overwrite=true and actions related props expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, expect.objectContaining({ ...existingDecryptedSiemRule.attributes, actions: ['fake-action-1'], 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 3aea832752dfa..a6fa751469625 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 @@ -26,6 +26,7 @@ import { RegistryRuleType } from '../../rule_type_registry'; import { schema } from '@kbn/config-schema'; import { enabledRule1, enabledRule2, siemRule1, siemRule2 } from './test_helpers'; import { formatLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/format_legacy_actions', () => { return { @@ -108,7 +109,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -221,7 +222,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -322,7 +323,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -524,7 +525,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -555,7 +556,7 @@ describe('find()', () => { }, { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '20s' }, @@ -738,7 +739,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', schedule: { interval: '10s' }, @@ -769,7 +770,7 @@ describe('find()', () => { }, { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '20s' }, @@ -854,7 +855,7 @@ describe('find()', () => { saved_objects: [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], alertTypeId: 'myType', @@ -893,7 +894,7 @@ describe('find()', () => { fields: ['tags', 'alertTypeId', 'consumer'], filter: null, sortField: undefined, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }); expect(ensureRuleTypeIsAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'rule'); }); @@ -909,7 +910,7 @@ describe('find()', () => { action: 'rule_find', outcome: 'success', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -948,7 +949,7 @@ describe('find()', () => { action: 'rule_find', outcome: 'failure', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, error: { code: 'Error', message: 'Unauthorized', 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 0d29a3fc402d1..c8eaa3eb319ec 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 @@ -23,6 +23,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; import { RecoveredActionGroup } from '../../../common'; import { formatLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/format_legacy_actions', () => { return { @@ -76,7 +77,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -143,7 +144,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -224,7 +225,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -327,7 +328,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -402,7 +403,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -455,7 +456,7 @@ describe('get()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -498,7 +499,7 @@ describe('get()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', consumer: 'myApp', @@ -561,7 +562,7 @@ describe('get()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -583,7 +584,7 @@ describe('get()', () => { action: 'rule_get', outcome: 'success', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -602,7 +603,7 @@ describe('get()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -617,7 +618,7 @@ describe('get()', () => { describe('legacy actions migration for SIEM', () => { const rule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts index 0fe46a07e4e7f..d6c8f0a0df3ec 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts @@ -25,6 +25,7 @@ import { SavedObject } from '@kbn/core/server'; import { RawRule } from '../../types'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, mockedDateString, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -74,7 +75,7 @@ const RuleIntervalSeconds = 1; const BaseRuleSavedObject: SavedObject = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', @@ -139,7 +140,7 @@ const findResults = { }, { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: 'a348a740-9e2c-11ec-bd64-774ed95c43ef', type_id: 'example.always-firing', }, @@ -188,7 +189,7 @@ const findResults = { }, { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: 'a348a740-9e2c-11ec-bd64-774ed95c43ef', type_id: 'example.always-firing', }, @@ -237,7 +238,7 @@ const findResults = { }, { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: 'a348a740-9e2c-11ec-bd64-774ed95c43ef', type_id: 'example.always-firing', }, @@ -286,7 +287,7 @@ const findResults = { }, { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: 'a348a740-9e2c-11ec-bd64-774ed95c43ef', type_id: 'example.always-firing', }, @@ -335,7 +336,7 @@ const findResults = { }, { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: 'a348a740-9e2c-11ec-bd64-774ed95c43ef', type_id: 'example.always-firing', }, @@ -450,7 +451,7 @@ describe('getActionErrorLog()', () => { expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { page: 1, @@ -480,7 +481,7 @@ describe('getActionErrorLog()', () => { expect(eventLogClient.findEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.findEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { page: 3, @@ -554,7 +555,7 @@ describe('getActionErrorLog()', () => { action: 'rule_get_action_error_log', outcome: 'success', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -576,7 +577,7 @@ describe('getActionErrorLog()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts index dee5cb2ab9a81..671dcc59c886f 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts @@ -20,6 +20,7 @@ import { actionsAuthorizationMock } from '@kbn/actions-plugin/server/mocks'; import { AlertingAuthorization } from '../../authorization/alerting_authorization'; import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { getBeforeSetup } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -64,7 +65,7 @@ describe('getAlertState()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -121,7 +122,7 @@ describe('getAlertState()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -176,7 +177,7 @@ describe('getAlertState()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', consumer: 'myApp', diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts index 1521dfdefced3..ba0e2d7a1a485 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts @@ -25,6 +25,7 @@ import { SavedObject } from '@kbn/core/server'; import { EventsFactory } from '../../lib/alert_summary_from_event_log.test'; import { RawRule } from '../../types'; import { getBeforeSetup, mockedDateString, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -78,7 +79,7 @@ const RuleIntervalSeconds = 1; const BaseRuleSavedObject: SavedObject = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts index f1d2dbcacf8fd..c4419ef8386a5 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts @@ -26,6 +26,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, mockedDateString, setGlobalDate } from './lib'; import { getExecutionLogAggregation } from '../../lib/get_execution_log_aggregation'; import { fromKueryExpression } from '@kbn/es-query'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -75,7 +76,7 @@ const RuleIntervalSeconds = 1; const BaseRuleSavedObject: SavedObject = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', @@ -444,7 +445,7 @@ describe('getExecutionLogForRule()', () => { expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { aggs: getExecutionLogAggregation({ @@ -470,7 +471,7 @@ describe('getExecutionLogForRule()', () => { expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { aggs: getExecutionLogAggregation({ @@ -496,7 +497,7 @@ describe('getExecutionLogForRule()', () => { expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { aggs: getExecutionLogAggregation({ @@ -522,7 +523,7 @@ describe('getExecutionLogForRule()', () => { expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds).toHaveBeenCalledTimes(1); expect(eventLogClient.aggregateEventsBySavedObjectIds.mock.calls[0]).toEqual([ - 'alert', + RULE_SAVED_OBJECT_TYPE, ['1'], { aggs: getExecutionLogAggregation({ @@ -662,7 +663,7 @@ describe('getExecutionLogForRule()', () => { action: 'rule_get_execution_log', outcome: 'success', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -684,7 +685,7 @@ describe('getExecutionLogForRule()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/lib.ts b/x-pack/plugins/alerting/server/rules_client/tests/lib.ts index 12da7211fdc12..20c0759e1d628 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/lib.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/lib.ts @@ -13,6 +13,7 @@ import { TaskStatus } from '@kbn/task-manager-plugin/server'; import { ConstructorOptions } from '../rules_client'; import { RuleTypeRegistry } from '../../rule_type_registry'; import { RecoveredActionGroup } from '../../../common'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export const mockedDateString = '2019-02-12T21:01:22.479Z'; @@ -69,7 +70,7 @@ export function getBeforeSetup( enabled: false, }); taskManager.bulkRemove.mockResolvedValue({ - statuses: [{ id: 'taskId', type: 'alert', success: true }], + statuses: [{ id: 'taskId', type: RULE_SAVED_OBJECT_TYPE, success: true }], }); const actionsClient = actionsClientMock.create(); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts index 2b6e2793aa648..cf585cc67a417 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts @@ -20,6 +20,7 @@ import { AlertingAuthorization } from '../../authorization/alerting_authorizatio import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -67,7 +68,7 @@ describe('muteAll()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -88,7 +89,7 @@ describe('muteAll()', () => { await rulesClient.muteAll({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { muteAll: true, @@ -107,7 +108,7 @@ describe('muteAll()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -171,7 +172,7 @@ describe('muteAll()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -196,7 +197,7 @@ describe('muteAll()', () => { action: 'rule_mute', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -205,7 +206,7 @@ describe('muteAll()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -235,7 +236,7 @@ describe('muteAll()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts index 4d7f1a52699cc..3aae21df3133d 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts @@ -20,6 +20,7 @@ import { AlertingAuthorization } from '../../authorization/alerting_authorizatio import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -67,7 +68,7 @@ describe('muteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -82,7 +83,7 @@ describe('muteInstance()', () => { await rulesClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { mutedInstanceIds: ['2'], @@ -99,7 +100,7 @@ describe('muteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -119,7 +120,7 @@ describe('muteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -140,7 +141,7 @@ describe('muteInstance()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -204,7 +205,7 @@ describe('muteInstance()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -223,7 +224,7 @@ describe('muteInstance()', () => { action: 'rule_alert_mute', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -232,7 +233,7 @@ describe('muteInstance()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -258,7 +259,7 @@ describe('muteInstance()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts index 70c6388c41ff4..13ab4778f82bc 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts @@ -23,6 +23,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; import { RecoveredActionGroup } from '../../../common'; import { formatLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/format_legacy_actions', () => { return { @@ -77,7 +78,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -160,7 +161,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { legacyId: 'some-legacy-id', alertTypeId: '123', @@ -243,7 +244,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -333,7 +334,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -395,7 +396,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -442,7 +443,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', consumer: 'myApp', @@ -514,7 +515,7 @@ describe('resolve()', () => { unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, @@ -544,7 +545,7 @@ describe('resolve()', () => { action: 'rule_resolve', outcome: 'success', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -563,7 +564,7 @@ describe('resolve()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -578,7 +579,7 @@ describe('resolve()', () => { describe('legacy actions migration for SIEM', () => { const rule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: '123', schedule: { interval: '10s' }, diff --git a/x-pack/plugins/alerting/server/rules_client/tests/run_soon.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/run_soon.test.ts index 9040096eba8b0..b156838704e0b 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/run_soon.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/run_soon.test.ts @@ -21,6 +21,7 @@ import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { TaskStatus } from '@kbn/task-manager-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -64,7 +65,7 @@ describe('runSoon()', () => { const existingRule = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'name', consumer: 'myApp', @@ -154,7 +155,7 @@ describe('runSoon()', () => { action: 'rule_run_soon', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -172,7 +173,7 @@ describe('runSoon()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/test_helpers.ts b/x-pack/plugins/alerting/server/rules_client/tests/test_helpers.ts index 8b2db34686577..f060187775a8e 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/test_helpers.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/test_helpers.ts @@ -7,6 +7,7 @@ import { AlertConsumers } from '@kbn/rule-data-utils'; import type { SavedObject } from '@kbn/core-saved-objects-server'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; export const savedObjectWith500Error = { id: 'id2', @@ -30,7 +31,7 @@ export const savedObjectWith409Error = { export const defaultRule = { id: 'id1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { name: 'fakeName', consumer: 'fakeConsumer', @@ -44,7 +45,7 @@ export const defaultRule = { export const defaultRuleForBulkDelete = { id: 'id1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { tags: ['ups'], params: { param: 1 }, diff --git a/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts index c8cb134b129d7..f8329f20fc432 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts @@ -20,6 +20,7 @@ import { AlertingAuthorization } from '../../authorization/alerting_authorizatio import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -67,7 +68,7 @@ describe('unmuteAll()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -88,7 +89,7 @@ describe('unmuteAll()', () => { await rulesClient.unmuteAll({ id: '1' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { muteAll: false, @@ -107,7 +108,7 @@ describe('unmuteAll()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -171,7 +172,7 @@ describe('unmuteAll()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -196,7 +197,7 @@ describe('unmuteAll()', () => { action: 'rule_unmute', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -205,7 +206,7 @@ describe('unmuteAll()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -235,7 +236,7 @@ describe('unmuteAll()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts index 4df037b8728f0..8d9232c4381c3 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts @@ -20,6 +20,7 @@ import { AlertingAuthorization } from '../../authorization/alerting_authorizatio import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; const taskManager = taskManagerMock.createStart(); const ruleTypeRegistry = ruleTypeRegistryMock.create(); @@ -67,7 +68,7 @@ describe('unmuteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -82,7 +83,7 @@ describe('unmuteInstance()', () => { await rulesClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { mutedInstanceIds: [], @@ -97,7 +98,7 @@ describe('unmuteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -117,7 +118,7 @@ describe('unmuteInstance()', () => { const rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -138,7 +139,7 @@ describe('unmuteInstance()', () => { beforeEach(() => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [ { @@ -202,7 +203,7 @@ describe('unmuteInstance()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -221,7 +222,7 @@ describe('unmuteInstance()', () => { action: 'rule_alert_unmute', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -230,7 +231,7 @@ describe('unmuteInstance()', () => { const rulesClient = new RulesClient({ ...rulesClientParams, auditLogger }); unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], schedule: { interval: '10s' }, @@ -256,7 +257,7 @@ describe('unmuteInstance()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { 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 c151e4f75e99e..aa03a71d93e14 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 @@ -28,6 +28,7 @@ import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; import { bulkMarkApiKeysForInvalidation } from '../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation'; import { migrateLegacyActions } from '../lib'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => { return { @@ -106,7 +107,7 @@ describe('update()', () => { let actionsClient: jest.Mocked; const existingAlert = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -238,7 +239,7 @@ describe('update()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -376,14 +377,18 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); expect(bulkMarkApiKeysForInvalidationMock).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -537,7 +542,7 @@ describe('update()', () => { actionsClient.isPreconfigured.mockReturnValueOnce(true); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -628,7 +633,7 @@ describe('update()', () => { expect(unsecuredSavedObjectsClient.create).toHaveBeenNthCalledWith( 1, - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -728,9 +733,13 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(actionsClient.isPreconfigured).toHaveBeenCalledTimes(3); }); @@ -789,7 +798,7 @@ describe('update()', () => { actionsClient.isSystemAction.mockReturnValueOnce(true); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -872,7 +881,7 @@ describe('update()', () => { expect(unsecuredSavedObjectsClient.create).toHaveBeenNthCalledWith( 1, - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -964,9 +973,13 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(actionsClient.isSystemAction).toHaveBeenCalledTimes(3); }); @@ -1017,7 +1030,7 @@ describe('update()', () => { })); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -1077,7 +1090,7 @@ describe('update()', () => { expect(extractReferencesFn).toHaveBeenCalledWith(ruleParams); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -1161,7 +1174,7 @@ describe('update()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -1254,7 +1267,7 @@ describe('update()', () => { expect.any(Object) ); expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -1321,7 +1334,7 @@ describe('update()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, schedule: { interval: '1m' }, @@ -1407,7 +1420,7 @@ describe('update()', () => { `); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -1563,7 +1576,7 @@ describe('update()', () => { it('should trim alert name in the API key name', async () => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, name: ' my alert name ', @@ -1613,7 +1626,7 @@ describe('update()', () => { it('swallows error when invalidate API key throws', async () => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -1721,7 +1734,7 @@ describe('update()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -1840,7 +1853,7 @@ describe('update()', () => { ], }, }); - expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); expect(rulesClientParams.logger.error).toHaveBeenCalledWith( 'update(): Failed to load API key to invalidate on alert 1: Fail' ); @@ -1920,7 +1933,7 @@ describe('update()', () => { }); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: alertId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], enabled: true, @@ -1947,7 +1960,7 @@ describe('update()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: alertId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: updatedSchedule, @@ -2374,7 +2387,7 @@ describe('update()', () => { actionsClient.isPreconfigured.mockReturnValueOnce(true); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -2436,7 +2449,7 @@ describe('update()', () => { expect(unsecuredSavedObjectsClient.create).toHaveBeenNthCalledWith( 1, - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -2502,9 +2515,13 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(actionsClient.isPreconfigured).toHaveBeenCalledTimes(1); }); @@ -2549,7 +2566,7 @@ describe('update()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -2700,7 +2717,7 @@ describe('update()', () => { beforeEach(() => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { alertTypeId: 'myType', consumer: 'myApp', @@ -2779,7 +2796,7 @@ describe('update()', () => { beforeEach(() => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -2817,7 +2834,7 @@ describe('update()', () => { action: 'rule_update', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -2850,7 +2867,7 @@ describe('update()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { @@ -2885,7 +2902,7 @@ describe('update()', () => { ]); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -2980,7 +2997,7 @@ describe('update()', () => { }, }); expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, { actions: [ { @@ -3031,7 +3048,7 @@ describe('update()', () => { beforeEach(() => { unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -3093,7 +3110,7 @@ describe('update()', () => { }); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, schedule: { interval: '1m' }, @@ -3190,7 +3207,7 @@ describe('update()', () => { expect(bulkMarkApiKeysForInvalidationMock).not.toHaveBeenCalled(); expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual(RULE_SAVED_OBJECT_TYPE); expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ diff --git a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts index f9cd570afa430..de54ab9f8d5f1 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts @@ -21,6 +21,7 @@ import { ActionsAuthorization } from '@kbn/actions-plugin/server'; import { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks'; import { getBeforeSetup, setGlobalDate } from './lib'; import { bulkMarkApiKeysForInvalidation } from '../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation'; +import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects'; jest.mock('../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation', () => ({ bulkMarkApiKeysForInvalidation: jest.fn(), @@ -73,7 +74,7 @@ describe('updateApiKey()', () => { let rulesClient: RulesClient; const existingAlert = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { revision: 0, schedule: { interval: '10s' }, @@ -117,11 +118,15 @@ describe('updateApiKey()', () => { }); await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { schedule: { interval: '10s' }, @@ -174,11 +179,15 @@ describe('updateApiKey()', () => { }); await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { schedule: { interval: '10s' }, @@ -226,11 +235,15 @@ describe('updateApiKey()', () => { }); await rulesClient.updateApiKey({ id: '1' }); expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { schedule: { interval: '10s' }, @@ -282,12 +295,16 @@ describe('updateApiKey()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await rulesClient.updateApiKey({ id: '1' }); - expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); - expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { - namespace: 'default', - }); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith(RULE_SAVED_OBJECT_TYPE, '1'); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + '1', + { + namespace: 'default', + } + ); expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { schedule: { interval: '10s' }, @@ -401,7 +418,7 @@ describe('updateApiKey()', () => { action: 'rule_update_api_key', outcome: 'unknown', }), - kibana: { saved_object: { id: '1', type: 'alert' } }, + kibana: { saved_object: { id: '1', type: RULE_SAVED_OBJECT_TYPE } }, }) ); }); @@ -419,7 +436,7 @@ describe('updateApiKey()', () => { kibana: { saved_object: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, }, error: { 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 d36c4a72d2bd2..821a04601c62d 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 @@ -24,6 +24,7 @@ import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { RetryForConflictsAttempts } from './lib/retry_if_conflicts'; import { TaskStatus } from '@kbn/task-manager-plugin/server/task'; import { RecoveredActionGroup } from '../common'; +import { RULE_SAVED_OBJECT_TYPE } from './saved_objects'; jest.mock('./application/rule/methods/get_schedule_frequency', () => ({ validateScheduleLimit: jest.fn(), @@ -227,7 +228,7 @@ function expectSuccess( // tests to run when the method is expected to fail function expectConflict(success: boolean, err: Error, method: 'update' | 'create' = 'update') { const conflictErrorMessage = SavedObjectsErrorHelpers.createConflictError( - 'alert', + RULE_SAVED_OBJECT_TYPE, MockAlertId ).message; @@ -249,7 +250,7 @@ function mockSavedObjectUpdateConflictErrorTimes(times: number) { // default success value const mockUpdateValue = { id: MockAlertId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'scheduled-task-id', @@ -263,10 +264,10 @@ function mockSavedObjectUpdateConflictErrorTimes(times: number) { // queue up specified number of errors before a success call for (let i = 0; i < times; i++) { unsecuredSavedObjectsClient.update.mockRejectedValueOnce( - SavedObjectsErrorHelpers.createConflictError('alert', MockAlertId) + SavedObjectsErrorHelpers.createConflictError(RULE_SAVED_OBJECT_TYPE, MockAlertId) ); unsecuredSavedObjectsClient.create.mockRejectedValueOnce( - SavedObjectsErrorHelpers.createConflictError('alert', MockAlertId) + SavedObjectsErrorHelpers.createConflictError(RULE_SAVED_OBJECT_TYPE, MockAlertId) ); } } @@ -276,9 +277,9 @@ function setupRawAlertMocks( overrides: Record = {}, attributeOverrides: Record = {} ) { - const rawAlert = { + const rawRule = { id: MockAlertId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, tags: ['foo'], @@ -297,10 +298,10 @@ function setupRawAlertMocks( version: '123', ...overrides, }; - const decryptedRawAlert = { - ...rawAlert, + const decryptedRawRule = { + ...rawRule, attributes: { - ...rawAlert.attributes, + ...rawRule.attributes, apiKey: Buffer.from('123:abc').toString('base64'), }, }; @@ -310,11 +311,11 @@ function setupRawAlertMocks( // splitting this out as it's easier to set a breakpoint :-) unsecuredSavedObjectsClient.get.mockImplementation(async () => { - return cloneDeep(rawAlert); + return cloneDeep(rawRule); }); encryptedSavedObjects.getDecryptedAsInternalUser.mockImplementation(async () => { - return cloneDeep(decryptedRawAlert); + return cloneDeep(decryptedRawRule); }); } 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 0532a48be01e1..76f4943172a4b 100644 --- a/x-pack/plugins/alerting/server/rules_client_factory.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.test.ts @@ -26,6 +26,7 @@ import { AlertingAuthorization } from './authorization'; import { AlertingAuthorizationClientFactory } from './alerting_authorization_client_factory'; import { SECURITY_EXTENSION_ID } from '@kbn/core-saved-objects-server'; import { mockRouter } from '@kbn/core-http-router-server-mocks'; +import { RULE_SAVED_OBJECT_TYPE } from './saved_objects'; jest.mock('./rules_client'); jest.mock('./authorization/alerting_authorization'); @@ -85,7 +86,7 @@ test('creates a rules client with proper constructor arguments when security is expect(savedObjectsService.getScopedClient).toHaveBeenCalledWith(request, { excludedExtensions: [SECURITY_EXTENSION_ID], - includedHiddenTypes: ['alert', 'api_key_pending_invalidation'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE, 'api_key_pending_invalidation'], }); expect(alertingAuthorizationClientFactory.create).toHaveBeenCalledWith(request); @@ -133,7 +134,7 @@ test('creates a rules client with proper constructor arguments', async () => { expect(savedObjectsService.getScopedClient).toHaveBeenCalledWith(request, { excludedExtensions: [SECURITY_EXTENSION_ID], - includedHiddenTypes: ['alert', 'api_key_pending_invalidation'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE, 'api_key_pending_invalidation'], }); expect(alertingAuthorizationClientFactory.create).toHaveBeenCalledWith(request); diff --git a/x-pack/plugins/alerting/server/rules_client_factory.ts b/x-pack/plugins/alerting/server/rules_client_factory.ts index 6f2930429256e..6b637eed5cd1f 100644 --- a/x-pack/plugins/alerting/server/rules_client_factory.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.ts @@ -28,6 +28,7 @@ import { AlertingAuthorizationClientFactory } from './alerting_authorization_cli import { AlertingRulesConfig } from './config'; import { GetAlertIndicesAlias } from './lib'; import { AlertsService } from './alerts_service/alerts_service'; +import { RULE_SAVED_OBJECT_TYPE } from './saved_objects'; export interface RulesClientFactoryOpts { logger: Logger; taskManager: TaskManagerStartContract; @@ -113,7 +114,7 @@ export class RulesClientFactory { maxScheduledPerMinute: this.maxScheduledPerMinute, unsecuredSavedObjectsClient: savedObjects.getScopedClient(request, { excludedExtensions: [SECURITY_EXTENSION_ID], - includedHiddenTypes: ['alert', 'api_key_pending_invalidation'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE, 'api_key_pending_invalidation'], }), authorization: this.authorization.create(request), actionsAuthorization: actions.getActionsAuthorizationWithRequest(request), diff --git a/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts b/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts index 1eff02d732231..85c35693b2b6a 100644 --- a/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts @@ -6,6 +6,7 @@ */ import { SavedObject } from '@kbn/core/server'; +import { RULE_SAVED_OBJECT_TYPE } from '.'; import { RawRule } from '../types'; import { getImportWarnings } from './get_import_warnings'; @@ -14,7 +15,7 @@ describe('getImportWarnings', () => { const savedObjectRules = [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name1', @@ -43,7 +44,7 @@ describe('getImportWarnings', () => { }, { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name2', diff --git a/x-pack/plugins/alerting/server/saved_objects/index.ts b/x-pack/plugins/alerting/server/saved_objects/index.ts index 9006bf1cab1b6..385a5dd25d6bf 100644 --- a/x-pack/plugins/alerting/server/saved_objects/index.ts +++ b/x-pack/plugins/alerting/server/saved_objects/index.ts @@ -23,7 +23,7 @@ import { RawRule } from '../types'; import { getImportWarnings } from './get_import_warnings'; import { isRuleExportable } from './is_rule_exportable'; import { RuleTypeRegistry } from '../rule_type_registry'; -export { partiallyUpdateAlert } from './partially_update_alert'; +export { partiallyUpdateRule } from './partially_update_rule'; export { getLatestRuleVersion, getMinimumCompatibleVersion } from './rule_model_versions'; import { RULES_SETTINGS_SAVED_OBJECT_TYPE, @@ -31,10 +31,12 @@ import { } from '../../common'; import { ruleModelVersions } from './rule_model_versions'; +export const RULE_SAVED_OBJECT_TYPE = 'alert'; + // Use caution when removing items from this array! Any field which has // ever existed in the rule SO must be included in this array to prevent // decryption failures during migration. -export const AlertAttributesExcludedFromAAD = [ +export const RuleAttributesExcludedFromAAD = [ 'scheduledTaskId', 'muteAll', 'mutedInstanceIds', @@ -51,11 +53,11 @@ export const AlertAttributesExcludedFromAAD = [ 'running', ]; -// useful for Pick which is a +// useful for Pick which is a // type which is a subset of RawAlert with just attributes excluded from AAD -// useful for Pick -export type AlertAttributesExcludedFromAADType = +// useful for Pick +export type RuleAttributesExcludedFromAADType = | 'scheduledTaskId' | 'muteAll' | 'mutedInstanceIds' @@ -80,7 +82,7 @@ export function setupSavedObjects( getSearchSourceMigrations: () => MigrateFunctionsObject ) { savedObjects.registerType({ - name: 'alert', + name: RULE_SAVED_OBJECT_TYPE, indexPattern: ALERTING_CASES_SAVED_OBJECT_INDEX, hidden: true, namespaceType: 'multiple-isolated', @@ -146,9 +148,9 @@ export function setupSavedObjects( // Encrypted attributes encryptedSavedObjects.registerType({ - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributesToEncrypt: new Set(['apiKey']), - attributesToExcludeFromAAD: new Set(AlertAttributesExcludedFromAAD), + attributesToExcludeFromAAD: new Set(RuleAttributesExcludedFromAAD), }); // Encrypted attributes diff --git a/x-pack/plugins/alerting/server/saved_objects/is_rule_exportable.test.ts b/x-pack/plugins/alerting/server/saved_objects/is_rule_exportable.test.ts index bf330be87257a..7ed188915c869 100644 --- a/x-pack/plugins/alerting/server/saved_objects/is_rule_exportable.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/is_rule_exportable.test.ts @@ -16,6 +16,7 @@ import { isRuleExportable } from './is_rule_exportable'; import { inMemoryMetricsMock } from '../monitoring/in_memory_metrics.mock'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { AlertingConfig } from '../config'; +import { RULE_SAVED_OBJECT_TYPE } from '.'; let ruleTypeRegistryParams: ConstructorOptions; let logger: MockedLogger; @@ -67,7 +68,7 @@ describe('isRuleExportable', () => { isRuleExportable( { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', @@ -127,7 +128,7 @@ describe('isRuleExportable', () => { isRuleExportable( { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', @@ -190,7 +191,7 @@ describe('isRuleExportable', () => { isRuleExportable( { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', diff --git a/x-pack/plugins/alerting/server/saved_objects/migrations/7.16/index.ts b/x-pack/plugins/alerting/server/saved_objects/migrations/7.16/index.ts index bf2870eb613bb..3984f3e5fb96e 100644 --- a/x-pack/plugins/alerting/server/saved_objects/migrations/7.16/index.ts +++ b/x-pack/plugins/alerting/server/saved_objects/migrations/7.16/index.ts @@ -9,6 +9,7 @@ import { SavedObjectAttribute, SavedObjectReference } from '@kbn/core-saved-obje import { SavedObjectUnsanitizedDoc } from '@kbn/core-saved-objects-server'; import { EncryptedSavedObjectsPluginSetup } from '@kbn/encrypted-saved-objects-plugin/server'; import { isString } from 'lodash/fp'; +import { RULE_SAVED_OBJECT_TYPE } from '../..'; import { RawRule, RawRuleAction } from '../../../types'; import { extractRefsFromGeoContainmentAlert } from '../../geo_containment/migrations'; import { createEsoMigration, isSecuritySolutionLegacyNotification, pipeMigrations } from '../utils'; @@ -126,7 +127,7 @@ function addRuleIdsToLegacyNotificationReferences( } else { const existingReferences = references ?? []; const existingReferenceFound = existingReferences.find((reference) => { - return reference.id === ruleAlertId && reference.type === 'alert'; + return reference.id === ruleAlertId && reference.type === RULE_SAVED_OBJECT_TYPE; }); if (existingReferenceFound) { // skip this if the references already exists for some uncommon reason so we do not add an additional one. @@ -135,7 +136,7 @@ function addRuleIdsToLegacyNotificationReferences( const savedObjectReference: SavedObjectReference = { id: ruleAlertId, name: 'param:alert_0', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }; const newReferences = [...existingReferences, savedObjectReference]; return { ...doc, references: newReferences }; diff --git a/x-pack/plugins/alerting/server/saved_objects/migrations/index.test.ts b/x-pack/plugins/alerting/server/saved_objects/migrations/index.test.ts index 93b8c647f7154..566911f00171d 100644 --- a/x-pack/plugins/alerting/server/saved_objects/migrations/index.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/migrations/index.test.ts @@ -15,6 +15,7 @@ import { migrationMocks } from '@kbn/core/server/mocks'; import { SavedObjectsUtils } from '@kbn/core-saved-objects-utils-server'; import { RuleType, ruleTypeMappings } from '@kbn/securitysolution-rules'; import { isAnyActionSupportIncidents } from './7.11'; +import { RULE_SAVED_OBJECT_TYPE } from '..'; const migrationContext = migrationMocks.createContext(); const encryptedSavedObjectsSetup = encryptedSavedObjectsMock.createSetup(); @@ -1811,7 +1812,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); @@ -1867,7 +1868,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }; @@ -1882,7 +1883,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); @@ -1923,7 +1924,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); @@ -1944,7 +1945,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }; @@ -1959,7 +1960,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); @@ -2002,7 +2003,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }; @@ -2017,7 +2018,7 @@ describe('successful migrations', () => { { name: 'param:alert_0', id: '123', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ], }); @@ -3208,6 +3209,6 @@ function getMockData( references: [], updated_at: withSavedObjectUpdatedAt ? getUpdatedAt() : undefined, id: uuidv4(), - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }; } diff --git a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts b/x-pack/plugins/alerting/server/saved_objects/partially_update_rule.test.ts similarity index 61% rename from x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts rename to x-pack/plugins/alerting/server/saved_objects/partially_update_rule.test.ts index 7560632d12e5a..2cdcd14d2dea5 100644 --- a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/partially_update_rule.test.ts @@ -11,14 +11,15 @@ import { SavedObjectsErrorHelpers, } from '@kbn/core/server'; -import { partiallyUpdateAlert, PartiallyUpdateableAlertAttributes } from './partially_update_alert'; +import { partiallyUpdateRule, PartiallyUpdateableRuleAttributes } from './partially_update_rule'; import { savedObjectsClientMock } from '@kbn/core/server/mocks'; +import { RULE_SAVED_OBJECT_TYPE } from '.'; const MockSavedObjectsClientContract = savedObjectsClientMock.create(); const MockISavedObjectsRepository = MockSavedObjectsClientContract as unknown as jest.Mocked; -describe('partially_update_alert', () => { +describe('partially_update_rule', () => { beforeEach(() => { jest.resetAllMocks(); }); @@ -28,52 +29,77 @@ describe('partially_update_alert', () => { test('should work with no options', async () => { soClient.update.mockResolvedValueOnce(MockUpdateValue); - await partiallyUpdateAlert(soClient, MockAlertId, DefaultAttributes); - expect(soClient.update).toHaveBeenCalledWith('alert', MockAlertId, DefaultAttributes, {}); + await partiallyUpdateRule(soClient, MockRuleId, DefaultAttributes); + expect(soClient.update).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + MockRuleId, + DefaultAttributes, + {} + ); }); test('should work with extraneous attributes ', async () => { - const attributes = InvalidAttributes as unknown as PartiallyUpdateableAlertAttributes; + const attributes = InvalidAttributes as unknown as PartiallyUpdateableRuleAttributes; soClient.update.mockResolvedValueOnce(MockUpdateValue); - await partiallyUpdateAlert(soClient, MockAlertId, attributes); - expect(soClient.update).toHaveBeenCalledWith('alert', MockAlertId, DefaultAttributes, {}); + await partiallyUpdateRule(soClient, MockRuleId, attributes); + expect(soClient.update).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + MockRuleId, + DefaultAttributes, + {} + ); }); test('should handle SO errors', async () => { soClient.update.mockRejectedValueOnce(new Error('wops')); await expect( - partiallyUpdateAlert(soClient, MockAlertId, DefaultAttributes) + partiallyUpdateRule(soClient, MockRuleId, DefaultAttributes) ).rejects.toThrowError('wops'); }); test('should handle the version option', async () => { soClient.update.mockResolvedValueOnce(MockUpdateValue); - await partiallyUpdateAlert(soClient, MockAlertId, DefaultAttributes, { version: '1.2.3' }); - expect(soClient.update).toHaveBeenCalledWith('alert', MockAlertId, DefaultAttributes, { - version: '1.2.3', - }); + await partiallyUpdateRule(soClient, MockRuleId, DefaultAttributes, { version: '1.2.3' }); + expect(soClient.update).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + MockRuleId, + DefaultAttributes, + { + version: '1.2.3', + } + ); }); test('should handle the ignore404 option', async () => { const err = SavedObjectsErrorHelpers.createGenericNotFoundError(); soClient.update.mockRejectedValueOnce(err); - await partiallyUpdateAlert(soClient, MockAlertId, DefaultAttributes, { ignore404: true }); - expect(soClient.update).toHaveBeenCalledWith('alert', MockAlertId, DefaultAttributes, {}); + await partiallyUpdateRule(soClient, MockRuleId, DefaultAttributes, { ignore404: true }); + expect(soClient.update).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + MockRuleId, + DefaultAttributes, + {} + ); }); test('should handle the namespace option', async () => { soClient.update.mockResolvedValueOnce(MockUpdateValue); - await partiallyUpdateAlert(soClient, MockAlertId, DefaultAttributes, { - namespace: 'bat.cave', - }); - expect(soClient.update).toHaveBeenCalledWith('alert', MockAlertId, DefaultAttributes, { + await partiallyUpdateRule(soClient, MockRuleId, DefaultAttributes, { namespace: 'bat.cave', }); + expect(soClient.update).toHaveBeenCalledWith( + RULE_SAVED_OBJECT_TYPE, + MockRuleId, + DefaultAttributes, + { + namespace: 'bat.cave', + } + ); }); }); }); @@ -100,11 +126,11 @@ const DefaultAttributes = { const InvalidAttributes = { ...DefaultAttributes, foo: 'bar' }; -const MockAlertId = 'alert-id'; +const MockRuleId = 'rule-id'; const MockUpdateValue = { - id: MockAlertId, - type: 'alert', + id: MockRuleId, + type: RULE_SAVED_OBJECT_TYPE, attributes: { actions: [], scheduledTaskId: 'scheduled-task-id', diff --git a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.ts b/x-pack/plugins/alerting/server/saved_objects/partially_update_rule.ts similarity index 63% rename from x-pack/plugins/alerting/server/saved_objects/partially_update_alert.ts rename to x-pack/plugins/alerting/server/saved_objects/partially_update_rule.ts index 2c275a5f602fc..8d79fe300c7e9 100644 --- a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.ts +++ b/x-pack/plugins/alerting/server/saved_objects/partially_update_rule.ts @@ -13,13 +13,17 @@ import { } from '@kbn/core/server'; import { RawRule } from '../types'; -import { AlertAttributesExcludedFromAAD, AlertAttributesExcludedFromAADType } from '.'; +import { + RuleAttributesExcludedFromAAD, + RuleAttributesExcludedFromAADType, + RULE_SAVED_OBJECT_TYPE, +} from '.'; -export type PartiallyUpdateableAlertAttributes = Partial< - Pick +export type PartiallyUpdateableRuleAttributes = Partial< + Pick >; -export interface PartiallyUpdateAlertSavedObjectOptions { +interface PartiallyUpdateRuleSavedObjectOptions { refresh?: SavedObjectsUpdateOptions['refresh']; version?: string; ignore404?: boolean; @@ -29,16 +33,16 @@ export interface PartiallyUpdateAlertSavedObjectOptions { // typed this way so we can send a SavedObjectClient or SavedObjectRepository type SavedObjectClientForUpdate = Pick; -// direct, partial update to an alert saved object via scoped SavedObjectsClient +// direct, partial update to a rule saved object via scoped SavedObjectsClient // using namespace set in the client -export async function partiallyUpdateAlert( +export async function partiallyUpdateRule( savedObjectsClient: SavedObjectClientForUpdate, id: string, - attributes: PartiallyUpdateableAlertAttributes, - options: PartiallyUpdateAlertSavedObjectOptions = {} + attributes: PartiallyUpdateableRuleAttributes, + options: PartiallyUpdateRuleSavedObjectOptions = {} ): Promise { // ensure we only have the valid attributes excluded from AAD - const attributeUpdates = pick(attributes, AlertAttributesExcludedFromAAD); + const attributeUpdates = pick(attributes, RuleAttributesExcludedFromAAD); const updateOptions: SavedObjectsUpdateOptions = pick( options, 'namespace', @@ -47,7 +51,12 @@ export async function partiallyUpdateAlert( ); try { - await savedObjectsClient.update('alert', id, attributeUpdates, updateOptions); + await savedObjectsClient.update( + RULE_SAVED_OBJECT_TYPE, + id, + attributeUpdates, + updateOptions + ); } catch (err) { if (options?.ignore404 && SavedObjectsErrorHelpers.isNotFoundError(err)) { return; diff --git a/x-pack/plugins/alerting/server/saved_objects/transform_rule_for_export.test.ts b/x-pack/plugins/alerting/server/saved_objects/transform_rule_for_export.test.ts index 1269a9a776307..7b11ab75f868d 100644 --- a/x-pack/plugins/alerting/server/saved_objects/transform_rule_for_export.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/transform_rule_for_export.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '.'; import { transformRulesForExport } from './transform_rule_for_export'; jest.mock('../lib/rule_execution_status', () => ({ getRuleExecutionStatusPendingAttributes: () => ({ @@ -18,7 +19,7 @@ describe('transform rule for export', () => { const mockRules = [ { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: true, name: 'rule-name', @@ -51,7 +52,7 @@ describe('transform rule for export', () => { }, { id: '2', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, attributes: { enabled: false, name: 'disabled-rule', diff --git a/x-pack/plugins/alerting/server/task_runner/execution_handler.test.ts b/x-pack/plugins/alerting/server/task_runner/execution_handler.test.ts index 2fbb7132e0a6f..c08fb5490fbb9 100644 --- a/x-pack/plugins/alerting/server/task_runner/execution_handler.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/execution_handler.test.ts @@ -36,6 +36,7 @@ import { mockAAD } from './fixtures'; import { schema } from '@kbn/config-schema'; import { alertsClientMock } from '../alerts_client/alerts_client.mock'; import { ExecutionResponseType } from '@kbn/actions-plugin/server/create_execute_function'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; jest.mock('./inject_action_params', () => ({ injectActionParams: jest.fn(), @@ -359,13 +360,13 @@ describe('Execution Handler', () => { }, source: asSavedObjectExecutionSource({ id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }), relatedSavedObjects: [ { id: '1', namespace: 'test1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: 'test', }, ], @@ -1683,8 +1684,10 @@ describe('Execution Handler', () => { executionId: '5f6aa57d-3e22-484e-bae8-cbed868f4d28', id: '1', params: {}, - relatedSavedObjects: [{ id: '1', namespace: 'test1', type: 'alert', typeId: 'test' }], - source: { source: { id: '1', type: 'alert' }, type: 'SAVED_OBJECT' }, + relatedSavedObjects: [ + { id: '1', namespace: 'test1', type: RULE_SAVED_OBJECT_TYPE, typeId: 'test' }, + ], + source: { source: { id: '1', type: RULE_SAVED_OBJECT_TYPE }, type: 'SAVED_OBJECT' }, spaceId: 'test1', }, ]); diff --git a/x-pack/plugins/alerting/server/task_runner/execution_handler.ts b/x-pack/plugins/alerting/server/task_runner/execution_handler.ts index e5fbe92238a0c..29f56b630eaf8 100644 --- a/x-pack/plugins/alerting/server/task_runner/execution_handler.ts +++ b/x-pack/plugins/alerting/server/task_runner/execution_handler.ts @@ -51,6 +51,7 @@ import { isSummaryActionOnInterval, isSummaryActionThrottled, } from './rule_action_helper'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; enum Reasons { MUTED = 'muted', @@ -554,13 +555,13 @@ export class ExecutionHandler< consumer: ruleConsumer, source: asSavedObjectExecutionSource({ id: ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }), executionId, relatedSavedObjects: [ { id: ruleId, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, namespace: namespace.namespace, typeId: this.ruleType.id, }, diff --git a/x-pack/plugins/alerting/server/task_runner/fixtures.ts b/x-pack/plugins/alerting/server/task_runner/fixtures.ts index c1c4b442de13e..b975f21304013 100644 --- a/x-pack/plugins/alerting/server/task_runner/fixtures.ts +++ b/x-pack/plugins/alerting/server/task_runner/fixtures.ts @@ -20,6 +20,7 @@ import { getDefaultMonitoring } from '../lib/monitoring'; import { UntypedNormalizedRuleType } from '../rule_type_registry'; import { EVENT_LOG_ACTIONS } from '../plugin'; import { RawRule } from '../types'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; interface GeneratorParams { [key: string]: string | number | boolean | undefined | object[] | boolean[] | object; @@ -81,7 +82,7 @@ export const generateSavedObjectParams = ({ history?: RuleMonitoring['run']['history']; alertsCount?: Record; }) => [ - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { monitoring: { @@ -213,7 +214,7 @@ export const mockedRuleTypeSavedObject: Rule = { export const mockedRawRuleSO: SavedObject = { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, references: [], attributes: { legacyId: '1', @@ -419,14 +420,14 @@ export const generateEnqueueFunctionInput = ({ { id: '1', namespace: undefined, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, typeId: RULE_TYPE_ID, }, ], source: { source: { id: '1', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, type: 'SAVED_OBJECT', }, diff --git a/x-pack/plugins/alerting/server/task_runner/rule_loader.test.ts b/x-pack/plugins/alerting/server/task_runner/rule_loader.test.ts index 5371e56ff07b2..380d436c95e65 100644 --- a/x-pack/plugins/alerting/server/task_runner/rule_loader.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/rule_loader.test.ts @@ -18,6 +18,7 @@ import { MONITORING_HISTORY_LIMIT, RuleExecutionStatusErrorReasons } from '../.. import { ErrorWithReason, getReasonFromError } from '../lib/error_with_reason'; import { alertingEventLoggerMock } from '../lib/alerting_event_logger/alerting_event_logger.mock'; import { mockedRawRuleSO, mockedRule } from './fixtures'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; // create mocks const rulesClient = rulesClientMock.create(); @@ -199,7 +200,7 @@ describe('rule_loader', () => { expect(contextMock.spaceIdToNamespace.mock.calls[0]).toEqual(['default']); const esoArgs = encryptedSavedObjects.getDecryptedAsInternalUser.mock.calls[0]; - expect(esoArgs).toEqual(['alert', ruleId, { namespace: undefined }]); + expect(esoArgs).toEqual([RULE_SAVED_OBJECT_TYPE, ruleId, { namespace: undefined }]); }); test('succeeds with non-default space', async () => { @@ -218,7 +219,7 @@ describe('rule_loader', () => { }); const esoArgs = encryptedSavedObjects.getDecryptedAsInternalUser.mock.calls[0]; - expect(esoArgs).toEqual(['alert', ruleId, { namespace: spaceId }]); + expect(esoArgs).toEqual([RULE_SAVED_OBJECT_TYPE, ruleId, { namespace: spaceId }]); }); test('fails', async () => { diff --git a/x-pack/plugins/alerting/server/task_runner/rule_loader.ts b/x-pack/plugins/alerting/server/task_runner/rule_loader.ts index f6bb71aef7453..fb037b802ec9b 100644 --- a/x-pack/plugins/alerting/server/task_runner/rule_loader.ts +++ b/x-pack/plugins/alerting/server/task_runner/rule_loader.ts @@ -24,6 +24,7 @@ import { } from '../types'; import { MONITORING_HISTORY_LIMIT, RuleTypeParams } from '../../common'; import { AlertingEventLogger } from '../lib/alerting_event_logger/alerting_event_logger'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; export interface RuleData extends LoadedIndirectParams { indirectParams: RawRule; @@ -114,7 +115,7 @@ export async function getRuleAttributes( const namespace = context.spaceIdToNamespace(spaceId); const rawRule = await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + RULE_SAVED_OBJECT_TYPE, ruleId, { namespace } ); diff --git a/x-pack/plugins/alerting/server/task_runner/running_handler.test.ts b/x-pack/plugins/alerting/server/task_runner/running_handler.test.ts index ce3a3c6680e7b..3ebb122b3a19a 100644 --- a/x-pack/plugins/alerting/server/task_runner/running_handler.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/running_handler.test.ts @@ -6,11 +6,11 @@ */ import { ISavedObjectsRepository, Logger } from '@kbn/core/server'; -import { partiallyUpdateAlert } from '../saved_objects/partially_update_alert'; +import { partiallyUpdateRule } from '../saved_objects/partially_update_rule'; import { RunningHandler } from './running_handler'; -jest.mock('../saved_objects/partially_update_alert', () => ({ - partiallyUpdateAlert: jest.fn(), +jest.mock('../saved_objects/partially_update_rule', () => ({ + partiallyUpdateRule: jest.fn(), })); describe('isRunning handler', () => { @@ -20,7 +20,7 @@ describe('isRunning handler', () => { } as unknown as Logger; const ruleTypeId = 'myType'; beforeEach(() => { - (partiallyUpdateAlert as jest.Mock).mockClear(); + (partiallyUpdateRule as jest.Mock).mockClear(); (logger.error as jest.Mock).mockClear(); jest.useFakeTimers(); }); @@ -29,23 +29,23 @@ describe('isRunning handler', () => { }); test('Should resolve if nothing got started', async () => { - (partiallyUpdateAlert as jest.Mock).mockImplementation(() => Promise.resolve('resolve')); + (partiallyUpdateRule as jest.Mock).mockImplementation(() => Promise.resolve('resolve')); const runHandler = new RunningHandler(soClient, logger, ruleTypeId); const resp = await runHandler.waitFor(); - expect(partiallyUpdateAlert).toHaveBeenCalledTimes(0); + expect(partiallyUpdateRule).toHaveBeenCalledTimes(0); expect(logger.error).toHaveBeenCalledTimes(0); expect(resp).toBe(undefined); }); - test('Should return the promise from partiallyUpdateAlert when the update isRunning has been a success', async () => { - (partiallyUpdateAlert as jest.Mock).mockImplementation(() => Promise.resolve('resolve')); + test('Should return the promise from partiallyUpdateRule when the update isRunning has been a success', async () => { + (partiallyUpdateRule as jest.Mock).mockImplementation(() => Promise.resolve('resolve')); const runHandler = new RunningHandler(soClient, logger, ruleTypeId); runHandler.start('9876543210'); jest.runAllTimers(); const resp = await runHandler.waitFor(); - expect(partiallyUpdateAlert).toHaveBeenCalledTimes(1); - expect((partiallyUpdateAlert as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` + expect(partiallyUpdateRule).toHaveBeenCalledTimes(1); + expect((partiallyUpdateRule as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` Array [ [MockFunction], "9876543210", @@ -64,15 +64,13 @@ describe('isRunning handler', () => { }); test('Should reject when the update isRunning has been a failure', async () => { - (partiallyUpdateAlert as jest.Mock).mockImplementation(() => - Promise.reject(new Error('error')) - ); + (partiallyUpdateRule as jest.Mock).mockImplementation(() => Promise.reject(new Error('error'))); const runHandler = new RunningHandler(soClient, logger, ruleTypeId); runHandler.start('9876543210'); jest.runAllTimers(); await expect(runHandler.waitFor()).rejects.toThrow(); - expect(partiallyUpdateAlert).toHaveBeenCalledTimes(1); + expect(partiallyUpdateRule).toHaveBeenCalledTimes(1); expect(logger.error).toHaveBeenCalledTimes(1); }); }); diff --git a/x-pack/plugins/alerting/server/task_runner/running_handler.ts b/x-pack/plugins/alerting/server/task_runner/running_handler.ts index 118f13ab6eed9..1602e9421ecef 100644 --- a/x-pack/plugins/alerting/server/task_runner/running_handler.ts +++ b/x-pack/plugins/alerting/server/task_runner/running_handler.ts @@ -6,7 +6,7 @@ */ import { ISavedObjectsRepository, Logger } from '@kbn/core/server'; -import { partiallyUpdateAlert } from '../saved_objects/partially_update_alert'; +import { partiallyUpdateRule } from '../saved_objects/partially_update_rule'; const TIME_TO_WAIT = 2000; @@ -45,7 +45,7 @@ export class RunningHandler { private setRunning(ruleId: string, namespace?: string) { this.isUpdating = true; - this.runningPromise = partiallyUpdateAlert( + this.runningPromise = partiallyUpdateRule( this.client, ruleId, { running: true }, 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 ee55378d08795..23d5d5f576ce3 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 @@ -82,6 +82,7 @@ import { alertsServiceMock } from '../alerts_service/alerts_service.mock'; import { getMockMaintenanceWindow } from '../data/maintenance_window/test_helpers'; import { alertsClientMock } from '../alerts_client/alerts_client.mock'; import { MaintenanceWindow } from '../application/maintenance_window/types'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; jest.mock('uuid', () => ({ v4: () => '5f6aa57d-3e22-484e-bae8-cbed868f4d28', @@ -2101,7 +2102,10 @@ describe('Task Runner', () => { test('reschedules for smaller interval if es connectivity error encountered and schedule interval is greater than connectivity retry', async () => { rulesClient.getAlertFromRaw.mockImplementation(() => { - throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError('alert', '1'); + throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError( + RULE_SAVED_OBJECT_TYPE, + '1' + ); }); const taskRunner = new TaskRunner({ 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 4a1245f29ee82..532dd7b1e12ba 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -43,7 +43,7 @@ import { import { asErr, asOk, isErr, isOk, map, resolveErr, Result } from '../lib/result_type'; import { taskInstanceToAlertTaskInstance } from './alert_task_instance'; import { isAlertSavedObjectNotFoundError, isEsUnavailableError } from '../lib/is_alerting_error'; -import { partiallyUpdateAlert } from '../saved_objects'; +import { partiallyUpdateRule, RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; import { AlertInstanceContext, AlertInstanceState, @@ -221,7 +221,7 @@ export class TaskRunner< // eslint-disable-next-line no-empty } catch {} try { - await partiallyUpdateAlert( + await partiallyUpdateRule( client, ruleId, { ...attributes, running: false }, @@ -473,7 +473,7 @@ export class TaskRunner< }; const savedObjectsClient = this.context.savedObjects.getScopedClient(fakeRequest, { - includedHiddenTypes: ['alert', 'action'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE, 'action'], }); const dataViews = await this.context.dataViews.dataViewsServiceFactory( diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts index 46783154a6a4a..0ce2f758ade39 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts @@ -58,6 +58,7 @@ import { dataViewPluginMocks } from '@kbn/data-views-plugin/public/mocks'; import { rulesSettingsClientMock } from '../rules_settings_client.mock'; import { maintenanceWindowClientMock } from '../maintenance_window_client.mock'; import { alertsServiceMock } from '../alerts_service/alerts_service.mock'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; jest.mock('uuid', () => ({ v4: () => '5f6aa57d-3e22-484e-bae8-cbed868f4d28', @@ -222,7 +223,7 @@ describe('Task Runner Cancel', () => { expect( taskRunnerFactoryInitializerParams.internalSavedObjectsRepository.update ).toHaveBeenCalledWith( - 'alert', + RULE_SAVED_OBJECT_TYPE, '1', { executionStatus: { diff --git a/x-pack/plugins/alerting/server/usage/task.ts b/x-pack/plugins/alerting/server/usage/task.ts index e7008056677d0..507970d436d6f 100644 --- a/x-pack/plugins/alerting/server/usage/task.ts +++ b/x-pack/plugins/alerting/server/usage/task.ts @@ -20,6 +20,7 @@ import { getExecutionTimeoutsPerDayCount, } from './lib/get_telemetry_from_event_log'; import { stateSchemaByVersion, emptyState, type LatestTaskStateSchema } from './task_state'; +import { RULE_SAVED_OBJECT_TYPE } from '../saved_objects'; export const TELEMETRY_TASK_TYPE = 'alerting_telemetry'; @@ -90,7 +91,7 @@ export function telemetryTaskRunner( const getAlertIndex = () => core .getStartServices() - .then(([coreStart]) => coreStart.savedObjects.getIndexForType('alert')); + .then(([coreStart]) => coreStart.savedObjects.getIndexForType(RULE_SAVED_OBJECT_TYPE)); return { async run() { diff --git a/x-pack/test/alerting_api_integration/common/plugins/aad/server/plugin.ts b/x-pack/test/alerting_api_integration/common/plugins/aad/server/plugin.ts index 75b66396c269c..a55417d668595 100644 --- a/x-pack/test/alerting_api_integration/common/plugins/aad/server/plugin.ts +++ b/x-pack/test/alerting_api_integration/common/plugins/aad/server/plugin.ts @@ -16,6 +16,7 @@ import { import { schema } from '@kbn/config-schema'; import { EncryptedSavedObjectsPluginStart } from '@kbn/encrypted-saved-objects-plugin/server'; import { SpacesPluginSetup } from '@kbn/spaces-plugin/server'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; interface FixtureSetupDeps { spaces?: SpacesPluginSetup; @@ -49,7 +50,7 @@ export class FixturePlugin implements Plugin { return await savedObjectsWithAlerts.update( - 'alert', + RULE_SAVED_OBJECT_TYPE, id, { ...( await encryptedSavedObjectsWithAlerts.getDecryptedAsInternalUser( - 'alert', + RULE_SAVED_OBJECT_TYPE, id, { namespace, @@ -182,7 +183,7 @@ export function defineRoutes( const [{ savedObjects }] = await core.getStartServices(); const savedObjectsWithAlerts = await savedObjects.getScopedClient(req, { - includedHiddenTypes: ['alert'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE], }); const savedAlert = await savedObjectsWithAlerts.get(type, id); const result = await retryIfConflicts( @@ -223,7 +224,7 @@ export function defineRoutes( const [{ savedObjects }] = await core.getStartServices(); const savedObjectsWithTasksAndAlerts = await savedObjects.getScopedClient(req, { - includedHiddenTypes: ['task', 'alert'], + includedHiddenTypes: ['task', RULE_SAVED_OBJECT_TYPE], }); const result = await retryIfConflicts( logger, @@ -260,9 +261,9 @@ export function defineRoutes( const [{ savedObjects }] = await core.getStartServices(); const savedObjectsWithTasksAndAlerts = await savedObjects.getScopedClient(req, { - includedHiddenTypes: ['task', 'alert'], + includedHiddenTypes: ['task', RULE_SAVED_OBJECT_TYPE], }); - const alert = await savedObjectsWithTasksAndAlerts.get('alert', id); + const alert = await savedObjectsWithTasksAndAlerts.get(RULE_SAVED_OBJECT_TYPE, id); const result = await retryIfConflicts( logger, `/api/alerts_fixture/{id}/reset_task_status`, @@ -422,9 +423,9 @@ export function defineRoutes( attributes: { apiKey, apiKeyOwner }, }: SavedObject = await encryptedSavedObjects .getClient({ - includedHiddenTypes: ['alert'], + includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE], }) - .getDecryptedAsInternalUser('alert', id, { + .getDecryptedAsInternalUser(RULE_SAVED_OBJECT_TYPE, id, { namespace, }); diff --git a/x-pack/test/alerting_api_integration/common/plugins/alerts_restricted/server/plugin.ts b/x-pack/test/alerting_api_integration/common/plugins/alerts_restricted/server/plugin.ts index 66a85b32e6be6..9e78728d1f7a8 100644 --- a/x-pack/test/alerting_api_integration/common/plugins/alerts_restricted/server/plugin.ts +++ b/x-pack/test/alerting_api_integration/common/plugins/alerts_restricted/server/plugin.ts @@ -10,6 +10,7 @@ import { PluginSetupContract as ActionsPluginSetup } from '@kbn/actions-plugin/s import { PluginSetupContract as AlertingPluginSetup } from '@kbn/alerting-plugin/server/plugin'; import { EncryptedSavedObjectsPluginStart } from '@kbn/encrypted-saved-objects-plugin/server'; import { PluginSetupContract as FeaturesPluginSetup } from '@kbn/features-plugin/server'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { defineAlertTypes } from './alert_types'; export interface FixtureSetupDeps { @@ -34,7 +35,7 @@ export class FixturePlugin implements Plugin = { space_1_all_alerts_none_actions: SavedObjectsUtils.getConvertedObjectId( 'space1', - 'alert', + RULE_SAVED_OBJECT_TYPE, '6ee9630a-a20e-44af-9465-217a3717d2ab' ), space_1_all_with_restricted_fixture: SavedObjectsUtils.getConvertedObjectId( 'space1', - 'alert', + RULE_SAVED_OBJECT_TYPE, '5cc59319-74ee-4edc-8646-a79ea91067cd' ), space_1_all: SavedObjectsUtils.getConvertedObjectId( 'space1', - 'alert', + RULE_SAVED_OBJECT_TYPE, 'd41a6abb-b93b-46df-a80a-926221ea847c' ), global_read: SavedObjectsUtils.getConvertedObjectId( 'space1', - 'alert', + RULE_SAVED_OBJECT_TYPE, '362e362b-a137-4aa2-9434-43e3d0d84a34' ), superuser: SavedObjectsUtils.getConvertedObjectId( 'space1', - 'alert', + RULE_SAVED_OBJECT_TYPE, 'b384be60-ec53-4b26-857e-0253ee55b277' ), }; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_all.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_all.ts index 9623462b8ae45..d038108d29f67 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_all.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_all.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -103,7 +104,7 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -164,7 +165,7 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -225,7 +226,7 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -293,7 +294,7 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_instance.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_instance.ts index 3d9f49eb3cffb..97add81c6d5b8 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_instance.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/unmute_instance.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -103,7 +104,7 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -164,7 +165,7 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -225,7 +226,7 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -297,7 +298,7 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update.ts index 31250862265ea..b4a775b7a6635 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update.ts @@ -7,6 +7,7 @@ import expect from '@kbn/expect'; import { Response as SupertestResponse } from 'supertest'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { checkAAD, @@ -146,7 +147,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -238,7 +239,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -330,7 +331,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -429,7 +430,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -526,7 +527,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update_api_key.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update_api_key.ts index 7e2f4e74aa023..3df0570650146 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update_api_key.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group2/tests/alerting/update_api_key.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -99,7 +100,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -155,7 +156,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -211,7 +212,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -278,7 +279,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -340,7 +341,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/bulk_edit.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/bulk_edit.ts index c948791e5ea49..8dec0a90e8d31 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/bulk_edit.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/bulk_edit.ts @@ -7,6 +7,7 @@ import expect from '@kbn/expect'; import type { SanitizedRule } from '@kbn/alerting-plugin/common'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { checkAAD, @@ -123,7 +124,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/clone.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/clone.ts index 2cbec3853f02e..90748d1b2d4cd 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/clone.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/clone.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces, UserAtSpaceScenarios } from '../../../scenarios'; import { checkAAD, @@ -194,7 +195,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts index 905fe05e110e1..77c6efc4e92d8 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts @@ -8,6 +8,7 @@ import expect from '@kbn/expect'; import { generateAPIKeyName } from '@kbn/alerting-plugin/server/rules_client/common'; import { IValidatedEvent } from '@kbn/event-log-plugin/server'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { checkAAD, getEventLog, @@ -128,7 +129,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -184,7 +185,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -248,7 +249,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); @@ -311,7 +312,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); @@ -347,7 +348,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -382,7 +383,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -407,7 +408,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -431,7 +432,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -452,7 +453,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -472,7 +473,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -496,7 +497,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); @@ -519,7 +520,7 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: SuperuserAtSpace1.space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: ruleId, }); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts index 90ddf77f888c3..bf6811b4ad175 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts @@ -13,6 +13,7 @@ import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server'; import { TaskRunning, TaskRunningStage } from '@kbn/task-manager-plugin/server/task_running'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; import { ESTestIndexTool, ES_TEST_INDEX_NAME } from '@kbn/alerting-api-integration-helpers'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios, Superuser } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -1916,7 +1917,7 @@ instanceStateValue: true expect(event?.kibana?.saved_objects).to.eql([ { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: alertId, namespace: spaceId, type_id: ruleObject.alertInfo.ruleTypeId, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/event_log.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/event_log.ts index 9ad165706bc3d..41963a2e488ba 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/event_log.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/event_log.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { descriptorToArray, SavedObjectDescriptor, @@ -85,7 +86,9 @@ export default function eventLogTests({ getService }: FtrProviderContext) { validateEvent(event, { spaceId, - savedObjects: [{ type: 'alert', id: alertId, rel: 'primary', type_id: 'test.noop' }], + savedObjects: [ + { type: RULE_SAVED_OBJECT_TYPE, id: alertId, rel: 'primary', type_id: 'test.noop' }, + ], outcome: 'failure', message: `test.noop:${alertId}: execution failed`, errorMessage: `Unable to decrypt attribute "apiKey" of saved object "${descriptorToArray( diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/snooze.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/snooze.ts index 8073ef48fbefe..8c1fed7978b55 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/snooze.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/snooze.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -114,7 +115,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -176,7 +177,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -238,7 +239,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -307,7 +308,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -388,7 +389,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/unsnooze.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/unsnooze.ts index 2f697b0ee3aff..eae8814a514fb 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/unsnooze.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/unsnooze.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { UserAtSpaceScenarios } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -98,7 +99,7 @@ export default function createUnsnoozeRuleTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -155,7 +156,7 @@ export default function createUnsnoozeRuleTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -212,7 +213,7 @@ export default function createUnsnoozeRuleTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; @@ -276,7 +277,7 @@ export default function createUnsnoozeRuleTests({ getService }: FtrProviderConte await checkAAD({ supertest, spaceId: space.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); break; diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/create.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/create.ts index eb9f90cb41f2a..3d97d39097348 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/create.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/create.ts @@ -9,6 +9,7 @@ import expect from '@kbn/expect'; import { SavedObject } from '@kbn/core/server'; import { RawRule } from '@kbn/alerting-plugin/server/types'; import { ALERTING_CASES_SAVED_OBJECT_INDEX } from '@kbn/core-saved-objects-server'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { checkAAD, @@ -122,7 +123,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); @@ -313,7 +314,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); @@ -380,7 +381,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: customId, }); }); @@ -399,7 +400,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: customId, }); }); @@ -556,7 +557,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts index 39eaa216e7e04..0dccb0ea5a545 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -75,7 +76,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -149,7 +150,12 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex validateEvent(event, { spaceId: Spaces.space1.id, savedObjects: [ - { type: 'alert', id: ruleId, rel: 'primary', type_id: 'test.cumulative-firing' }, + { + type: RULE_SAVED_OBJECT_TYPE, + id: ruleId, + rel: 'primary', + type_id: 'test.cumulative-firing', + }, ], message: "instance 'instance-0' has been untracked because the rule was disabled", shouldHaveEventEnd: false, @@ -193,7 +199,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -237,7 +243,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/enable.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/enable.ts index b9538c786a496..cf49801cb6145 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/enable.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/enable.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -68,7 +69,7 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -124,7 +125,7 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/event_log.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/event_log.ts index 2662ba69f3025..4b0bcba103e10 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/event_log.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/event_log.ts @@ -10,6 +10,7 @@ import expect from '@kbn/expect'; import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server'; import { RuleNotifyWhen } from '@kbn/alerting-plugin/common'; import { ES_TEST_INDEX_NAME, ESTestIndexTool } from '@kbn/alerting-api-integration-helpers'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { getUrlPrefix, @@ -167,7 +168,12 @@ export default function eventLogTests({ getService }: FtrProviderContext) { validateEvent(event, { spaceId: space.id, savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, + { + type: RULE_SAVED_OBJECT_TYPE, + id: alertId, + rel: 'primary', + type_id: 'test.patternFiring', + }, ], message: `rule execution start: "${alertId}"`, shouldHaveTask: true, @@ -186,7 +192,12 @@ export default function eventLogTests({ getService }: FtrProviderContext) { validateEvent(event, { spaceId: space.id, savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, + { + type: RULE_SAVED_OBJECT_TYPE, + id: alertId, + rel: 'primary', + type_id: 'test.patternFiring', + }, { type: 'action', id: createdAction.id, type_id: 'test.noop' }, ], message: `alert: test.patternFiring:${alertId}: 'abc' instanceId: 'instance' scheduled actionGroup: 'default' action: test.noop:${createdAction.id}`, @@ -238,7 +249,12 @@ export default function eventLogTests({ getService }: FtrProviderContext) { validateEvent(event, { spaceId: space.id, savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, + { + type: RULE_SAVED_OBJECT_TYPE, + id: alertId, + rel: 'primary', + type_id: 'test.patternFiring', + }, ], outcome: 'success', message: `rule executed: test.patternFiring:${alertId}: 'abc'`, @@ -289,7 +305,12 @@ export default function eventLogTests({ getService }: FtrProviderContext) { validateEvent(event, { spaceId: space.id, savedObjects: [ - { type: 'alert', id: alertId, rel: 'primary', type_id: 'test.patternFiring' }, + { + type: RULE_SAVED_OBJECT_TYPE, + id: alertId, + rel: 'primary', + type_id: 'test.patternFiring', + }, ], message: `test.patternFiring:${alertId}: 'abc' ${subMessage}`, instanceId: 'instance', diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/execution_status.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/execution_status.ts index a21027ea448b9..9f2dc2ff77eb6 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/execution_status.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/execution_status.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { checkAAD, @@ -49,7 +50,7 @@ export default function executionStatusAlertTests({ getService }: FtrProviderCon await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); @@ -82,7 +83,7 @@ export default function executionStatusAlertTests({ getService }: FtrProviderCon await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); @@ -118,7 +119,7 @@ export default function executionStatusAlertTests({ getService }: FtrProviderCon await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); @@ -151,7 +152,7 @@ export default function executionStatusAlertTests({ getService }: FtrProviderCon await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: response.body.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_all.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_all.ts index 9cfbb1e477526..f6d6f56306753 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_all.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_all.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -45,7 +46,7 @@ export default function createMuteTests({ getService }: FtrProviderContext) { await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -74,7 +75,7 @@ export default function createMuteTests({ getService }: FtrProviderContext) { await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_instance.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_instance.ts index 85dda60babfd0..85f55ce3ba51c 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_instance.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/mute_instance.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -46,7 +47,7 @@ export default function createMuteInstanceTests({ getService }: FtrProviderConte await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -79,7 +80,7 @@ export default function createMuteInstanceTests({ getService }: FtrProviderConte await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_all.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_all.ts index a39f576364d04..24c717a97dcdc 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_all.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_all.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -47,7 +48,7 @@ export default function createUnmuteTests({ getService }: FtrProviderContext) { await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -80,7 +81,7 @@ export default function createUnmuteTests({ getService }: FtrProviderContext) { await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_instance.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_instance.ts index 3dda4b0db49b8..6e6c7c0d368b9 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_instance.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/unmute_instance.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -47,7 +48,7 @@ export default function createUnmuteInstanceTests({ getService }: FtrProviderCon await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -88,7 +89,7 @@ export default function createUnmuteInstanceTests({ getService }: FtrProviderCon await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update.ts index c7dc4e1484580..623a2efc3f005 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { checkAAD, getUrlPrefix, getTestRuleData, ObjectRemover } from '../../../../common/lib'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; @@ -93,7 +94,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -190,7 +191,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update_api_key.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update_api_key.ts index bd3a12d9afdb6..546c4df51c62e 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update_api_key.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/update_api_key.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -53,7 +54,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); @@ -102,7 +103,7 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte await checkAAD({ supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_edit.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_edit.ts index 23e05ed530d4a..7bbf87f9901c2 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_edit.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_edit.ts @@ -8,6 +8,7 @@ import expect from '@kbn/expect'; import { v4 as uuidv4 } from 'uuid'; import type { SanitizedRule } from '@kbn/alerting-plugin/common'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { checkAAD, @@ -81,7 +82,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -183,7 +184,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -229,7 +230,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -275,7 +276,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -340,7 +341,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -417,7 +418,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts index 5611341bd3223..b339f9492b054 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts @@ -11,6 +11,7 @@ import type { RawRule, RawRuleAction } from '@kbn/alerting-plugin/server/types'; import { FILEBEAT_7X_INDICATOR_PATH } from '@kbn/alerting-plugin/server/saved_objects/migrations'; import type { SavedObjectReference } from '@kbn/core/server'; import { ALERTING_CASES_SAVED_OBJECT_INDEX } from '@kbn/core-saved-objects-server'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { getUrlPrefix } from '../../../../common/lib'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; @@ -284,7 +285,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { { name: 'param:alert_0', id: '1a4ed6ae-3c89-44b2-999d-db554144504c', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, }, ]); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/snooze.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/snooze.ts index a658e461917f4..a027a427c9d01 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/snooze.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/snooze.ts @@ -7,6 +7,7 @@ import expect from '@kbn/expect'; import { v4 as uuidv4 } from 'uuid'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -92,7 +93,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -147,7 +148,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); @@ -390,7 +391,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdRule.id, }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/unsnooze.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/unsnooze.ts index 81e246de3214a..31b7c8bf9befc 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/unsnooze.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/unsnooze.ts @@ -6,6 +6,7 @@ */ import expect from '@kbn/expect'; +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import { Spaces } from '../../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { @@ -73,7 +74,7 @@ export default function createSnoozeRuleTests({ getService }: FtrProviderContext await checkAAD({ supertest, spaceId: Spaces.space1.id, - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: createdAlert.id, }); }); diff --git a/x-pack/test_serverless/api_integration/test_suites/common/alerting/rules.ts b/x-pack/test_serverless/api_integration/test_suites/common/alerting/rules.ts index b0813a55325f1..be10f9b83ac6b 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/alerting/rules.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/alerting/rules.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { RULE_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server'; import expect from '@kbn/expect'; import { omit } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; @@ -926,7 +927,7 @@ function validateEventLog(event: any, params: ValidateEventLogParams) { expect(event?.kibana?.saved_objects).to.eql([ { rel: 'primary', - type: 'alert', + type: RULE_SAVED_OBJECT_TYPE, id: params.ruleId, type_id: params.ruleTypeId, }, diff --git a/x-pack/test_serverless/tsconfig.json b/x-pack/test_serverless/tsconfig.json index 72039a6ad1368..54c1e26f069d1 100644 --- a/x-pack/test_serverless/tsconfig.json +++ b/x-pack/test_serverless/tsconfig.json @@ -83,5 +83,6 @@ "@kbn/io-ts-utils", "@kbn/log-explorer-plugin", "@kbn/index-management-plugin", + "@kbn/alerting-plugin", ] }