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 415638d
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 65 deletions.
18 changes: 18 additions & 0 deletions x-pack/plugins/alerting/common/routes/rule/apis/disable/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export { disableRuleRequestBodySchema, disableRuleRequestParamsSchema } from './schemas/latest';
export {
disableRuleRequestBodySchema as disableRuleRequestBodySchemaV1,
disableRuleRequestParamsSchema as disableRuleRequestParamsSchemaV1,
} from './schemas/v1';

export type { DisableRuleRequestBody, DisableRuleRequestParams } from './types/latest';
export type {
DisableRuleRequestBody as DisableRuleRequestBodyV1,
DisableRuleRequestParams as DisableRuleRequestParamsV1,
} 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,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

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

export const disableRuleRequestBodySchema = schema.nullable(
schema.maybe(
schema.object({
untrack: schema.maybe(schema.boolean({ defaultValue: false })),
})
)
);

export const disableRuleRequestParamsSchema = 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';
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 { disableRuleRequestBodySchemaV1, disableRuleRequestParamsSchemaV1 } from '..';

export type DisableRuleRequestBody = TypeOf<typeof disableRuleRequestBodySchemaV1>;
export type DisableRuleRequestParams = TypeOf<typeof disableRuleRequestParamsSchemaV1>;
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,37 @@
*/
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 { auditLoggerMock } from '@kbn/security-plugin/server/audit/mocks';
import { getBeforeSetup, setGlobalDate } from './lib';
import { getBeforeSetup, setGlobalDate } from '../../../../rules_client/tests/lib';
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 { ConnectorAdapterRegistry } from '../../connector_adapters/connector_adapter_registry';
import { RULE_SAVED_OBJECT_TYPE } from '../../saved_objects';
import { backfillClientMock } from '../../backfill_client/backfill_client.mock';
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 { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects';
import { backfillClientMock } from '../../../../backfill_client/backfill_client.mock';

jest.mock('../lib/siem_legacy_actions/migrate_legacy_actions', () => {
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(),
}));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,21 @@
*/
import type { SavedObjectReference } from '@kbn/core/server';

import { RawRule } from '../../types';
import { WriteOperations, AlertingAuthorizationEntity } from '../../authorization';
import { retryIfConflicts } from '../../lib/retry_if_conflicts';
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';
import Boom from '@hapi/boom';
import { RawRule } from '../../../../types';
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 { untrackRuleAlerts, updateMeta, migrateLegacyActions } from '../../../../rules_client/lib';
import { RuleAttributes } from '../../../../data/rule/types';
import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects';
import { DisableRuleParams } from './types';
import { disableRuleParamsSchema } from './schemas';

export async function disable(
context: RulesClientContext,
{
id,
untrack = false,
}: {
id: string;
untrack?: boolean;
}
{ id, untrack = false }: DisableRuleParams
): Promise<void> {
return await retryIfConflicts(
context.logger,
Expand All @@ -34,18 +31,18 @@ export async function disable(

async function disableWithOCC(
context: RulesClientContext,
{
id,
untrack = false,
}: {
id: string;
untrack?: boolean;
}
{ id, untrack = false }: DisableRuleParams
) {
let attributes: RawRule;
let version: string | undefined;
let references: SavedObjectReference[];

try {
disableRuleParamsSchema.validate({ id, untrack });
} catch (error) {
throw Boom.badRequest(`Error validating disable rule parameters - ${error.message}`);
}

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

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

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

export const disableRuleParamsSchema = schema.object({
id: schema.string(),
untrack: schema.maybe(schema.boolean({ defaultValue: false })),
});
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.
*/
import type { TypeOf } from '@kbn/config-schema';
import { disableRuleParamsSchema } from '../schemas';

export type DisableRuleParams = TypeOf<typeof disableRuleParamsSchema>;
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 @@ -18,7 +18,7 @@ import { getRuleRoute, getInternalRuleRoute } from './rule/apis/get/get_rule_rou
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 { disableRuleRoute } from './rule/apis/disable/disable_rule_route';
import { enableRuleRoute } from './enable_rule';
import { findRulesRoute, findInternalRulesRoute } from './rule/apis/find/find_rules_route';
import { getRuleAlertSummaryRoute } from './get_rule_alert_summary';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
* 2.0.
*/

import { disableRuleRoute } from './disable_rule';
import { disableRuleRoute } from './disable_rule_route';
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,22 +6,15 @@
*/

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';

const paramSchema = schema.object({
id: schema.string(),
});

const bodySchema = schema.nullable(
schema.maybe(
schema.object({
untrack: schema.maybe(schema.boolean({ defaultValue: false })),
})
)
);
import {
disableRuleRequestParamsSchemaV1,
disableRuleRequestBodySchemaV1,
DisableRuleRequestParamsV1,
DisableRuleRequestBodyV1,
} from '../../../../../common/routes/rule/apis/disable';
import { ILicenseState, RuleTypeDisabledError } from '../../../../lib';
import { verifyAccessAndContext } from '../../../lib';
import { AlertingRequestHandlerContext, BASE_ALERTING_API_PATH } from '../../../../types';

export const disableRuleRoute = (
router: IRouter<AlertingRequestHandlerContext>,
Expand All @@ -32,20 +25,24 @@ export const disableRuleRoute = (
path: `${BASE_ALERTING_API_PATH}/rule/{id}/_disable`,
options: {
access: 'public',
summary: `Disable a rule`,
summary: 'Disable a rule',
},
validate: {
params: paramSchema,
body: bodySchema,
params: disableRuleRequestParamsSchemaV1,
body: disableRuleRequestBodySchemaV1,
},
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const { untrack = false } = req.body || {};
const { id }: DisableRuleRequestParamsV1 = req.params;
const body: DisableRuleRequestBodyV1 = req.body || {};
const { untrack = false } = body;

const disableParams = { id, untrack };

try {
await rulesClient.disable({ id, untrack });
await rulesClient.disable(disableParams);
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 @@ -55,7 +55,7 @@ import {
import { bulkEnableRules, BulkEnableRulesParams } from '../application/rule/methods/bulk_enable';
import { updateApiKey } from './methods/update_api_key';
import { enable } from './methods/enable';
import { disable } from './methods/disable';
import { disable } from '../application/rule/methods/disable/disable';
import { clearExpiredSnoozes } from './methods/clear_expired_snoozes';
import { muteInstance } from '../application/rule/methods/mute_alert/mute_instance';
import { muteAll } from './methods/mute_all';
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 { DisableRuleParams } from '../application/rule/methods/disable';

export type ConstructorOptions = Omit<
RulesClientContext,
Expand Down Expand Up @@ -167,7 +168,7 @@ export class RulesClient {
public updateApiKey = (options: { id: string }) => updateApiKey(this.context, options);

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

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

0 comments on commit 415638d

Please sign in to comment.