Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Security Solution] [Platform] Migrate legacy actions whenever user interacts with the rule #115101

Merged
merged 14 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ export const createPrepackagedRules = async (
);
await updatePrepackagedRules(
rulesClient,
savedObjectsClient,
context.securitySolution.getSpaceId(),
ruleStatusClient,
rulesToUpdate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ export const importRulesRoute = (
} else if (rule != null && request.query.overwrite) {
await patchRules({
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
spaceId: context.securitySolution.getSpaceId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export const patchRulesBulkRoute = (
const rule = await patchRules({
rule: existingRule,
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export const patchRulesRoute = (

const rule = await patchRules({
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export const updateRulesBulkRoute = (
spaceId: context.securitySolution.getSpaceId(),
rulesClient,
ruleStatusClient,
savedObjectsClient,
defaultOutputIndex: siemClient.getSignalsIndex(),
ruleUpdate: payloadRule,
isRuleRegistryEnabled,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export const updateRulesRoute = (
isRuleRegistryEnabled,
rulesClient,
ruleStatusClient,
savedObjectsClient,
ruleUpdate: request.body,
spaceId: context.securitySolution.getSpaceId(),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { PatchRulesOptions } from './types';
import { rulesClientMock } from '../../../../../alerting/server/mocks';
import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks';
import { getAlertMock } from '../routes/__mocks__/request_responses';
import { getMlRuleParams, getQueryRuleParams } from '../schemas/rule_schemas.mock';
import { ruleExecutionLogClientMock } from '../rule_execution_log/__mocks__/rule_execution_log_client';
Expand All @@ -15,6 +16,7 @@ export const getPatchRulesOptionsMock = (isRuleRegistryEnabled: boolean): PatchR
author: ['Elastic'],
buildingBlockType: undefined,
rulesClient: rulesClientMock.create(),
savedObjectsClient: savedObjectsClientMock.create(),
spaceId: 'default',
ruleStatusClient: ruleExecutionLogClientMock.create(),
anomalyThreshold: undefined,
Expand Down Expand Up @@ -68,6 +70,7 @@ export const getPatchMlRulesOptionsMock = (isRuleRegistryEnabled: boolean): Patc
author: ['Elastic'],
buildingBlockType: undefined,
rulesClient: rulesClientMock.create(),
savedObjectsClient: savedObjectsClientMock.create(),
spaceId: 'default',
ruleStatusClient: ruleExecutionLogClientMock.create(),
anomalyThreshold: 55,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
normalizeMachineLearningJobIds,
normalizeThresholdObject,
} from '../../../../common/detection_engine/utils';
// eslint-disable-next-line no-restricted-imports
import { legacyRuleActionsSavedObjectType } from '../rule_actions/legacy_saved_object_mappings';
import { internalRuleUpdate, RuleParams } from '../schemas/rule_schemas';
import { addTags } from './add_tags';
import { enableRule } from './enable_rule';
Expand All @@ -35,8 +37,10 @@ class PatchError extends Error {
}
}

// eslint-disable-next-line complexity
export const patchRules = async ({
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
ruleStatusClient,
Expand Down Expand Up @@ -92,6 +96,39 @@ export const patchRules = async ({
return null;
}

/**
* On update / patch I'm going to take the actions as they are, better off taking rules client.find (siem.notification) result
* and putting that into the actions array of the rule, then set the rules onThrottle property, notifyWhen and throttle from null -> actualy value (1hr etc..)
* Then use the rules client to delete the siem.notification
* Then with the legacy Rule Actions saved object type, just delete it.
*/

// find it using the references array, not params.ruleAlertId
let migratedRule = false;
const siemNotification = await rulesClient.find({
options: {
hasReference: {
type: 'alert',
id: rule.id,
},
},
});

const legacyRuleActionsSO = await savedObjectsClient.find({
type: legacyRuleActionsSavedObjectType,
});
dhurley14 marked this conversation as resolved.
Show resolved Hide resolved

if (siemNotification != null && siemNotification.data.length > 0) {
await rulesClient.delete({ id: siemNotification.data[0].id });
if (legacyRuleActionsSO != null && legacyRuleActionsSO.saved_objects.length > 0) {
await savedObjectsClient.delete(
legacyRuleActionsSavedObjectType,
legacyRuleActionsSO.saved_objects[0].id
);
}
dhurley14 marked this conversation as resolved.
Show resolved Hide resolved
migratedRule = true;
dhurley14 marked this conversation as resolved.
Show resolved Hide resolved
}

const calculatedVersion = calculateVersion(rule.params.immutable, rule.params.version, {
author,
buildingBlockType,
Expand Down Expand Up @@ -191,14 +228,24 @@ export const patchRules = async ({

const newRule = {
tags: addTags(tags ?? rule.tags, rule.params.ruleId, rule.params.immutable),
throttle: throttle !== undefined ? transformToAlertThrottle(throttle) : rule.throttle,
notifyWhen: throttle !== undefined ? transformToNotifyWhen(throttle) : rule.notifyWhen,
name: calculateName({ updatedName: name, originalName: rule.name }),
schedule: {
interval: calculateInterval(interval, rule.schedule.interval),
},
actions: actions?.map(transformRuleToAlertAction) ?? rule.actions,
params: removeUndefined(nextParams),
actions: migratedRule
? siemNotification.data[0].actions
: actions?.map(transformRuleToAlertAction) ?? rule.actions,
throttle: migratedRule
? siemNotification.data[0].schedule.interval
: throttle !== undefined
? transformToAlertThrottle(throttle)
: rule.throttle,
notifyWhen: migratedRule
? transformToNotifyWhen(siemNotification.data[0].throttle)
: throttle !== undefined
? transformToNotifyWhen(throttle)
: rule.notifyWhen,
};

const [validated, errors] = validate(newRule, internalRuleUpdate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@
import { get } from 'lodash/fp';
import { Readable } from 'stream';

import { SavedObject, SavedObjectAttributes, SavedObjectsFindResult } from 'kibana/server';
import {
SavedObject,
SavedObjectAttributes,
SavedObjectsClientContract,
SavedObjectsFindResult,
} from 'kibana/server';
import type {
MachineLearningJobIdOrUndefined,
From,
Expand Down Expand Up @@ -271,12 +276,14 @@ export interface UpdateRulesOptions {
rulesClient: RulesClient;
defaultOutputIndex: string;
ruleUpdate: UpdateRulesSchema;
savedObjectsClient: SavedObjectsClientContract;
}

export interface PatchRulesOptions {
spaceId: string;
ruleStatusClient: IRuleExecutionLogClient;
rulesClient: RulesClient;
savedObjectsClient: SavedObjectsClientContract;
anomalyThreshold: AnomalyThresholdOrUndefined;
author: AuthorOrUndefined;
buildingBlockType: BuildingBlockTypeOrUndefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { rulesClientMock } from '../../../../../alerting/server/mocks';
import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks';
import { getFindResultWithSingleHit } from '../routes/__mocks__/request_responses';
import { updatePrepackagedRules } from './update_prepacked_rules';
import { patchRules } from './patch_rules';
Expand All @@ -19,10 +20,12 @@ describe.each([
])('updatePrepackagedRules - %s', (_, isRuleRegistryEnabled) => {
let rulesClient: ReturnType<typeof rulesClientMock.create>;
let ruleStatusClient: ReturnType<typeof ruleExecutionLogClientMock.create>;
let savedObjectsClient: ReturnType<typeof savedObjectsClientMock.create>;

beforeEach(() => {
rulesClient = rulesClientMock.create();
ruleStatusClient = ruleExecutionLogClientMock.create();
savedObjectsClient = savedObjectsClientMock.create();
});

it('should omit actions and enabled when calling patchRules', async () => {
Expand All @@ -40,6 +43,7 @@ describe.each([

await updatePrepackagedRules(
rulesClient,
savedObjectsClient,
'default',
ruleStatusClient,
[{ ...prepackagedRule, actions }],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { chunk } from 'lodash/fp';
import { SavedObjectsClientContract } from 'kibana/server';
import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema';
import { RulesClient, PartialAlert } from '../../../../../alerting/server';
import { patchRules } from './patch_rules';
Expand Down Expand Up @@ -51,6 +52,7 @@ export const UPDATE_CHUNK_SIZE = 50;
*/
export const updatePrepackagedRules = async (
rulesClient: RulesClient,
savedObjectsClient: SavedObjectsClientContract,
spaceId: string,
ruleStatusClient: IRuleExecutionLogClient,
rules: AddPrepackagedRulesSchemaDecoded[],
Expand All @@ -61,6 +63,7 @@ export const updatePrepackagedRules = async (
for (const ruleChunk of ruleChunks) {
const rulePromises = createPromises(
rulesClient,
savedObjectsClient,
spaceId,
ruleStatusClient,
ruleChunk,
Expand All @@ -82,6 +85,7 @@ export const updatePrepackagedRules = async (
*/
export const createPromises = (
rulesClient: RulesClient,
savedObjectsClient: SavedObjectsClientContract,
spaceId: string,
ruleStatusClient: IRuleExecutionLogClient,
rules: AddPrepackagedRulesSchemaDecoded[],
Expand Down Expand Up @@ -150,6 +154,7 @@ export const createPromises = (
// or enable rules on the user when they were not expecting it if a rule updates
return patchRules({
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { rulesClientMock } from '../../../../../alerting/server/mocks';
import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks';
import {
getUpdateMachineLearningSchemaMock,
getUpdateRulesSchemaMock,
Expand All @@ -16,6 +17,7 @@ export const getUpdateRulesOptionsMock = (isRuleRegistryEnabled: boolean) => ({
spaceId: 'default',
rulesClient: rulesClientMock.create(),
ruleStatusClient: ruleExecutionLogClientMock.create(),
savedObjectsClient: savedObjectsClientMock.create(),
defaultOutputIndex: '.siem-signals-default',
ruleUpdate: getUpdateRulesSchemaMock(),
isRuleRegistryEnabled,
Expand All @@ -25,6 +27,7 @@ export const getUpdateMlRulesOptionsMock = (isRuleRegistryEnabled: boolean) => (
spaceId: 'default',
rulesClient: rulesClientMock.create(),
ruleStatusClient: ruleExecutionLogClientMock.create(),
savedObjectsClient: savedObjectsClientMock.create(),
defaultOutputIndex: '.siem-signals-default',
ruleUpdate: getUpdateMachineLearningSchemaMock(),
isRuleRegistryEnabled,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { typeSpecificSnakeToCamel } from '../schemas/rule_converters';
import { RuleParams } from '../schemas/rule_schemas';
import { enableRule } from './enable_rule';
import { maybeMute, transformToAlertThrottle, transformToNotifyWhen } from './utils';
// eslint-disable-next-line no-restricted-imports
import { legacyRuleActionsSavedObjectType } from '../rule_actions/legacy_saved_object_mappings';

export const updateRules = async ({
isRuleRegistryEnabled,
Expand All @@ -25,6 +27,7 @@ export const updateRules = async ({
ruleStatusClient,
defaultOutputIndex,
ruleUpdate,
savedObjectsClient,
}: UpdateRulesOptions): Promise<PartialAlert<RuleParams> | null> => {
const existingRule = await readRules({
isRuleRegistryEnabled,
Expand All @@ -36,6 +39,44 @@ export const updateRules = async ({
return null;
}

/**
* On update / patch I'm going to take the actions as they are, better off taking rules client.find (siem.notification) result
* and putting that into the actions array of the rule, then set the rules onThrottle property, notifyWhen and throttle from null -> actualy value (1hr etc..)
* Then use the rules client to delete the siem.notification
* Then with the legacy Rule Actions saved object type, just delete it.
*/

// find it using the references array, not params.ruleAlertId
let migratedRule = false;
if (existingRule != null) {
const siemNotification = await rulesClient.find({
options: {
hasReference: {
type: 'alert',
id: existingRule.id,
},
},
});

const legacyRuleActionsSO = await savedObjectsClient.find({
type: legacyRuleActionsSavedObjectType,
});

if (siemNotification != null && siemNotification.data.length > 0) {
existingRule.actions = siemNotification.data[0].actions;
existingRule.throttle = siemNotification.data[0].schedule.interval;
existingRule.notifyWhen = transformToNotifyWhen(siemNotification.data[0].throttle);
await rulesClient.delete({ id: siemNotification.data[0].id });
if (legacyRuleActionsSO != null && legacyRuleActionsSO.saved_objects.length > 0) {
await savedObjectsClient.delete(
legacyRuleActionsSavedObjectType,
legacyRuleActionsSO.saved_objects[0].id
);
}
migratedRule = true;
}
}

const typeSpecificParams = typeSpecificSnakeToCamel(ruleUpdate);
const enabled = ruleUpdate.enabled ?? true;
const newInternalRule = {
Expand Down Expand Up @@ -77,9 +118,13 @@ export const updateRules = async ({
...typeSpecificParams,
},
schedule: { interval: ruleUpdate.interval ?? '5m' },
actions: ruleUpdate.actions != null ? ruleUpdate.actions.map(transformRuleToAlertAction) : [],
throttle: transformToAlertThrottle(ruleUpdate.throttle),
notifyWhen: transformToNotifyWhen(ruleUpdate.throttle),
actions: migratedRule
? existingRule.actions
: ruleUpdate.actions != null
? ruleUpdate.actions.map(transformRuleToAlertAction)
: [],
throttle: migratedRule ? existingRule.throttle : transformToAlertThrottle(ruleUpdate.throttle),
notifyWhen: migratedRule ? existingRule.notifyWhen : transformToNotifyWhen(ruleUpdate.throttle),
};

const update = await rulesClient.update({
Expand Down