Skip to content

Commit

Permalink
[Security Solutions] Adds back the legacy actions and notification sy…
Browse files Browse the repository at this point in the history
…stem in a limited fashion (#112869)

## Summary

Fixes https://github.com/elastic/security-team/issues/1759

Related earlier PR, #109722, where these were removed to where they could no longer function. This PR adds them back to where they will function for existing users. The end goal is to have users naturally migrate as they update, enable/disable, or create new rules. 

What this PR does:
* Adds back the legacy side car actions `siem-detection-engine-rule-actions`
* Adds back the legacy hidden alert of `siem.notifications`
* Adds back unit tests where they existed. Both of these systems did not have existing e2e tests.
* Re-adds the find feature and functionality which should show the rules with legacy and non-legacy notifications/side car actions during a REST find operation.
* Updates the logic for when to show a legacy vs. non-legacy notification/side car action.
* Adds a new route called `/internal/api/detection/legacy/notifications` which is only for developer and tests for us to maintain this system for the foreseeable future.
* Adds script to exercise creating old notifications `detection_engine/scripts/post_legacy_notification.sh`
* Adds a data file for the script to use as an example for ad-hoc testing, `scripts/legacy_notifications/one_action.json`
* Adds within `security_solution/server/types.ts` `ActionsApiRequestHandlerContext` so that if we need to directly access actions within plugins we can. I do not use it here, but it should have been existing there and is good to have it in case we need it at this point within REST routes.
* When adding back the files and changes, I use the kibana-core approach of prefixing files, functions, types, etc... with the words `legacyFoo`. The files are named `legacy_foo.ts`. Everything has `@deprecation` above them as well. The intent here is all of this should hopefully make it unambiguously clear which parts of the notification system are for the new system/existing API and which ones are only for the deprecated legacy system. There exists some parts of the system that are used within _both_ and the hope is that we can keep the legacy pieces separate from the non-legacy pieces for strangling the legacy pieces.   
* This adds a new linter rule to prevent users from easily importing files named `legacy_foo.ts` or `foo_legacy.ts` we are using here and can also use for other similar legacy parts of the system we have.  This seems to be the established pattern that kibana-core does as well looking through the linters and code base.
* Removes some dead import/export code and types instead of maintaining them since they are no longer used.

What this PR does not do (but are planned on follow ups):
* This PR does not add migration logic in most conditions such as a user enabling/disabling a rule, editing a rule unless the user is explicitly changing the actions by turning off the notification and then re-adding the notification.
* This PR does not log any information indicating to the user that they are running legacy rules or indicates they have that.
* This PR does not allow the executors or any UI/UX, backend to re-add a legacy notification. Instead only the hidden REST route of `/internal/api/detection/legacy/notifications` allows us to do this for testing purposes.
* This PR does not migrate the data structure of actions legacy notification system `siem-detection-engine-rule-actions` to use saved object references.
* If you delete an alert this will not delete the side car if it detects one is present on it.
* If you update an alert notification with a new notification this will not remove the side car on the update.

**Ad-hoc testing instructions**
How to do ad-hoc testing for various situations such as having a legacy notification system such as a user's or if you want to mimic a malfunction and result of a "split-brain" to where you have both notification systems running at the same time due to a bug or regression:

Create a rule and activate it normally within security_solution:
<img width="1046" alt="Screen Shot 2021-09-22 at 2 09 14 PM" src="https://user-images.githubusercontent.com/1151048/134416564-e4e001a7-1086-46a1-aa8d-79880f70cc35.png">

Do not add actions to the rule at this point as we will first exercise the older legacy system. However, you want at least one action configured such as a slack notification:
<img width="575" alt="Screen Shot 2021-09-22 at 2 28 16 PM" src="https://user-images.githubusercontent.com/1151048/134417012-58e63709-5447-4832-8866-f82be1b9596b.png">

Within dev tools do a query for all your actions and grab one of the `_id` of them without their prefix:
```json
# See all your actions
GET .kibana/_search
{
  "query": {
    "term": {
      "type": "action"
    }
  }
}
```

Mine was `"_id" : "action:879e8ff0-1be1-11ec-a722-83da1c22a481",` so I will be copying the ID of `879e8ff0-1be1-11ec-a722-83da1c22a481`

Go to the file `detection_engine/scripts/legacy_notifications/one_action.json` and add this id to the file. Something like this:
```json
{
  "name": "Legacy notification with one action",
  "interval": "1m",  <--- You can use whatever you want. Real values are "1h", "1d", "1w". I use "1m" for testing purposes.
  "actions": [
    {
      "id": "879e8ff0-1be1-11ec-a722-83da1c22a481", <--- My action id
      "group": "default",
      "params": {
        "message": "Hourly\nRule {{context.rule.name}} generated {{state.signals_count}} alerts"
      },
      "actionTypeId": ".slack" <--- I am a slack action id type.
    }
  ]
}
```

Query for an alert you want to add manually add back a legacy notification to it. Such as:
```json
# See all your siem.signals alert types and choose one
GET .kibana/_search
{
  "query": {
    "term": {
      "alert.alertTypeId": "siem.signals"
    }
  }
}
```

Grab the `_id` without the `alert` prefix. For mine this was `933ca720-1be1-11ec-a722-83da1c22a481`

Within the directory of `detection_engine/scripts` execute the script
```bash
./post_legacy_notification.sh 933ca720-1be1-11ec-a722-83da1c22a481
{
  "ok": "acknowledged"
}
```

which is going to do a few things. See the file `detection_engine/routes/rules/legacy_create_legacy_notification.ts` for the definition of the route and what it does in full, but we should notice that we have now:

Created a legacy side car action object of type `siem-detection-engine-rule-actions` you can see in dev tools:
```json
# See the actions "side car" which are part of the legacy notification system.
GET .kibana/_search
{
  "query": {
    "term": {
      "type": {
        "value": "siem-detection-engine-rule-actions"
      }
    }
  }
}
```

Note in the response:
```json
          "siem-detection-engine-rule-actions" : {
            "ruleAlertId" : "933ca720-1be1-11ec-a722-83da1c22a481", <--- NOTE, not migrated to references yet
            "actions" : [
              {
                "action_type_id" : ".slack",
                "id" : "879e8ff0-1be1-11ec-a722-83da1c22a481", <--- NOTE, not migrated to references yet
                "params" : {
                  "message" : "Hourly\nRule {{context.rule.name}} generated {{state.signals_count}} alerts"
                },
                "group" : "default"
              }
            ],
            "ruleThrottle" : "1m", <--- Should be the same as the interval in "one_action.json" config
            "alertThrottle" : "1m" <--- Should be the same as the interval in "one_action.json" config
          },
          "type" : "siem-detection-engine-rule-actions",
          "references" : [ ],
```

Created a `siem.notification` rule instance which you can see in dev tools as well:
```json
# Get the alert type of "siem-notifications" which is part of the legacy system.
GET .kibana/_search
{
  "query": {
    "term": {
      "alert.alertTypeId": "siem.notifications"
    }
  }
}
```

Take note from the `siem.notifications` these values which determine how/when it fires and if your actions are set up correctly:
```json
            "name" : "Legacy notification with one action" <--- Our name from one_action.json 
            "schedule" : {
              "interval" : "1m" <--- Interval should match interval in one_action.json
            },
            "enabled" : true, <--- We should be enabled
            "actions" : [
              {
                "group" : "default",
                "params" : {
                  "message" : "Hourly\nRule {{context.rule.name}} generated {{state.signals_count}} alerts"
                },
                "actionTypeId" : ".slack", <--- Our actionID
                "actionRef" : "action_0"
              }
            ],
```


And that now there exists a task within task manager that will be executing this:
```json
# Get the tasks of siem notifications to ensure and see it is running
GET .task-manager/_search
{
  "query": {
    "term": {
      "task.taskType": "alerting:siem.notifications"
    }
  }
}
```

You can double check the interval from the result of the query to ensure it runs as the configuration test file shows it should be:
```json
            "schedule" : {
              "interval" : "1m"
            },
```

Within time you should see your action execute like the legacy notification system:
<img width="876" alt="Screen Shot 2021-09-22 at 2 55 28 PM" src="https://user-images.githubusercontent.com/1151048/134422639-80523abb-f43c-4f7c-abef-a60062bef139.png">

If you go to edit the rule you should notice that the rule now has the side car attached to it within the UI:
<img width="1050" alt="Screen Shot 2021-09-22 at 8 08 54 PM" src="https://user-images.githubusercontent.com/1151048/134445265-fa0a330b-3238-48e2-aef3-6042c7e9aa69.png">

You can also look at your log messages in debug mode to verify the behaviors of the legacy system and the normal rules running.

Compare these data structures to a 7.14.x system in cloud to ensure the data looks the same and the ad-hoc testing functions as expected.

Check the scripts of `./find_rules.sh`, `./read_rules.sh` to ensure that the find REST route returns the legacy actions when they are there.

### Checklist


- [x] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios
  • Loading branch information
FrankHassanabad authored Sep 27, 2021
1 parent 90792cf commit de43a3b
Show file tree
Hide file tree
Showing 41 changed files with 2,025 additions and 528 deletions.
27 changes: 27 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,15 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/unified-signatures': 'error',
'no-restricted-imports': [
'error',
{
// prevents code from importing files that contain the name "legacy" within their name. This is a mechanism
// to help deprecation and prevent accidental re-use/continued use of code we plan on removing. If you are
// finding yourself turning this off a lot for "new code" consider renaming the file and functions if it is has valid uses.
patterns: ['*legacy*'],
},
],
},
},
{
Expand Down Expand Up @@ -1192,6 +1201,15 @@ module.exports = {
'no-template-curly-in-string': 'error',
'sort-keys': 'error',
'prefer-destructuring': 'error',
'no-restricted-imports': [
'error',
{
// prevents code from importing files that contain the name "legacy" within their name. This is a mechanism
// to help deprecation and prevent accidental re-use/continued use of code we plan on removing. If you are
// finding yourself turning this off a lot for "new code" consider renaming the file and functions if it has valid uses.
patterns: ['*legacy*'],
},
],
},
},
/**
Expand Down Expand Up @@ -1304,6 +1322,15 @@ module.exports = {
'no-template-curly-in-string': 'error',
'sort-keys': 'error',
'prefer-destructuring': 'error',
'no-restricted-imports': [
'error',
{
// prevents code from importing files that contain the name "legacy" within their name. This is a mechanism
// to help deprecation and prevent accidental re-use/continued use of code we plan on removing. If you are
// finding yourself turning this off a lot for "new code" consider renaming the file and functions if it has valid uses.
patterns: ['*legacy*'],
},
],
},
},
/**
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/security_solution/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,9 @@ export const THRESHOLD_RULE_TYPE_ID = `${RULE_TYPE_PREFIX}.thresholdRule` as con

/**
* Id for the notifications alerting type
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
export const NOTIFICATIONS_ID = `siem.notifications`;
export const LEGACY_NOTIFICATIONS_ID = `siem.notifications`;

/**
* Special internal structure for tags for signals. This is used
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* 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.
*/

// eslint-disable-next-line no-restricted-imports
import { legacyAddTags } from './legacy_add_tags';
import { INTERNAL_RULE_ALERT_ID_KEY } from '../../../../common/constants';

describe('legacyAdd_tags', () => {
test('it should add a rule id as an internal structure', () => {
const tags = legacyAddTags([], 'rule-1');
expect(tags).toEqual([`${INTERNAL_RULE_ALERT_ID_KEY}:rule-1`]);
});

test('it should not allow duplicate tags to be created', () => {
const tags = legacyAddTags(['tag-1', 'tag-1'], 'rule-1');
expect(tags).toEqual(['tag-1', `${INTERNAL_RULE_ALERT_ID_KEY}:rule-1`]);
});

test('it should not allow duplicate internal tags to be created when called two times in a row', () => {
const tags1 = legacyAddTags(['tag-1'], 'rule-1');
const tags2 = legacyAddTags(tags1, 'rule-1');
expect(tags2).toEqual(['tag-1', `${INTERNAL_RULE_ALERT_ID_KEY}:rule-1`]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* 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 { INTERNAL_RULE_ALERT_ID_KEY } from '../../../../common/constants';

/**
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
export const legacyAddTags = (tags: string[], ruleAlertId: string): string[] =>
Array.from(new Set([...tags, `${INTERNAL_RULE_ALERT_ID_KEY}:${ruleAlertId}`]));
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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 { rulesClientMock } from '../../../../../alerting/server/mocks';
// eslint-disable-next-line no-restricted-imports
import { legacyCreateNotifications } from './legacy_create_notifications';

/**
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
describe('legacyCreateNotifications', () => {
let rulesClient: ReturnType<typeof rulesClientMock.create>;

beforeEach(() => {
rulesClient = rulesClientMock.create();
});

it('calls the rulesClient with proper params', async () => {
const ruleAlertId = 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd';

await legacyCreateNotifications({
rulesClient,
actions: [],
ruleAlertId,
enabled: true,
interval: '',
name: '',
});

expect(rulesClient.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
params: expect.objectContaining({
ruleAlertId,
}),
}),
})
);
});

it('calls the rulesClient with transformed actions', async () => {
const action = {
group: 'default',
id: '99403909-ca9b-49ba-9d7a-7e5320e68d05',
params: { message: 'Rule generated {{state.signals_count}} signals' },
actionTypeId: '.slack',
};
await legacyCreateNotifications({
rulesClient,
actions: [action],
ruleAlertId: 'new-rule-id',
enabled: true,
interval: '',
name: '',
});

expect(rulesClient.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
actions: expect.arrayContaining([
{
group: action.group,
id: action.id,
params: action.params,
actionTypeId: '.slack',
},
]),
}),
})
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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 { SanitizedAlert } from '../../../../../alerting/common';
import { SERVER_APP_ID, LEGACY_NOTIFICATIONS_ID } from '../../../../common/constants';
// eslint-disable-next-line no-restricted-imports
import { CreateNotificationParams, LegacyRuleNotificationAlertTypeParams } from './legacy_types';
// eslint-disable-next-line no-restricted-imports
import { legacyAddTags } from './legacy_add_tags';

/**
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
export const legacyCreateNotifications = async ({
rulesClient,
actions,
enabled,
ruleAlertId,
interval,
name,
}: CreateNotificationParams): Promise<SanitizedAlert<LegacyRuleNotificationAlertTypeParams>> =>
rulesClient.create<LegacyRuleNotificationAlertTypeParams>({
data: {
name,
tags: legacyAddTags([], ruleAlertId),
alertTypeId: LEGACY_NOTIFICATIONS_ID,
consumer: SERVER_APP_ID,
params: {
ruleAlertId,
},
schedule: { interval },
enabled,
actions,
throttle: null,
notifyWhen: null,
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* 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.
*/

// eslint-disable-next-line no-restricted-imports
import { legacyGetFilter } from './legacy_find_notifications';
import { LEGACY_NOTIFICATIONS_ID } from '../../../../common/constants';

describe('legacyFind_notifications', () => {
test('it returns a full filter with an AND if sent down', () => {
expect(legacyGetFilter('alert.attributes.enabled: true')).toEqual(
`alert.attributes.alertTypeId: ${LEGACY_NOTIFICATIONS_ID} AND alert.attributes.enabled: true`
);
});

test('it returns existing filter with no AND when not set', () => {
expect(legacyGetFilter(null)).toEqual(
`alert.attributes.alertTypeId: ${LEGACY_NOTIFICATIONS_ID}`
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* 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 { AlertTypeParams, FindResult } from '../../../../../alerting/server';
import { LEGACY_NOTIFICATIONS_ID } from '../../../../common/constants';
// eslint-disable-next-line no-restricted-imports
import { LegacyFindNotificationParams } from './legacy_types';

/**
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
export const legacyGetFilter = (filter: string | null | undefined) => {
if (filter == null) {
return `alert.attributes.alertTypeId: ${LEGACY_NOTIFICATIONS_ID}`;
} else {
return `alert.attributes.alertTypeId: ${LEGACY_NOTIFICATIONS_ID} AND ${filter}`;
}
};

/**
* @deprecated Once we are confident all rules relying on side-car actions SO's have been migrated to SO references we should remove this function
*/
export const legacyFindNotifications = async ({
rulesClient,
perPage,
page,
fields,
filter,
sortField,
sortOrder,
}: LegacyFindNotificationParams): Promise<FindResult<AlertTypeParams>> =>
rulesClient.find({
options: {
fields,
page,
perPage,
filter: legacyGetFilter(filter),
sortOrder,
sortField,
},
});
Loading

0 comments on commit de43a3b

Please sign in to comment.