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 11 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 @@ -21,6 +21,7 @@ import {
calculateInterval,
calculateName,
calculateVersion,
legacyMigrate,
maybeMute,
removeUndefined,
transformToAlertThrottle,
Expand All @@ -37,6 +38,7 @@ class PatchError extends Error {

export const patchRules = async ({
rulesClient,
savedObjectsClient,
author,
buildingBlockType,
ruleStatusClient,
Expand Down Expand Up @@ -92,6 +94,12 @@ export const patchRules = async ({
return null;
}

const { migratedActions, migratedThrottle, migratedNotifyWhen } = await legacyMigrate({
rulesClient,
savedObjectsClient,
id: rule.id,
});
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 +199,20 @@ 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: actions?.map(transformRuleToAlertAction) ?? migratedActions ?? rule.actions,
throttle:
throttle !== undefined
? transformToAlertThrottle(throttle)
: migratedThrottle ?? rule.throttle,
notifyWhen:
throttle !== undefined
? transformToNotifyWhen(throttle)
: migratedNotifyWhen ?? 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 Expand Up @@ -351,3 +358,9 @@ export interface FindRuleOptions {
fields: FieldsOrUndefined;
sortOrder: SortOrderOrUndefined;
}

export interface LegacyMigrateParams {
rulesClient: RulesClient;
savedObjectsClient: SavedObjectsClientContract;
id: string;
}
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 @@ -6,17 +6,25 @@
*/

/* eslint-disable complexity */

import { validate } from '@kbn/securitysolution-io-ts-utils';
import { DEFAULT_MAX_SIGNALS } from '../../../../common/constants';
import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions';
import { PartialAlert } from '../../../../../alerting/server';
import { readRules } from './read_rules';
import { UpdateRulesOptions } from './types';
import { addTags } from './add_tags';
import { typeSpecificSnakeToCamel } from '../schemas/rule_converters';
import { RuleParams } from '../schemas/rule_schemas';
import { internalRuleUpdate, RuleParams } from '../schemas/rule_schemas';
import { enableRule } from './enable_rule';
import { maybeMute, transformToAlertThrottle, transformToNotifyWhen } from './utils';
import { legacyMigrate, maybeMute, transformToAlertThrottle, transformToNotifyWhen } from './utils';

class UpdateError extends Error {
public readonly statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
}
}

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

const { migratedActions, migratedThrottle, migratedNotifyWhen } = await legacyMigrate({
rulesClient,
savedObjectsClient,
id: existingRule.id,
});

const typeSpecificParams = typeSpecificSnakeToCamel(ruleUpdate);
const enabled = ruleUpdate.enabled ?? true;
const newInternalRule = {
Expand Down Expand Up @@ -77,14 +92,28 @@ 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:
ruleUpdate.actions != null
? ruleUpdate.actions.map(transformRuleToAlertAction)
: migratedActions ?? [],
throttle:
ruleUpdate.throttle !== existingRule.throttle
? transformToAlertThrottle(ruleUpdate.throttle)
: migratedThrottle ?? transformToAlertThrottle(ruleUpdate.throttle),
notifyWhen:
transformToNotifyWhen(ruleUpdate.throttle) !== transformToNotifyWhen(existingRule.throttle)
? transformToNotifyWhen(ruleUpdate.throttle)
: migratedNotifyWhen ?? transformToNotifyWhen(ruleUpdate.throttle),
};

const [validated, errors] = validate(newInternalRule, internalRuleUpdate);
if (errors != null || validated === null) {
throw new UpdateError(`Applying update would create invalid rule: ${errors}`, 400);
Copy link
Contributor

@FrankHassanabad FrankHassanabad Oct 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we have this extra error throw here now? I wouldn't want to add another layer of validation. We are already validating the input arguments and then the response on the way out. We typically just validate on the API boundaries to ensure that the 3rd party services and user input work as we expect.

Within the boundaries we usually trust we are writing code well enough and straight forward enough. If this begins causing errors at this point I would want to fix the user input at the REST API boundary or the response boundary rather than fix issues here or worry about this part.

Otherwise future maintainers might have to maintain multiple spots of validation or change error codes in multiple spots, etc...

Copy link
Contributor Author

@dhurley14 dhurley14 Oct 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually saw this was missing here. This same piece is in the patch rules function

const [validated, errors] = validate(newRule, internalRuleUpdate);
if (errors != null || validated === null) {
throw new PatchError(`Applying patch would create invalid rule: ${errors}`, 400);
}

And I figured it would be good to add it here to keep it consistent.

}

const update = await rulesClient.update({
id: existingRule.id,
data: newInternalRule,
data: validated,
});

await maybeMute({
Expand Down
Loading