Skip to content

Commit

Permalink
[8.7] [Security Solution] Enrich Value List Telemetry (#149621) (#151076
Browse files Browse the repository at this point in the history
)

# Backport

This will backport the following commits from `main` to `8.7`:
- [[Security Solution] Enrich Value List Telemetry
(#149621)](#149621)

<!--- Backport version: 8.9.7 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"JD
Kurma","email":"JDKurma@gmail.com"},"sourceCommit":{"committedDate":"2023-02-13T21:12:47Z","message":"[Security
Solution] Enrich Value List Telemetry (#149621)\n\n## Summary\r\n\r\nAdd
cluster and license information to value list telemetry sent
via\r\nsecurity channel\r\n\r\n### Checklist\r\n\r\nDelete any items
that are not applicable to this PR.\r\n\r\n- [x] ~~Any text added
follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)~~\r\n-
[x]\r\n~~[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials~~\r\n- [x]
[Unit or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [x] ~~Any UI
touched in this PR is usable by keyboard only (learn more\r\nabout
[keyboard\r\naccessibility](https://webaim.org/techniques/keyboard/))~~\r\n-
[x] ~~Any UI touched in this PR does not create any new axe
failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))~~\r\n-
[x] ~~If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)~~\r\n-
[x] ~~This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))~~\r\n-
[x] ~~This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)~~\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [x] ~~This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)~~\r\n\r\n---------\r\n\r\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>","sha":"457e13d962fdab47c8283a4b7e5c6a000ccf0bc6","branchLabelMapping":{"^v8.8.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Feature:Telemetry","release_note:skip","Team:
SecuritySolution","auto-backport","v8.7.0"],"number":149621,"url":"#149621
Solution] Enrich Value List Telemetry (#149621)\n\n## Summary\r\n\r\nAdd
cluster and license information to value list telemetry sent
via\r\nsecurity channel\r\n\r\n### Checklist\r\n\r\nDelete any items
that are not applicable to this PR.\r\n\r\n- [x] ~~Any text added
follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)~~\r\n-
[x]\r\n~~[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials~~\r\n- [x]
[Unit or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [x] ~~Any UI
touched in this PR is usable by keyboard only (learn more\r\nabout
[keyboard\r\naccessibility](https://webaim.org/techniques/keyboard/))~~\r\n-
[x] ~~Any UI touched in this PR does not create any new axe
failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))~~\r\n-
[x] ~~If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)~~\r\n-
[x] ~~This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))~~\r\n-
[x] ~~This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)~~\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [x] ~~This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)~~\r\n\r\n---------\r\n\r\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>","sha":"457e13d962fdab47c8283a4b7e5c6a000ccf0bc6"}},"sourceBranch":"main","suggestedTargetBranches":["8.7"],"targetPullRequestStates":[{"branch":"8.7","label":"v8.7.0","labelRegex":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: JD Kurma <JDKurma@gmail.com>
  • Loading branch information
kibanamachine and JDKurma committed Feb 13, 2023
1 parent 489abdc commit f2ea20f
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { PackagePolicy } from '@kbn/fleet-plugin/common/types/models/packag
import { stubEndpointAlertResponse, stubProcessTree, stubFetchTimelineEvents } from './timeline';
import { stubEndpointMetricsResponse } from './metrics';
import { prebuiltRuleAlertsResponse } from './prebuilt_rule_alerts';
import type { ESClusterInfo, ESLicense } from '../types';

export const createMockTelemetryEventsSender = (
enableTelemetry?: boolean,
Expand All @@ -37,33 +38,31 @@ export const createMockTelemetryEventsSender = (
} as unknown as jest.Mocked<TelemetryEventsSender>;
};

const stubClusterInfo = {
name: 'Stub-MacBook-Pro.local',
export const stubClusterInfo: ESClusterInfo = {
cluster_name: 'elasticsearch',
cluster_uuid: '5Pr5PXRQQpGJUTn0czAvKQ',
version: {
number: '8.0.0-SNAPSHOT',
build_type: 'tar',
build_hash: '38537ab4a726b42ce8f034aad78d8fca4d4f3e51',
build_date: moment().toISOString(),
build_flavor: 'DEFAULT',
build_snapshot: true,
lucene_version: '9.2.0',
minimum_wire_compatibility_version: '7.17.0',
minimum_index_compatibility_version: '7.0.0',
},
tagline: 'You Know, for Search',
};

const stubLicenseInfo = {
export const stubLicenseInfo: ESLicense = {
status: 'active',
uid: '4a7dde08-e5f8-4e50-80f8-bc85b72b4934',
type: 'trial',
issue_date: moment().toISOString(),
issue_date_in_millis: 1653299879146,
expiry_date: moment().toISOString(),
expiry_date_in_millis: 1655891879146,
expirty_date_in_millis: 1655891879146,
max_nodes: 1000,
max_resource_units: null,
issued_to: 'elasticsearch',
issuer: 'elasticsearch',
start_date_in_millis: -1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import moment from 'moment';
import { createMockPackagePolicy } from './__mocks__';
import { createMockPackagePolicy, stubClusterInfo, stubLicenseInfo } from './__mocks__';
import {
LIST_DETECTION_RULE_EXCEPTION,
LIST_ENDPOINT_EXCEPTION,
Expand All @@ -21,7 +21,7 @@ import {
isPackagePolicyList,
templateExceptionList,
addDefaultAdvancedPolicyConfigSettings,
metricsResponseToValueListMetaData,
formatValueListMetaData,
tlog,
setIsElasticCloudDeployment,
createTaskMetric,
Expand Down Expand Up @@ -805,10 +805,11 @@ describe('test advanced policy config overlap ', () => {

describe('test metrics response to value list meta data', () => {
test('can succeed when metrics response is fully populated', async () => {
jest.useFakeTimers().setSystemTime(new Date('2023-01-30'));
const stubMetricResponses = {
listMetricsResponse: {
aggregations: {
total_value_list_count: 5,
total_value_list_count: { value: 5 },
type_breakdown: {
buckets: [
{
Expand Down Expand Up @@ -858,8 +859,12 @@ describe('test metrics response to value list meta data', () => {
},
},
};
const response = metricsResponseToValueListMetaData(stubMetricResponses);
const response = formatValueListMetaData(stubMetricResponses, stubClusterInfo, stubLicenseInfo);
expect(response).toEqual({
'@timestamp': '2023-01-30T00:00:00.000Z',
cluster_uuid: '5Pr5PXRQQpGJUTn0czAvKQ',
cluster_name: 'elasticsearch',
license_id: '4a7dde08-e5f8-4e50-80f8-bc85b72b4934',
total_list_count: 5,
types: [
{
Expand Down Expand Up @@ -901,8 +906,12 @@ describe('test metrics response to value list meta data', () => {
indicatorMatchMetricsResponse: {},
};
// @ts-ignore
const response = metricsResponseToValueListMetaData(stubMetricResponses);
const response = formatValueListMetaData(stubMetricResponses, stubClusterInfo, stubLicenseInfo);
expect(response).toEqual({
'@timestamp': '2023-01-30T00:00:00.000Z',
cluster_uuid: '5Pr5PXRQQpGJUTn0czAvKQ',
cluster_name: 'elasticsearch',
license_id: '4a7dde08-e5f8-4e50-80f8-bc85b72b4934',
total_list_count: 0,
types: [],
lists: [],
Expand Down
54 changes: 28 additions & 26 deletions x-pack/plugins/security_solution/server/lib/telemetry/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ import type {
ESLicense,
ListTemplate,
TelemetryEvent,
ValueListResponseAggregation,
ValueListExceptionListResponseAggregation,
ValueListItemsResponseAggregation,
ValueListIndicatorMatchResponseAggregation,
ValueListResponse,
TaskMetric,
} from './types';
import {
Expand Down Expand Up @@ -241,32 +238,37 @@ export const addDefaultAdvancedPolicyConfigSettings = (policyConfig: PolicyConfi
return merge(DEFAULT_ADVANCED_POLICY_CONFIG_SETTINGS, policyConfig);
};

export const metricsResponseToValueListMetaData = ({
listMetricsResponse,
itemMetricsResponse,
exceptionListMetricsResponse,
indicatorMatchMetricsResponse,
}: {
listMetricsResponse: ValueListResponseAggregation;
itemMetricsResponse: ValueListItemsResponseAggregation;
exceptionListMetricsResponse: ValueListExceptionListResponseAggregation;
indicatorMatchMetricsResponse: ValueListIndicatorMatchResponseAggregation;
}) => ({
total_list_count: listMetricsResponse?.aggregations?.total_value_list_count ?? 0,
export const formatValueListMetaData = (
valueListResponse: ValueListResponse,
clusterInfo: ESClusterInfo,
licenseInfo: ESLicense | undefined
) => ({
'@timestamp': moment().toISOString(),
cluster_uuid: clusterInfo.cluster_uuid,
cluster_name: clusterInfo.cluster_name,
license_id: licenseInfo?.uid,
total_list_count:
valueListResponse.listMetricsResponse?.aggregations?.total_value_list_count?.value ?? 0,
types:
listMetricsResponse?.aggregations?.type_breakdown?.buckets.map((breakdown) => ({
type: breakdown.key,
count: breakdown.doc_count,
})) ?? [],
valueListResponse.listMetricsResponse?.aggregations?.type_breakdown?.buckets.map(
(breakdown) => ({
type: breakdown.key,
count: breakdown.doc_count,
})
) ?? [],
lists:
itemMetricsResponse?.aggregations?.value_list_item_count?.buckets.map((itemCount) => ({
id: itemCount.key,
count: itemCount.doc_count,
})) ?? [],
valueListResponse.itemMetricsResponse?.aggregations?.value_list_item_count?.buckets.map(
(itemCount) => ({
id: itemCount.key,
count: itemCount.doc_count,
})
) ?? [],
included_in_exception_lists_count:
exceptionListMetricsResponse?.aggregations?.vl_included_in_exception_lists_count?.value ?? 0,
valueListResponse.exceptionListMetricsResponse?.aggregations
?.vl_included_in_exception_lists_count?.value ?? 0,
used_in_indicator_match_rule_count:
indicatorMatchMetricsResponse?.aggregations?.vl_used_in_indicator_match_rule_count?.value ?? 0,
valueListResponse.indicatorMatchMetricsResponse?.aggregations
?.vl_used_in_indicator_match_rule_count?.value ?? 0,
});

export let isElasticCloudDeployment = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import {
exceptionListItemToTelemetryEntry,
trustedApplicationToTelemetryEntry,
ruleExceptionListItemToTelemetryEvent,
metricsResponseToValueListMetaData,
tlog,
} from './helpers';
import { Fetcher } from '../../endpoint/routes/resolver/tree/utils/fetch';
Expand All @@ -55,7 +54,7 @@ import type {
GetEndpointListResponse,
RuleSearchResult,
ExceptionListItem,
ValueListMetaData,
ValueListResponse,
ValueListResponseAggregation,
ValueListItemsResponseAggregation,
ValueListExceptionListResponseAggregation,
Expand Down Expand Up @@ -172,7 +171,7 @@ export interface ITelemetryReceiver {
nodeIds: string[]
): Promise<SearchResponse<SafeEndpointEvent, Record<string, AggregationsAggregate>>>;

fetchValueListMetaData(interval: number): Promise<ValueListMetaData>;
fetchValueListMetaData(interval: number): Promise<ValueListResponse>;
}

export class TelemetryReceiver implements ITelemetryReceiver {
Expand Down Expand Up @@ -924,12 +923,12 @@ export class TelemetryReceiver implements ITelemetryReceiver {
exceptionListMetrics as unknown as ValueListExceptionListResponseAggregation;
const indicatorMatchMetricsResponse =
indicatorMatchMetrics as unknown as ValueListIndicatorMatchResponseAggregation;
return metricsResponseToValueListMetaData({
return {
listMetricsResponse,
itemMetricsResponse,
exceptionListMetricsResponse,
indicatorMatchMetricsResponse,
});
};
}

public async fetchClusterInfo(): Promise<ESClusterInfo> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ import {
TASK_METRICS_CHANNEL,
} from '../constants';
import type { ESClusterInfo, ESLicense } from '../types';
import { batchTelemetryRecords, templateExceptionList, tlog, createTaskMetric } from '../helpers';
import {
batchTelemetryRecords,
templateExceptionList,
tlog,
createTaskMetric,
formatValueListMetaData,
} from '../helpers';
import type { ITelemetryEventsSender } from '../sender';
import type { ITelemetryReceiver } from '../receiver';
import type { TaskExecutionPeriod } from '../task';
Expand Down Expand Up @@ -114,9 +120,14 @@ export function createTelemetrySecurityListTaskConfig(maxTelemetryBatch: number)
}

// Value list meta data
const valueListMetaData = await receiver.fetchValueListMetaData(
const valueListResponse = await receiver.fetchValueListMetaData(
FETCH_VALUE_LIST_META_DATA_INTERVAL_IN_HOURS
);
const valueListMetaData = formatValueListMetaData(
valueListResponse,
clusterInfo,
licenseInfo
);
tlog(logger, `Value List Meta Data: ${JSON.stringify(valueListMetaData)}`);
if (valueListMetaData?.total_list_count) {
await sender.sendOnDemand(TELEMETRY_CHANNEL_LISTS, [valueListMetaData]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ export interface ValueListMetaData {

export interface ValueListResponseAggregation {
aggregations: {
total_value_list_count: number;
total_value_list_count: { value: number };
type_breakdown: {
buckets: Array<{
key: string;
Expand Down Expand Up @@ -437,3 +437,10 @@ export interface TelemetryFilterListArtifact {
exception_lists: AllowlistFields;
prebuilt_rules_alerts: AllowlistFields;
}

export interface ValueListResponse {
listMetricsResponse: ValueListResponseAggregation;
itemMetricsResponse: ValueListItemsResponseAggregation;
exceptionListMetricsResponse: ValueListExceptionListResponseAggregation;
indicatorMatchMetricsResponse: ValueListIndicatorMatchResponseAggregation;
}

0 comments on commit f2ea20f

Please sign in to comment.