Skip to content

Commit

Permalink
[8.x] [Security Solution] Add Alert Suppression editable component (#…
Browse files Browse the repository at this point in the history
…198673) (#199809)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[Security Solution] Add Alert Suppression editable component
(#198673)](#198673)

<!--- Backport version: 8.9.8 -->

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

<!--BACKPORT [{"author":{"name":"Maxim
Palenov","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-11-12T14:46:39Z","message":"[Security
Solution] Add Alert Suppression editable component
(#198673)\n\n**Partially addresses:**
https://github.com/elastic/kibana/issues/171520\r\n\r\n##
Summary\r\n\r\nThis PR adds is built on top of
#193828 and
#196948 and adds an Alert
Suppression editable component for Three Way Diff tab's final edit side
of the upgrade prebuilt rule workflow.\r\n\r\n##
Details\r\n\r\nhttps://github.com//issues/171520 required
adding editable components for each field diffable rule field. Alert
Suppression edit component was extracted from Define Rule Step Component
into a separate reusable component. To simplify the logic it was split
into common Alert Suppression and Threshold Alert Suppression since the
latter is a specific use case.\r\n\r\n## Caveats\r\n\r\nUpgrade prebuilt
rules workflow is quite different from rule creation and editing. In
create and edit rule forms users are capable to change any field at
their will. Upgrade prebuilt rules workflow allow to modify only
specific fields having diff in the current rule upgrade.\r\n\r\nThere
are fields which depend on each other. In particular Alert Suppression
isn't supported for EQL sequence though it's addressed in
#189725. \r\n\r\n- Alert
Suppression editable component in Three Way Diff workflow isn't disabled
EQL sequence rule queries. Alert suppression support for rules with EQL
sequence queries is implemented in
#189725. \r\n\r\n- Machine
learning rule type require running selected machine learning jobs
otherwise input could be disabled in case of there are no fields to pick
from otherwise a warning message below the combobox is shown.\r\n\r\n##
How to test\r\n\r\nThe simplest way to test is via patching installed
prebuilt rules via Rule Patch API. Please follow steps below\r\n\r\n-
Enable Prebuilt rule customization feature by adding a
`prebuiltRulesCustomizationEnabled` feature flag\r\n- Run Kibana
locally\r\n- Install a prebuilt rule, e.g. `Potential Code Execution via
Postgresql` with rule_id `2a692072-d78d-42f3-a48a-775677d79c4e`\r\n-
Patch the installed rule by running a query below\r\n\r\n```bash\r\ncurl
-X PATCH --user elastic:changeme -H 'Content-Type: application/json' -H
'kbn-xsrf: 123' -H \"elastic-api-version: 2023-10-31\" -d
'{\"rule_id\":\"2a692072-d78d-42f3-a48a-775677d79c4e\",\"version\":1,\"alert_suppression\":{\"group_by\":[\"host.name\"]}}'
http://localhost:5601/kbn/api/detection_engine/rules\r\n```\r\n\r\n-
Open `Detection Rules (SIEM)` Page -> `Rule Updates` -> click on
`Potential Code Execution via Postgresql` rule -> expand `EQL Query` to
see EQL Query -> press `Edit` button\r\n\r\n## Screenshots\r\n\r\nCustom
query prebuilt rule (UI looks similar for EQL, Indicator Match, New
Terms and ES|QL rule
types)\r\n\r\n![image](https://github.com/user-attachments/assets/86015d5b-e252-4d0b-9aa3-fc14679a493b)\r\n\r\nMachine
learning prebuilt rule with a diff in alert
suppression\r\n\r\n![image](https://github.com/user-attachments/assets/210246cd-27fd-4976-befc-dee023101ec9)\r\n\r\nThreshold
prebuilt
rule\r\n\r\n![image](https://github.com/user-attachments/assets/44b0c1bc-4134-4d58-bd9a-e8e2d4c50802)","sha":"06986e4a86a0fa3c3951fcb6b2ba34ebe2769820","branchLabelMapping":{"^v9.0.0$":"main","^v8.17.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:Detections
and Resp","Team: SecuritySolution","Team:Detection Rule
Management","Feature:Prebuilt Detection
Rules","backport:prev-minor","v8.17.0"],"number":198673,"url":"https://github.com/elastic/kibana/pull/198673","mergeCommit":{"message":"[Security
Solution] Add Alert Suppression editable component
(#198673)\n\n**Partially addresses:**
https://github.com/elastic/kibana/issues/171520\r\n\r\n##
Summary\r\n\r\nThis PR adds is built on top of
#193828 and
#196948 and adds an Alert
Suppression editable component for Three Way Diff tab's final edit side
of the upgrade prebuilt rule workflow.\r\n\r\n##
Details\r\n\r\nhttps://github.com//issues/171520 required
adding editable components for each field diffable rule field. Alert
Suppression edit component was extracted from Define Rule Step Component
into a separate reusable component. To simplify the logic it was split
into common Alert Suppression and Threshold Alert Suppression since the
latter is a specific use case.\r\n\r\n## Caveats\r\n\r\nUpgrade prebuilt
rules workflow is quite different from rule creation and editing. In
create and edit rule forms users are capable to change any field at
their will. Upgrade prebuilt rules workflow allow to modify only
specific fields having diff in the current rule upgrade.\r\n\r\nThere
are fields which depend on each other. In particular Alert Suppression
isn't supported for EQL sequence though it's addressed in
#189725. \r\n\r\n- Alert
Suppression editable component in Three Way Diff workflow isn't disabled
EQL sequence rule queries. Alert suppression support for rules with EQL
sequence queries is implemented in
#189725. \r\n\r\n- Machine
learning rule type require running selected machine learning jobs
otherwise input could be disabled in case of there are no fields to pick
from otherwise a warning message below the combobox is shown.\r\n\r\n##
How to test\r\n\r\nThe simplest way to test is via patching installed
prebuilt rules via Rule Patch API. Please follow steps below\r\n\r\n-
Enable Prebuilt rule customization feature by adding a
`prebuiltRulesCustomizationEnabled` feature flag\r\n- Run Kibana
locally\r\n- Install a prebuilt rule, e.g. `Potential Code Execution via
Postgresql` with rule_id `2a692072-d78d-42f3-a48a-775677d79c4e`\r\n-
Patch the installed rule by running a query below\r\n\r\n```bash\r\ncurl
-X PATCH --user elastic:changeme -H 'Content-Type: application/json' -H
'kbn-xsrf: 123' -H \"elastic-api-version: 2023-10-31\" -d
'{\"rule_id\":\"2a692072-d78d-42f3-a48a-775677d79c4e\",\"version\":1,\"alert_suppression\":{\"group_by\":[\"host.name\"]}}'
http://localhost:5601/kbn/api/detection_engine/rules\r\n```\r\n\r\n-
Open `Detection Rules (SIEM)` Page -> `Rule Updates` -> click on
`Potential Code Execution via Postgresql` rule -> expand `EQL Query` to
see EQL Query -> press `Edit` button\r\n\r\n## Screenshots\r\n\r\nCustom
query prebuilt rule (UI looks similar for EQL, Indicator Match, New
Terms and ES|QL rule
types)\r\n\r\n![image](https://github.com/user-attachments/assets/86015d5b-e252-4d0b-9aa3-fc14679a493b)\r\n\r\nMachine
learning prebuilt rule with a diff in alert
suppression\r\n\r\n![image](https://github.com/user-attachments/assets/210246cd-27fd-4976-befc-dee023101ec9)\r\n\r\nThreshold
prebuilt
rule\r\n\r\n![image](https://github.com/user-attachments/assets/44b0c1bc-4134-4d58-bd9a-e8e2d4c50802)","sha":"06986e4a86a0fa3c3951fcb6b2ba34ebe2769820"}},"sourceBranch":"main","suggestedTargetBranches":["8.x"],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","labelRegex":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/198673","number":198673,"mergeCommit":{"message":"[Security
Solution] Add Alert Suppression editable component
(#198673)\n\n**Partially addresses:**
https://github.com/elastic/kibana/issues/171520\r\n\r\n##
Summary\r\n\r\nThis PR adds is built on top of
#193828 and
#196948 and adds an Alert
Suppression editable component for Three Way Diff tab's final edit side
of the upgrade prebuilt rule workflow.\r\n\r\n##
Details\r\n\r\nhttps://github.com//issues/171520 required
adding editable components for each field diffable rule field. Alert
Suppression edit component was extracted from Define Rule Step Component
into a separate reusable component. To simplify the logic it was split
into common Alert Suppression and Threshold Alert Suppression since the
latter is a specific use case.\r\n\r\n## Caveats\r\n\r\nUpgrade prebuilt
rules workflow is quite different from rule creation and editing. In
create and edit rule forms users are capable to change any field at
their will. Upgrade prebuilt rules workflow allow to modify only
specific fields having diff in the current rule upgrade.\r\n\r\nThere
are fields which depend on each other. In particular Alert Suppression
isn't supported for EQL sequence though it's addressed in
#189725. \r\n\r\n- Alert
Suppression editable component in Three Way Diff workflow isn't disabled
EQL sequence rule queries. Alert suppression support for rules with EQL
sequence queries is implemented in
#189725. \r\n\r\n- Machine
learning rule type require running selected machine learning jobs
otherwise input could be disabled in case of there are no fields to pick
from otherwise a warning message below the combobox is shown.\r\n\r\n##
How to test\r\n\r\nThe simplest way to test is via patching installed
prebuilt rules via Rule Patch API. Please follow steps below\r\n\r\n-
Enable Prebuilt rule customization feature by adding a
`prebuiltRulesCustomizationEnabled` feature flag\r\n- Run Kibana
locally\r\n- Install a prebuilt rule, e.g. `Potential Code Execution via
Postgresql` with rule_id `2a692072-d78d-42f3-a48a-775677d79c4e`\r\n-
Patch the installed rule by running a query below\r\n\r\n```bash\r\ncurl
-X PATCH --user elastic:changeme -H 'Content-Type: application/json' -H
'kbn-xsrf: 123' -H \"elastic-api-version: 2023-10-31\" -d
'{\"rule_id\":\"2a692072-d78d-42f3-a48a-775677d79c4e\",\"version\":1,\"alert_suppression\":{\"group_by\":[\"host.name\"]}}'
http://localhost:5601/kbn/api/detection_engine/rules\r\n```\r\n\r\n-
Open `Detection Rules (SIEM)` Page -> `Rule Updates` -> click on
`Potential Code Execution via Postgresql` rule -> expand `EQL Query` to
see EQL Query -> press `Edit` button\r\n\r\n## Screenshots\r\n\r\nCustom
query prebuilt rule (UI looks similar for EQL, Indicator Match, New
Terms and ES|QL rule
types)\r\n\r\n![image](https://github.com/user-attachments/assets/86015d5b-e252-4d0b-9aa3-fc14679a493b)\r\n\r\nMachine
learning prebuilt rule with a diff in alert
suppression\r\n\r\n![image](https://github.com/user-attachments/assets/210246cd-27fd-4976-befc-dee023101ec9)\r\n\r\nThreshold
prebuilt
rule\r\n\r\n![image](https://github.com/user-attachments/assets/44b0c1bc-4134-4d58-bd9a-e8e2d4c50802)","sha":"06986e4a86a0fa3c3951fcb6b2ba34ebe2769820"}},{"branch":"8.x","label":"v8.17.0","labelRegex":"^v8.17.0$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->
  • Loading branch information
maximpn authored Nov 12, 2024
1 parent cee0d98 commit 02a90c1
Show file tree
Hide file tree
Showing 95 changed files with 1,934 additions and 872 deletions.
13 changes: 8 additions & 5 deletions oas_docs/output/kibana.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33105,17 +33105,20 @@ components:
type: object
properties:
unit:
enum:
- s
- m
- h
type: string
$ref: >-
#/components/schemas/Security_Detections_API_AlertSuppressionDurationUnit
value:
minimum: 1
type: integer
required:
- value
- unit
Security_Detections_API_AlertSuppressionDurationUnit:
enum:
- s
- m
- h
type: string
Security_Detections_API_AlertSuppressionGroupBy:
items:
type: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,10 +555,15 @@ export const RuleExceptionList = z.object({
namespace_type: z.enum(['agnostic', 'single']),
});

export type AlertSuppressionDurationUnit = z.infer<typeof AlertSuppressionDurationUnit>;
export const AlertSuppressionDurationUnit = z.enum(['s', 'm', 'h']);
export type AlertSuppressionDurationUnitEnum = typeof AlertSuppressionDurationUnit.enum;
export const AlertSuppressionDurationUnitEnum = AlertSuppressionDurationUnit.enum;

export type AlertSuppressionDuration = z.infer<typeof AlertSuppressionDuration>;
export const AlertSuppressionDuration = z.object({
value: z.number().int().min(1),
unit: z.enum(['s', 'm', 'h']),
unit: AlertSuppressionDurationUnit,
});

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -581,18 +581,21 @@ components:
- type
- namespace_type

AlertSuppressionDurationUnit:
type: string
enum:
- s
- m
- h

AlertSuppressionDuration:
type: object
properties:
value:
type: integer
minimum: 1
unit:
type: string
enum:
- s
- m
- h
$ref: '#/components/schemas/AlertSuppressionDurationUnit'
required:
- value
- unit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1560,17 +1560,19 @@ components:
type: object
properties:
unit:
enum:
- s
- m
- h
type: string
$ref: '#/components/schemas/AlertSuppressionDurationUnit'
value:
minimum: 1
type: integer
required:
- value
- unit
AlertSuppressionDurationUnit:
enum:
- s
- m
- h
type: string
AlertSuppressionGroupBy:
items:
type: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -850,17 +850,19 @@ components:
type: object
properties:
unit:
enum:
- s
- m
- h
type: string
$ref: '#/components/schemas/AlertSuppressionDurationUnit'
value:
minimum: 1
type: integer
required:
- value
- unit
AlertSuppressionDurationUnit:
enum:
- s
- m
- h
type: string
AlertSuppressionGroupBy:
items:
type: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export const uiPlugins = ({
insightsUpsellingMessage,
interactionsUpsellingMessage,
}: {
insightsUpsellingMessage: string | null;
interactionsUpsellingMessage: string | null;
insightsUpsellingMessage?: string;
interactionsUpsellingMessage?: string;
}) => {
const currentPlugins = nonStatefulUiPlugins.map((plugin) => plugin.name);
const insightPluginWithLicense = insightMarkdownPlugin.plugin({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ describe('plugin', () => {
});

it('show investigate message when insightsUpsellingMessage is not provided', () => {
const result = plugin({ insightsUpsellingMessage: null });
const result = plugin({ insightsUpsellingMessage: undefined });

expect(result.button.label).toEqual('Investigate');
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -541,11 +541,7 @@ const exampleInsight = `${insightPrefix}{
]
}}`;

export const plugin = ({
insightsUpsellingMessage,
}: {
insightsUpsellingMessage: string | null;
}) => {
export const plugin = ({ insightsUpsellingMessage }: { insightsUpsellingMessage?: string }) => {
return {
name: 'insights',
button: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const OsqueryEditor = React.memo(OsqueryEditorComponent);
export const plugin = ({
interactionsUpsellingMessage,
}: {
interactionsUpsellingMessage: string | null;
interactionsUpsellingMessage?: string;
}) => {
return {
name: 'osquery',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const TimelineEditor = memo(TimelineEditorComponent);
export const plugin = ({
interactionsUpsellingMessage,
}: {
interactionsUpsellingMessage: string | null;
interactionsUpsellingMessage?: string;
}): EuiMarkdownEditorUiPlugin => {
return {
name: ID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe('use_upselling', () => {
expect(result.all.length).toBe(1); // assert that it should not cause unnecessary re-renders
});

test('useUpsellingMessage returns null when upsellingMessageId not found', () => {
test('useUpsellingMessage returns undefined when upsellingMessageId not found', () => {
const emptyMessages = {};
mockUpselling.setPages(emptyMessages);

Expand All @@ -81,6 +81,6 @@ describe('use_upselling', () => {
wrapper: RenderWrapper,
}
);
expect(result.current).toBe(null);
expect(result.current).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ export const useUpsellingComponent = (id: UpsellingSectionId): React.ComponentTy
return useMemo(() => upsellingSections?.get(id) ?? null, [id, upsellingSections]);
};

export const useUpsellingMessage = (id: UpsellingMessageId): string | null => {
export const useUpsellingMessage = (id: UpsellingMessageId): string | undefined => {
const upselling = useUpsellingService();
const upsellingMessages = useObservable(upselling.messages$, upselling.getMessagesValue());

return useMemo(() => upsellingMessages?.get(id) ?? null, [id, upsellingMessages]);
return useMemo(() => upsellingMessages?.get(id), [id, upsellingMessages]);
};

export const useUpsellingPage = (pageName: SecurityPageName): React.ComponentType | null => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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 { act, fireEvent, waitFor } from '@testing-library/react';

export function showEuiComboBoxOptions(comboBoxToggleButton: HTMLElement): Promise<void> {
fireEvent.click(comboBoxToggleButton);

return waitFor(() => {
const listWithOptionsElement = document.querySelector('[role="listbox"]');
const emptyListElement = document.querySelector('.euiComboBoxOptionsList__empty');

expect(listWithOptionsElement || emptyListElement).toBeInTheDocument();
});
}

type SelectEuiComboBoxOptionParameters =
| {
comboBoxToggleButton: HTMLElement;
optionIndex: number;
optionText?: undefined;
}
| {
comboBoxToggleButton: HTMLElement;
optionText: string;
optionIndex?: undefined;
};

export function selectEuiComboBoxOption({
comboBoxToggleButton,
optionIndex,
optionText,
}: SelectEuiComboBoxOptionParameters): Promise<void> {
return act(async () => {
await showEuiComboBoxOptions(comboBoxToggleButton);

const options = Array.from(
document.querySelectorAll('[data-test-subj*="comboBoxOptionsList"] [role="option"]')
);

if (typeof optionText === 'string') {
const optionToSelect = options.find((option) => option.textContent === optionText);

if (optionToSelect) {
fireEvent.click(optionToSelect);
} else {
throw new Error(
`Could not find option with text "${optionText}". Available options: ${options
.map((option) => option.textContent)
.join(', ')}`
);
}
} else {
fireEvent.click(options[optionIndex]);
}
});
}

export function selectFirstEuiComboBoxOption({
comboBoxToggleButton,
}: {
comboBoxToggleButton: HTMLElement;
}): Promise<void> {
return selectEuiComboBoxOption({ comboBoxToggleButton, optionIndex: 0 });
}

export function clearEuiComboBoxSelection({
clearButton,
}: {
clearButton: HTMLElement;
}): Promise<void> {
return act(async () => {
fireEvent.click(clearButton);
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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 React, { memo } from 'react';
import { EuiPanel, EuiText, EuiToolTip } from '@elastic/eui';
import type { DataViewFieldBase } from '@kbn/es-query';
import { useFormData } from '../../../../../shared_imports';
import { MissingFieldsStrategySelector } from './missing_fields_strategy_selector';
import { SuppressionDurationSelector } from './suppression_duration_selector';
import { SuppressionFieldsSelector } from './suppression_fields_selector';
import { ALERT_SUPPRESSION_FIELDS_FIELD_NAME } from '../constants/fields';

interface AlertSuppressionEditProps {
suppressibleFields: DataViewFieldBase[];
labelAppend?: React.ReactNode;
disabled?: boolean;
disabledText?: string;
warningText?: string;
}

export const AlertSuppressionEdit = memo(function AlertSuppressionEdit({
suppressibleFields,
labelAppend,
disabled,
disabledText,
warningText,
}: AlertSuppressionEditProps): JSX.Element {
const [{ [ALERT_SUPPRESSION_FIELDS_FIELD_NAME]: suppressionFields }] = useFormData<{
[ALERT_SUPPRESSION_FIELDS_FIELD_NAME]: string[];
}>({
watch: ALERT_SUPPRESSION_FIELDS_FIELD_NAME,
});
const hasSelectedFields = suppressionFields?.length > 0;
const content = (
<>
<SuppressionFieldsSelector
suppressibleFields={suppressibleFields}
labelAppend={labelAppend}
disabled={disabled}
/>
{warningText && (
<EuiText size="xs" color="warning" data-test-subj="alertSuppressionWarning">
{warningText}
</EuiText>
)}
<EuiPanel paddingSize="m" hasShadow={false}>
<SuppressionDurationSelector disabled={disabled || !hasSelectedFields} />
<MissingFieldsStrategySelector disabled={disabled || !hasSelectedFields} />
</EuiPanel>
</>
);

return disabled && disabledText ? (
<EuiToolTip position="right" content={disabledText}>
{content}
</EuiToolTip>
) : (
content
);
});
Loading

0 comments on commit 02a90c1

Please sign in to comment.