Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
adcoelho committed Jul 18, 2024
1 parent c76f68e commit e96d350
Show file tree
Hide file tree
Showing 16 changed files with 165 additions and 46 deletions.
12 changes: 12 additions & 0 deletions x-pack/plugins/alerting/common/routes/rule/apis/enable/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export { enableRuleRequestParamsSchema } from './schemas/latest';
export type { EnableRuleRequestParams } from './types/latest';

export { enableRuleRequestParamsSchema as enableRuleRequestParamsSchemaV1 } from './schemas/v1';
export type { EnableRuleRequestParams as EnableRuleRequestParamsV1 } from './types/v1';
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export * from './v1';
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { schema } from '@kbn/config-schema';

export const enableRuleRequestParamsSchema = schema.object({
id: schema.string(),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export * from './v1';
11 changes: 11 additions & 0 deletions x-pack/plugins/alerting/common/routes/rule/apis/enable/types/v1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { TypeOf } from '@kbn/config-schema';
import { enableRuleRequestParamsSchemaV1 } from '..';

export type EnableRuleRequestParams = TypeOf<typeof enableRuleRequestParamsSchemaV1>;
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,43 @@
*/
import { AlertConsumers } from '@kbn/rule-data-utils';

import { RulesClient, ConstructorOptions } from '../rules_client';
import { RulesClient, ConstructorOptions } from '../../../../rules_client/rules_client';
import {
savedObjectsClientMock,
loggingSystemMock,
savedObjectsRepositoryMock,
uiSettingsServiceMock,
} from '@kbn/core/server/mocks';
import { taskManagerMock } from '@kbn/task-manager-plugin/server/mocks';
import { ruleTypeRegistryMock } from '../../rule_type_registry.mock';
import { alertingAuthorizationMock } from '../../authorization/alerting_authorization.mock';
import { ruleTypeRegistryMock } from '../../../../rule_type_registry.mock';
import { alertingAuthorizationMock } from '../../../../authorization/alerting_authorization.mock';
import { encryptedSavedObjectsMock } from '@kbn/encrypted-saved-objects-plugin/server/mocks';
import { actionsAuthorizationMock } from '@kbn/actions-plugin/server/mocks';
import { AlertingAuthorization } from '../../authorization/alerting_authorization';
import { AlertingAuthorization } from '../../../../authorization/alerting_authorization';
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 { migrateLegacyActions } from '../lib';
import { migrateLegacyActionsMock } from '../lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock';
import { ConnectorAdapterRegistry } from '../../connector_adapters/connector_adapter_registry';
import { API_KEY_PENDING_INVALIDATION_TYPE, RULE_SAVED_OBJECT_TYPE } from '../../saved_objects';
import { backfillClientMock } from '../../backfill_client/backfill_client.mock';

jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => {
import { getBeforeSetup, setGlobalDate } from '../../../../rules_client/tests/lib';
import { migrateLegacyActions } from '../../../../rules_client/lib';
import { migrateLegacyActionsMock } from '../../../../rules_client/lib/siem_legacy_actions/retrieve_migrated_legacy_actions.mock';
import { ConnectorAdapterRegistry } from '../../../../connector_adapters/connector_adapter_registry';
import {
API_KEY_PENDING_INVALIDATION_TYPE,
RULE_SAVED_OBJECT_TYPE,
} from '../../../../saved_objects';
import { backfillClientMock } from '../../../../backfill_client/backfill_client.mock';

jest.mock('../../../../rules_client/lib/siem_legacy_actions/migrate_legacy_actions', () => {
return {
migrateLegacyActions: jest.fn(),
};
});

jest.mock('../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation', () => ({
jest.mock('../../../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation', () => ({
bulkMarkApiKeysForInvalidation: jest.fn(),
}));

jest.mock('../../application/rule/methods/get_schedule_frequency', () => ({
jest.mock('../get_schedule_frequency', () => ({
validateScheduleLimit: jest.fn(),
}));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,45 @@
import Boom from '@hapi/boom';
import type { SavedObjectReference } from '@kbn/core/server';
import { TaskStatus } from '@kbn/task-manager-plugin/server';
import { RawRule, IntervalSchedule } from '../../types';
import { resetMonitoringLastRun, getNextRun } from '../../lib';
import { WriteOperations, AlertingAuthorizationEntity } from '../../authorization';
import { retryIfConflicts } from '../../lib/retry_if_conflicts';
import { ruleAuditEvent, RuleAuditAction } from '../common/audit_events';
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<void> {
import { RawRule, IntervalSchedule } from '../../../../types';
import { resetMonitoringLastRun, getNextRun } from '../../../../lib';
import { WriteOperations, AlertingAuthorizationEntity } from '../../../../authorization';
import { retryIfConflicts } from '../../../../lib/retry_if_conflicts';
import { ruleAuditEvent, RuleAuditAction } from '../../../../rules_client/common/audit_events';
import { RulesClientContext } from '../../../../rules_client/types';
import {
updateMeta,
createNewAPIKeySet,
scheduleTask,
migrateLegacyActions,
} from '../../../../rules_client/lib';
import { validateScheduleLimit } from '../get_schedule_frequency';
import { getRuleCircuitBreakerErrorMessage } from '../../../../../common';
import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects';
import { EnableRuleParams } from './types';
import { enableRuleParamsSchema } from './schemas';

export async function enable(context: RulesClientContext, { id }: EnableRuleParams): Promise<void> {
return await retryIfConflicts(
context.logger,
`rulesClient.enable('${id}')`,
async () => await enableWithOCC(context, { id })
);
}

async function enableWithOCC(context: RulesClientContext, { id }: { id: string }) {
async function enableWithOCC(context: RulesClientContext, params: EnableRuleParams) {
let existingApiKey: string | null = null;
let attributes: RawRule;
let version: string | undefined;
let references: SavedObjectReference[];

try {
enableRuleParamsSchema.validate(params);
} catch (error) {
throw Boom.badRequest(`Error validating enable rule parameters - ${error.message}`);
}

const { id } = params;
try {
const decryptedAlert =
await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser<RawRule>(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export type { BulkEnableRulesParams, BulkEnableRulesError, BulkEnableRulesResult } from './types';

export { enable } from './enable';
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { schema } from '@kbn/config-schema';

export const enableRuleParamsSchema = schema.object({
id: schema.string(),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export * from './enable_schemas';
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { TypeOf } from '@kbn/config-schema';
import { enableRuleParamsSchema } from '../schemas';

export type EnableRuleParams = TypeOf<typeof enableRuleParamsSchema>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export * from './enable_types';
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/server/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { updateRuleRoute } from './rule/apis/update/update_rule_route';
import { deleteRuleRoute } from './rule/apis/delete/delete_rule_route';
import { aggregateRulesRoute } from './rule/apis/aggregate/aggregate_rules_route';
import { disableRuleRoute } from './disable_rule';
import { enableRuleRoute } from './enable_rule';
import { enableRuleRoute } from './rule/apis/enable/enable_rule';
import { findRulesRoute, findInternalRulesRoute } from './rule/apis/find/find_rules_route';
import { getRuleAlertSummaryRoute } from './get_rule_alert_summary';
import { getRuleExecutionLogRoute } from './get_rule_execution_log';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

import { enableRuleRoute } from './enable_rule';
import { httpServiceMock } from '@kbn/core/server/mocks';
import { licenseStateMock } from '../lib/license_state.mock';
import { mockHandlerArguments } from './_mock_handler_arguments';
import { rulesClientMock } from '../rules_client.mock';
import { RuleTypeDisabledError } from '../lib/errors/rule_type_disabled';
import { licenseStateMock } from '../../../../lib/license_state.mock';
import { mockHandlerArguments } from '../../../_mock_handler_arguments';
import { rulesClientMock } from '../../../../rules_client.mock';
import { RuleTypeDisabledError } from '../../../../lib/errors/rule_type_disabled';

const rulesClient = rulesClientMock.create();

jest.mock('../lib/license_api_access', () => ({
jest.mock('../../../../lib/license_api_access', () => ({
verifyApiAccess: jest.fn(),
}));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
*/

import { IRouter } from '@kbn/core/server';
import { schema } from '@kbn/config-schema';
import { ILicenseState, RuleTypeDisabledError } from '../lib';
import { verifyAccessAndContext } from './lib';
import { AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../types';
import { ILicenseState, RuleTypeDisabledError } from '../../../../lib';
import { verifyAccessAndContext } from '../../../lib';
import { AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../../../../types';

const paramSchema = schema.object({
id: schema.string(),
});
import {
EnableRuleRequestParamsV1,
enableRuleRequestParamsSchemaV1,
} from '../../../../../common/routes/rule/apis/enable';

export const enableRuleRoute = (
router: IRouter<AlertingRequestHandlerContext>,
Expand All @@ -24,18 +24,19 @@ export const enableRuleRoute = (
path: `${BASE_ALERTING_API_PATH}/rule/{id}/_enable`,
options: {
access: 'public',
summary: `Enable a rule`,
summary: 'Enable a rule',
},
validate: {
params: paramSchema,
params: enableRuleRequestParamsSchemaV1,
},
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const params: EnableRuleRequestParamsV1 = req.params;

try {
await rulesClient.enable({ id });
await rulesClient.enable(params);
return res.noContent();
} catch (e) {
if (e instanceof RuleTypeDisabledError) {
Expand Down
5 changes: 3 additions & 2 deletions x-pack/plugins/alerting/server/rules_client/rules_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ import {
} from '../application/rule/methods/bulk_edit/bulk_edit_rules';
import { bulkEnableRules, BulkEnableRulesParams } from '../application/rule/methods/bulk_enable';
import { updateApiKey } from './methods/update_api_key';
import { enable } from './methods/enable';
import { enable } from '../application/rule/methods/enable/enable';
import { disable } from './methods/disable';
import { clearExpiredSnoozes } from './methods/clear_expired_snoozes';
import { muteInstance } from '../application/rule/methods/mute_alert/mute_instance';
Expand All @@ -75,6 +75,7 @@ import { getBackfill } from '../application/backfill/methods/get';
import { findBackfill } from '../application/backfill/methods/find';
import { deleteBackfill } from '../application/backfill/methods/delete';
import { FindBackfillParams } from '../application/backfill/methods/find/types';
import { EnableRuleParams } from '../application/rule/methods/enable/types';

export type ConstructorOptions = Omit<
RulesClientContext,
Expand Down Expand Up @@ -166,7 +167,7 @@ export class RulesClient {

public updateApiKey = (options: { id: string }) => updateApiKey(this.context, options);

public enable = (options: { id: string }) => enable(this.context, options);
public enable = (params: EnableRuleParams) => enable(this.context, params);
public disable = (options: { id: string; untrack?: boolean }) => disable(this.context, options);

public snooze = (options: SnoozeRuleOptions) => snoozeRule(this.context, options);
Expand Down

0 comments on commit e96d350

Please sign in to comment.