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] Allow users to edit max_signals field for custom rules #179680

Merged
merged 62 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
15db4e4
exposes alerting config setting and creates form compoenent
dplumlee Mar 29, 2024
af60e77
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 2, 2024
bb5a1d2
changes user-facing language to max alerts
dplumlee Apr 2, 2024
8015b84
adds tests
dplumlee Apr 2, 2024
264cdb6
updates language
dplumlee Apr 2, 2024
69dc936
adds param to one million mock constructors
dplumlee Apr 2, 2024
ca8b462
updates types
dplumlee Apr 2, 2024
d396a12
updates tests and mocks
dplumlee Apr 3, 2024
07927d1
adds type
dplumlee Apr 3, 2024
3522cb7
updates tests
dplumlee Apr 3, 2024
1a1c121
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 9, 2024
0319c94
changes logic for max validations
dplumlee Apr 9, 2024
1749631
updates tests
dplumlee Apr 9, 2024
19ebcf0
adds warning state
dplumlee Apr 10, 2024
813c807
reset config value
dplumlee Apr 10, 2024
00e942a
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 11, 2024
cd4eb47
adds max_signals rule execution logic
dplumlee Apr 12, 2024
5ad1b65
updates tests and types
dplumlee Apr 12, 2024
ff4b232
adds cypress tests
dplumlee Apr 12, 2024
2053068
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 15, 2024
bec6bf7
updates test attributes
dplumlee Apr 15, 2024
aadde40
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 15, 2024
34588b2
updates warning design
dplumlee Apr 16, 2024
61fbdc1
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 16, 2024
7aaa62a
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 16, 2024
3e749f6
updates language
dplumlee Apr 16, 2024
bd01d55
updates attribute
dplumlee Apr 16, 2024
aa2c565
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 17, 2024
975490e
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 22, 2024
25c05e3
addresses comments
dplumlee Apr 22, 2024
b47deff
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 22, 2024
e709722
fixes execution logic
dplumlee Apr 22, 2024
9886913
strips out no longer needed rulesClient param
dplumlee Apr 22, 2024
89bd1e7
adds defaultable import export tests
dplumlee Apr 23, 2024
304db6f
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 24, 2024
db88782
addresses comments
dplumlee Apr 24, 2024
dd0a87e
updates tests
dplumlee Apr 24, 2024
bedbd7d
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 25, 2024
f400f99
changes defaulting logic one last time
dplumlee Apr 25, 2024
8add109
updates integration tests to match unified method
dplumlee Apr 25, 2024
e4e8af5
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 26, 2024
54b8041
fixes spelling mistakes
dplumlee Apr 26, 2024
ad64d19
addresses response ops changes
dplumlee Apr 26, 2024
1cb02a2
fixes test
dplumlee Apr 27, 2024
259d52e
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 29, 2024
bcca901
addresses comments
dplumlee Apr 30, 2024
346e10e
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee Apr 30, 2024
ce2f06e
adds test
dplumlee Apr 30, 2024
940f925
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 1, 2024
92d3ed2
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 1, 2024
b1ce138
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
995462b
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
69f4b87
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
dad1f8d
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
9244392
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
8d02476
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
d0e0432
Merge remote-tracking branch 'upstream/main' into max-signals-field-f…
dplumlee May 2, 2024
18a724f
Merge branch 'main' into max-signals-field-form-component
jpdjere May 3, 2024
0b71b77
Fix handling of 0 in form
jpdjere May 3, 2024
07d81e6
Added tests for form validation
jpdjere May 3, 2024
c850892
Remove empty line
jpdjere May 3, 2024
3cbb10f
Merge branch 'main' into max-signals-field-form-component
jpdjere May 3, 2024
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
21 changes: 20 additions & 1 deletion x-pack/plugins/alerting/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export interface PluginSetupContract {
}
export interface PluginStartContract {
getNavigation: (ruleId: Rule['id']) => Promise<string | undefined>;
getMaxAlertsPerRun: () => number | undefined;
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
}
export interface AlertingPluginSetup {
management: ManagementSetup;
Expand All @@ -69,13 +70,28 @@ export interface AlertingPluginStart {
data: DataPublicPluginStart;
}

export interface AlertingUIConfig {
rules: {
run: {
alerts: {
max: number;
};
};
};
}

export class AlertingPublicPlugin
implements
Plugin<PluginSetupContract, PluginStartContract, AlertingPluginSetup, AlertingPluginStart>
{
private alertNavigationRegistry?: AlertNavigationRegistry;
private config: AlertingUIConfig;
readonly maxAlertsPerRun?: number;

constructor(private readonly initContext: PluginInitializerContext) {}
constructor(private readonly initContext: PluginInitializerContext) {
this.config = this.initContext.config.get<AlertingUIConfig>();
this.maxAlertsPerRun = this.config.rules.run.alerts.max;
}

public setup(core: CoreSetup, plugins: AlertingPluginSetup) {
this.alertNavigationRegistry = new AlertNavigationRegistry();
Expand Down Expand Up @@ -150,6 +166,9 @@ export class AlertingPublicPlugin
return rule.viewInAppRelativeUrl;
}
},
getMaxAlertsPerRun: () => {
return this.maxAlertsPerRun;
},
};
}
}
8 changes: 5 additions & 3 deletions x-pack/plugins/alerting/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
import type { PublicMethodsOf } from '@kbn/utility-types';
import { PluginConfigDescriptor, PluginInitializerContext } from '@kbn/core/server';
import { RulesClient as RulesClientClass } from './rules_client';
import { configSchema } from './config';
import { AlertsConfigType } from './types';
import { AlertingConfig, configSchema } from './config';

export type RulesClient = PublicMethodsOf<RulesClientClass>;

Expand Down Expand Up @@ -78,8 +77,11 @@ export const plugin = async (initContext: PluginInitializerContext) => {
return new AlertingPlugin(initContext);
};

export const config: PluginConfigDescriptor<AlertsConfigType> = {
export const config: PluginConfigDescriptor<AlertingConfig> = {
schema: configSchema,
exposeToBrowser: {
Copy link
Member

Choose a reason for hiding this comment

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

If we use exposeToBrowser, then in theory we don't need this added to the triggers_actions_ui config route. Though exposeToBrowser only makes it available to the browsers alerting plugin, not t_a_ui - though obviously we could make it accessible.

But I don't think we need both, so we should pick one and not do the other. We don't need two ways to do the same thing ...

Or perhaps I missed something ...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure if I understand, the only triggers_actions_ui code that has been modified here was some test files to align with the mock alerting plugin. But to your larger point, I agree - the exposeToBrowser has been implemented here and other plugins can use them if they so choose. That's how we're utilizing it in security solution

Copy link
Member

Choose a reason for hiding this comment

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

The way this is structured we are also changing the output of the HTTP endpoint /internal/triggers_actions_ui/_config - to return ALL the values under run ,not just the alerts.max value -
which is something we need to consider re: backwards compatibility, documentation, and security (should we be exposing these via API). Do we really need to change the output of this endpoint?

$ curl $KB_URL/internal/triggers_actions_ui/_config
{"minimumScheduleInterval":{"value":"1s","enforce":false},"maxScheduledPerMinute":10000,"run":{"actions":{"max":100000},"alerts":{"max":1000}},"isUsingSecurity":true}

I believe it's also the case that the values returned by this endpoint are or can be calculated, so using the value from the config wouldn't work. Which is why we have this endpoint. Static values (I assume these are static) can just use the exposeToBrowser path.

Copy link
Member

Choose a reason for hiding this comment

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

In the end, I would like to NOT change the output of the _config route (that's adding the run props) - not so much because it's a security concern now, but feels like a slippery slope to having a problem later, if someone follows this pattern, and we do leak something we shouldn't.

Feels like we need to remove run from AlertingRulesConfig, or change the _config route in t_a_ui to pick the fields it should be returning from the bigger config object (the existing ones, but not run).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think the second way is probably the more preferable method, just so we can use that getConfig function elsewhere in other plugins without changing the _config route output. Right now we're using the getConfig function to compare on the server side in security solution as well which is why the run props were added in the first place. If y'all are ok with exposing the config values under run to that internal getConfig method from the plugin setup object and modifying the triggers_actions_ui config route so that we're locked into the existing values, I can change that over.

Copy link
Member

Choose a reason for hiding this comment

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

I don't have a problem exposting this at the plugin level - my concern is at the HTTP response level.

Filtering IN just the props we want returned from that _config endpoint would be perfect, as it means we won't have to worry about accidently leaking things later. So, in theory, x-pack/plugins/triggers_actions_ui/server/routes/config.test.ts won't have any changes, but presumably it's pair config.ts will.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok that all sounds good, I think we're on the same page 👍

rules: { run: { alerts: { max: true } } },
},
deprecations: ({ renameFromRoot, deprecate }) => [
renameFromRoot('xpack.alerts.healthCheck', 'xpack.alerting.healthCheck', { level: 'warning' }),
renameFromRoot(
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/alerting/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ export class AlertingPlugin {
getAlertIndicesAlias: createGetAlertIndicesAliasFn(this.ruleTypeRegistry!),
alertsService: this.alertsService,
uiSettings: core.uiSettings,
maxAlertsPerRun: this.config.rules.run.alerts.max,
});

rulesSettingsClientFactory.initialize({
Expand Down
4 changes: 4 additions & 0 deletions x-pack/plugins/alerting/server/rules_client/rules_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ export class RulesClient {
return this.context.auditLogger;
}

public getMaxAlertsPerRun() {
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
return this.context.maxAlertsPerRun;
}

public getTags = (params: RuleTagsParams) => getRuleTags(this.context, params);

public getScheduleFrequency = () => getScheduleFrequency(this.context);
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/alerting/server/rules_client/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
RawRuleAlertsFilter,
} from '../types';
import { AlertingAuthorization } from '../authorization';
import { AlertingRulesConfig } from '../config';
import { ActionsConfig, AlertingRulesConfig } from '../config';
import { GetAlertIndicesAlias } from '../lib';
import { AlertsService } from '../alerts_service';

Expand Down Expand Up @@ -80,6 +80,7 @@ export interface RulesClientContext {
readonly getAlertIndicesAlias: GetAlertIndicesAlias;
readonly alertsService: AlertsService | null;
readonly uiSettings: UiSettingsServiceStart;
readonly maxAlertsPerRun: ActionsConfig['max'];
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
}

export type NormalizedAlertAction = Omit<RuleAction, 'actionTypeId'>;
Expand Down
6 changes: 5 additions & 1 deletion x-pack/plugins/alerting/server/rules_client_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { SECURITY_EXTENSION_ID } from '@kbn/core-saved-objects-server';
import { RuleTypeRegistry, SpaceIdToNamespaceFunction } from './types';
import { RulesClient } from './rules_client';
import { AlertingAuthorizationClientFactory } from './alerting_authorization_client_factory';
import { AlertingRulesConfig } from './config';
import { ActionsConfig, AlertingRulesConfig } from './config';
import { GetAlertIndicesAlias } from './lib';
import { AlertsService } from './alerts_service/alerts_service';
import { RULE_SAVED_OBJECT_TYPE } from './saved_objects';
Expand All @@ -50,6 +50,7 @@ export interface RulesClientFactoryOpts {
getAlertIndicesAlias: GetAlertIndicesAlias;
alertsService: AlertsService | null;
uiSettings: CoreStart['uiSettings'];
maxAlertsPerRun: ActionsConfig['max'];
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
}

export class RulesClientFactory {
Expand All @@ -73,6 +74,7 @@ export class RulesClientFactory {
private getAlertIndicesAlias!: GetAlertIndicesAlias;
private alertsService!: AlertsService | null;
private uiSettings!: CoreStart['uiSettings'];
private maxAlertsPerRun!: ActionsConfig['max'];

public initialize(options: RulesClientFactoryOpts) {
if (this.isInitialized) {
Expand All @@ -98,6 +100,7 @@ export class RulesClientFactory {
this.getAlertIndicesAlias = options.getAlertIndicesAlias;
this.alertsService = options.alertsService;
this.uiSettings = options.uiSettings;
this.maxAlertsPerRun = options.maxAlertsPerRun;
}

public create(request: KibanaRequest, savedObjects: SavedObjectsServiceStart): RulesClient {
Expand Down Expand Up @@ -129,6 +132,7 @@ export class RulesClientFactory {
getAlertIndicesAlias: this.getAlertIndicesAlias,
alertsService: this.alertsService,
uiSettings: this.uiSettings,
maxAlertsPerRun: this.maxAlertsPerRun,

async getUserName() {
if (!securityPluginStart) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,9 @@ export const getDescriptionItem = (
return get('isBuildingBlock', data)
? [{ title: i18n.BUILDING_BLOCK_LABEL, description: i18n.BUILDING_BLOCK_DESCRIPTION }]
: [];
} else if (field === 'maxSignals') {
const value: number = get(field, data);
return [{ title: label, description: value }];
}

const description: string = get(field, data);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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, { useMemo, useCallback } from 'react';
import type { EuiFieldNumberProps } from '@elastic/eui';
import { EuiFormRow, EuiFieldNumber } from '@elastic/eui';

import type { FieldHook } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import * as i18n from './translations';
import { useKibana } from '../../../../common/lib/kibana';

interface MaxSignalsFieldProps {
dataTestSubj: string;
field: FieldHook;
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
idAria: string;
isDisabled: boolean;
placeholder?: string;
}

export const MaxSignals: React.FC<MaxSignalsFieldProps> = ({
dataTestSubj,
field,
idAria,
isDisabled,
placeholder,
}): JSX.Element => {
const { setValue, value } = field;
const { alerting } = useKibana().services;
const maxAlertsPerRun = alerting.getMaxAlertsPerRun() ?? 1000; // Defaults to 1000 in the alerting framework config
dplumlee marked this conversation as resolved.
Show resolved Hide resolved

const [isInvalid, error] = useMemo(() => {
if (typeof value === 'number' && !isNaN(value)) {
if (value <= 0) {
return [true, i18n.GREATER_THAN_ERROR];
} else if (value > maxAlertsPerRun) {
return [true, i18n.LESS_THAN_ERROR(maxAlertsPerRun)];
}
}
return [false];
}, [maxAlertsPerRun, value]);

const handleMaxSignalsChange: EuiFieldNumberProps['onChange'] = useCallback(
(e) => {
const maxSignalsValue = (e.target as HTMLInputElement).value;
// Has to handle an empty string as the field is optional
setValue(maxSignalsValue !== '' ? Number(maxSignalsValue.trim()) : '');
},
[setValue]
);

return (
<EuiFormRow
data-test-subj={dataTestSubj}
describedByIds={idAria ? [idAria] : undefined}
fullWidth
helpText={field.helpText}
label={field.label}
labelAppend={field.labelAppend}
isInvalid={isInvalid}
error={error}
>
<EuiFieldNumber
isInvalid={isInvalid}
value={value as EuiFieldNumberProps['value']}
onChange={handleMaxSignalsChange}
isLoading={field.isValidating}
fullWidth
data-test-subj="input"
placeholder={placeholder}
disabled={isDisabled}
/>
</EuiFormRow>
);
};

MaxSignals.displayName = 'MaxSignals';
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.
*/

import { i18n } from '@kbn/i18n';

export const GREATER_THAN_ERROR = i18n.translate(
'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxSignalsFieldGreaterThanError',
{
defaultMessage: 'Max signals must be greater than 0.',
}
);

export const LESS_THAN_ERROR = (maxNumber: number) =>
i18n.translate(
'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxSignalsFieldLessThanError',
{
values: { maxNumber },
defaultMessage: 'Max signals must be less than {maxNumber}.',
}
);
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ export const stepAboutDefaultValue: AboutStepRule = {
timestampOverride: '',
threat: threatDefault,
note: '',
maxSignals: 100,
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
};
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ describe('StepAboutRuleComponent', () => {
},
],
investigationFields: [],
maxSignals: 100,
};

await act(async () => {
Expand Down Expand Up @@ -341,6 +342,7 @@ describe('StepAboutRuleComponent', () => {
},
],
investigationFields: [],
maxSignals: 100,
};

await act(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { useRuleIndices } from '../../../rule_management/logic/use_rule_indices'
import { EsqlAutocomplete } from '../esql_autocomplete';
import { MultiSelectFieldsAutocomplete } from '../multi_select_fields';
import { useInvestigationFields } from '../../hooks/use_investigation_fields';
import { MaxSignals } from '../max_signals';

const CommonUseField = getUseField({ component: Field });

Expand Down Expand Up @@ -315,6 +316,18 @@ const StepAboutRuleComponent: FC<StepAboutRuleProps> = ({
/>
</EuiFormRow>
<EuiSpacer size="l" />
<EuiFormRow label={I18n.MAX_SIGNALS} fullWidth>
<CommonUseField
path="maxSignals"
component={MaxSignals}
componentProps={{
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
idAria: 'detectionEngineStepAboutRuleMaxSignals',
'data-test-subj': 'detectionEngineStepAboutRuleMaxSignals',
isDisabled: isLoading,
}}
/>
</EuiFormRow>
<EuiSpacer size="l" />
{isThreatMatchRuleValue && (
<>
<CommonUseField
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ export const schema: FormSchema<AboutStepRule> = {
),
labelAppend: OptionalFieldLabel,
},
maxSignals: {
type: FIELD_TYPES.NUMBER,
helpText: i18n.translate(
'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldMaxSignalsHelpText',
{
defaultMessage:
'The maximum number of alerts a rule will create per execution. Defaults to 100.',
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
}
),
labelAppend: OptionalFieldLabel,
},
isAssociatedToEndpointList: {
type: FIELD_TYPES.CHECKBOX,
label: i18n.translate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,10 @@ export const ADD_RULE_NOTE_HELP_TEXT = i18n.translate(
defaultMessage: 'Add rule investigation guide...',
}
);

export const MAX_SIGNALS = i18n.translate(
'xpack.securitySolution.detectionEngine.createRule.stepAboutRuleForm.maxSignalsLabel',
{
defaultMessage: 'Max signals',
}
);
Loading