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

[System Actions] Complete API audit and update APIs to comply with System Actions #172937

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions x-pack/plugins/alerting/common/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ export interface RuleSystemAction {
actionTypeId: string;
params: RuleActionParams;
type: typeof RuleActionTypes.SYSTEM;
useAlertDataForTemplate?: boolean;
}

export type RuleAction = RuleDefaultAction | RuleSystemAction;
Expand Down
15 changes: 5 additions & 10 deletions x-pack/plugins/alerting/server/routes/clone_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,21 @@
import { schema } from '@kbn/config-schema';
import { IRouter } from '@kbn/core/server';
import { ILicenseState, RuleTypeDisabledError } from '../lib';
import {
verifyAccessAndContext,
RewriteResponseCase,
handleDisabledApiKeysError,
rewriteRuleLastRun,
rewriteActionsRes,
} from './lib';
import { verifyAccessAndContext, handleDisabledApiKeysError, rewriteRuleLastRun } from './lib';
import {
RuleTypeParams,
AlertingRequestHandlerContext,
INTERNAL_BASE_ALERTING_API_PATH,
PartialRule,
} from '../types';
import { transformRuleActions } from './rule/transforms';

const paramSchema = schema.object({
id: schema.string(),
newId: schema.maybe(schema.string()),
});

const rewriteBodyRes: RewriteResponseCase<PartialRule<RuleTypeParams>> = ({
const rewriteBodyRes = ({
actions,
alertTypeId,
scheduledTaskId,
Expand All @@ -46,7 +41,7 @@ const rewriteBodyRes: RewriteResponseCase<PartialRule<RuleTypeParams>> = ({
lastRun,
nextRun,
...rest
}) => ({
}: PartialRule<RuleTypeParams>) => ({
...rest,
api_key_owner: apiKeyOwner,
created_by: createdBy,
Expand All @@ -71,7 +66,7 @@ const rewriteBodyRes: RewriteResponseCase<PartialRule<RuleTypeParams>> = ({
: {}),
...(actions
? {
actions: rewriteActionsRes(actions),
actions: transformRuleActions(actions),
}
: {}),
...(lastRun ? { last_run: rewriteRuleLastRun(lastRun) } : {}),
Expand Down
13 changes: 2 additions & 11 deletions x-pack/plugins/alerting/server/routes/find_rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@ import { UsageCounter } from '@kbn/usage-collection-plugin/server';
import { schema } from '@kbn/config-schema';
import { ILicenseState } from '../lib';
import { FindOptions, FindResult } from '../rules_client';
import {
RewriteRequestCase,
RewriteResponseCase,
verifyAccessAndContext,
rewriteRule,
} from './lib';
import { RewriteRequestCase, verifyAccessAndContext, rewriteRule } from './lib';
import {
RuleTypeParams,
AlertingRequestHandlerContext,
Expand Down Expand Up @@ -69,11 +64,7 @@ const rewriteQueryReq: RewriteRequestCase<FindOptions> = ({
...(hasReference ? { hasReference } : {}),
...(searchFields ? { searchFields } : {}),
});
const rewriteBodyRes: RewriteResponseCase<FindResult<RuleTypeParams>> = ({
perPage,
data,
...restOfResult
}) => {
const rewriteBodyRes = ({ perPage, data, ...restOfResult }: FindResult<RuleTypeParams>) => {
return {
...restOfResult,
per_page: perPage,
Expand Down
14 changes: 5 additions & 9 deletions x-pack/plugins/alerting/server/routes/get_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,21 @@ import { omit } from 'lodash';
import { schema } from '@kbn/config-schema';
import { IRouter } from '@kbn/core/server';
import { ILicenseState } from '../lib';
import {
verifyAccessAndContext,
RewriteResponseCase,
rewriteRuleLastRun,
rewriteActionsRes,
} from './lib';
import { verifyAccessAndContext, rewriteRuleLastRun } from './lib';
import {
RuleTypeParams,
AlertingRequestHandlerContext,
BASE_ALERTING_API_PATH,
INTERNAL_BASE_ALERTING_API_PATH,
SanitizedRule,
} from '../types';
import { transformRuleActions } from './rule/transforms';

const paramSchema = schema.object({
id: schema.string(),
});

const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
const rewriteBodyRes = ({
alertTypeId,
createdBy,
updatedBy,
Expand All @@ -47,7 +43,7 @@ const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
nextRun,
viewInAppRelativeUrl,
...rest
}) => ({
}: SanitizedRule<RuleTypeParams>) => ({
...rest,
rule_type_id: alertTypeId,
created_by: createdBy,
Expand All @@ -66,7 +62,7 @@ const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
last_execution_date: executionStatus.lastExecutionDate,
last_duration: executionStatus.lastDuration,
},
actions: rewriteActionsRes(actions),
actions: transformRuleActions(actions),
...(lastRun ? { last_run: rewriteRuleLastRun(lastRun) } : {}),
...(nextRun ? { next_run: nextRun } : {}),
...(viewInAppRelativeUrl ? { view_in_app_relative_url: viewInAppRelativeUrl } : {}),
Expand Down
6 changes: 1 addition & 5 deletions x-pack/plugins/alerting/server/routes/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ export type {
} from './rewrite_request_case';
export { verifyAccessAndContext } from './verify_access_and_context';
export { countUsageOfPredefinedIds } from './count_usage_of_predefined_ids';
export {
rewriteActionsReq,
rewriteActionsRes,
rewriteActionsReqWithSystemActions,
} from './rewrite_actions';
export { rewriteActionsReq } from './rewrite_actions';
export { actionsSchema } from './actions_schema';
export { rewriteRule, rewriteRuleLastRun } from './rewrite_rule';
export { rewriteNamespaces } from './rewrite_namespaces';
Expand Down
81 changes: 19 additions & 62 deletions x-pack/plugins/alerting/server/routes/lib/rewrite_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import { TypeOf } from '@kbn/config-schema/src/types/object_type';
import { omit } from 'lodash';
import { NormalizedAlertAction } from '../../rules_client';
import { RuleAction } from '../../types';
import { actionsSchema } from './actions_schema';
import { RuleActionTypes } from '../../../common';

export const rewriteActionsReq = (
actions?: TypeOf<typeof actionsSchema>
actions: TypeOf<typeof actionsSchema>,
isSystemAction: (connectorId: string) => boolean
): NormalizedAlertAction[] => {
if (!actions) return [];

Expand All @@ -23,78 +23,35 @@ export const rewriteActionsReq = (
use_alert_data_for_template: useAlertDataForTemplate,
...action
}) => {
if (isSystemAction(action.id)) {
return {
id: action.id,
params: action.params,
...(typeof useAlertDataForTemplate !== 'undefined' ? { useAlertDataForTemplate } : {}),
...(action.uuid ? { uuid: action.uuid } : {}),
type: RuleActionTypes.SYSTEM,
};
Comment on lines +27 to +33
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's write some unit tests for this

}

return {
...action,
group: action.group ?? 'default',
id: action.id,
params: action.params,
...(action.uuid ? { uuid: action.uuid } : {}),
...(typeof useAlertDataForTemplate !== 'undefined' ? { useAlertDataForTemplate } : {}),
...(frequency
? {
frequency: {
...omit(frequency, 'notify_when'),
summary: frequency.summary,
throttle: frequency.throttle,
notifyWhen: frequency.notify_when,
},
}
: {}),
...(alertsFilter ? { alertsFilter } : {}),
type: RuleActionTypes.DEFAULT,
};
}
);
};

export const rewriteActionsReqWithSystemActions = (
actions: TypeOf<typeof actionsSchema>,
isSystemAction: (connectorId: string) => boolean
): NormalizedAlertAction[] => {
if (!actions) return [];

return actions.map(({ frequency, alerts_filter: alertsFilter, ...action }) => {
if (isSystemAction(action.id)) {
return {
id: action.id,
params: action.params,
...(action.uuid ? { uuid: action.uuid } : {}),
type: RuleActionTypes.SYSTEM,
};
}

return {
group: action.group ?? 'default',
id: action.id,
params: action.params,
...(action.uuid ? { uuid: action.uuid } : {}),
...(frequency
? {
frequency: {
summary: frequency.summary,
throttle: frequency.throttle,
notifyWhen: frequency.notify_when,
},
}
: {}),
...(alertsFilter ? { alertsFilter } : {}),
type: RuleActionTypes.DEFAULT,
};
});
};

export const rewriteActionsRes = (actions?: RuleAction[]) => {
const rewriteFrequency = ({ notifyWhen, ...rest }: NonNullable<RuleAction['frequency']>) => ({
...rest,
notify_when: notifyWhen,
});
if (!actions) return [];
return actions.map(
({ actionTypeId, frequency, alertsFilter, useAlertDataForTemplate, ...action }) => ({
...action,
connector_type_id: actionTypeId,
...(typeof useAlertDataForTemplate !== 'undefined'
? { use_alert_data_for_template: useAlertDataForTemplate }
: {}),
...(frequency ? { frequency: rewriteFrequency(frequency) } : {}),
...(alertsFilter
? {
alerts_filter: alertsFilter,
}
: {}),
})
);
};
56 changes: 38 additions & 18 deletions x-pack/plugins/alerting/server/routes/lib/rewrite_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
*/
import { omit } from 'lodash';

import { RuleTypeParams, SanitizedRule, RuleLastRun } from '../../types';
import {
RuleTypeParams,
SanitizedRule,
RuleLastRun,
RuleActionTypes,
RuleDefaultAction,
} from '../../types';

export const rewriteRuleLastRun = (lastRun: RuleLastRun) => {
const { outcomeMsg, outcomeOrder, alertsCount, ...rest } = lastRun;
Expand Down Expand Up @@ -58,23 +64,37 @@ export const rewriteRule = ({
last_execution_date: executionStatus.lastExecutionDate,
last_duration: executionStatus.lastDuration,
},
actions: actions.map(({ group, id, actionTypeId, params, frequency, uuid, alertsFilter }) => ({
group,
id,
params,
connector_type_id: actionTypeId,
...(frequency
? {
frequency: {
summary: frequency.summary,
notify_when: frequency.notifyWhen,
throttle: frequency.throttle,
},
}
: {}),
...(uuid && { uuid }),
...(alertsFilter && { alerts_filter: alertsFilter }),
})),
actions: actions.map(
({ id, actionTypeId, params, uuid, type, useAlertDataForTemplate, ...action }) => {
if (type === RuleActionTypes.SYSTEM) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's write some unit tests for this as well

return {
...action,
connector_type_id: actionTypeId,
...(typeof useAlertDataForTemplate !== 'undefined'
? { use_alert_data_for_template: useAlertDataForTemplate }
: {}),
};
}
const { group, frequency, alertsFilter } = action as RuleDefaultAction;
return {
group,
id,
params,
connector_type_id: actionTypeId,
...(frequency
? {
frequency: {
summary: frequency.summary,
notify_when: frequency.notifyWhen,
throttle: frequency.throttle,
},
}
: {}),
...(uuid && { uuid }),
...(alertsFilter && { alerts_filter: alertsFilter }),
};
}
),
...(lastRun ? { last_run: rewriteRuleLastRun(lastRun) } : {}),
...(nextRun ? { next_run: nextRun } : {}),
...(apiKeyCreatedByUser !== undefined ? { api_key_created_by_user: apiKeyCreatedByUser } : {}),
Expand Down
10 changes: 4 additions & 6 deletions x-pack/plugins/alerting/server/routes/update_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
handleDisabledApiKeysError,
actionsSchema,
rewriteRuleLastRun,
rewriteActionsReqWithSystemActions,
rewriteActionsReq,
} from './lib';
import {
RuleTypeParams,
Expand Down Expand Up @@ -70,7 +70,7 @@ const rewriteBodyReq = (
data: {
...rest,
notifyWhen,
actions: rewriteActionsReqWithSystemActions(actions, isSystemAction),
actions: rewriteActionsReq(actions, isSystemAction),
},
};
};
Expand Down Expand Up @@ -146,15 +146,13 @@ export const updateRuleRoute = (
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
const rulesClient = (await context.alerting).getRulesClient();
const actionsClient = (await context.actions).getActionsClient();
const { isSystemAction } = (await context.actions).getActionsClient();
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we have E2E test cases to assert the correct output for these endpoints?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Don't think so but as per Zoom discussion with @XavierM this is out of scope for this PR. Tracked here: #173761


const { id } = req.params;
const rule = req.body;
try {
const alertRes = await rulesClient.update(
rewriteBodyReq({ id, data: rule }, (connectorId: string) =>
actionsClient.isSystemAction(connectorId)
)
rewriteBodyReq({ id, data: rule }, isSystemAction)
);
return res.ok({
body: rewriteBodyRes(alertRes),
Expand Down