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

[ALERTING][CONNECTOR] Swimlane #95109

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const ACTION_TYPE_IDS = [
'.pagerduty',
'.server-log',
'.slack',
'.swimlane',
'.teams',
'.webhook',
];
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/actions/server/builtin_action_types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Logger } from '../../../../../src/core/server';
import { getActionType as getEmailActionType } from './email';
import { getActionType as getIndexActionType } from './es_index';
import { getActionType as getPagerDutyActionType } from './pagerduty';
import { getActionType as getSwimlaneActionType } from './swimlane';
import { getActionType as getServerLogActionType } from './server_log';
import { getActionType as getSlackActionType } from './slack';
import { getActionType as getWebhookActionType } from './webhook';
Expand Down Expand Up @@ -65,6 +66,7 @@ export function registerBuiltInActionTypes({
);
actionTypeRegistry.register(getIndexActionType({ logger }));
actionTypeRegistry.register(getPagerDutyActionType({ logger, configurationUtilities }));
actionTypeRegistry.register(getSwimlaneActionType({ logger, configurationUtilities }));
actionTypeRegistry.register(getServerLogActionType({ logger }));
actionTypeRegistry.register(getSlackActionType({ logger, configurationUtilities }));
actionTypeRegistry.register(getWebhookActionType({ logger, configurationUtilities }));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* 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 { api } from './api';
import { ExternalService } from './types';
import { externalServiceMock } from './mocks';
import { Logger } from '@kbn/logging';
let mockedLogger: jest.Mocked<Logger>;

describe('api', () => {
let externalService: jest.Mocked<ExternalService>;

beforeEach(() => {
externalService = externalServiceMock.create();
});

describe('createRecord', () => {
test('it creates a record correctly', async () => {
const res = await api.createRecord({
externalService,
logger: mockedLogger,
params: {
alertName: 'alert name',
caseName: 'case name',
severity: 'critical',
alertSource: 'elastic',
caseId: '123456',
comments: 'some comments',
},
});
expect(res).toEqual({
id: '123456',
});
});
});
});
19 changes: 19 additions & 0 deletions x-pack/plugins/actions/server/builtin_action_types/swimlane/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* 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 { CreateRecordApiHandlerArgs, CreateRecordResponse, ExternalServiceApi } from './types';

const createRecordHandler = async ({
externalService,
params,
}: CreateRecordApiHandlerArgs): Promise<CreateRecordResponse> => {
return await externalService.createRecord(params);
};

export const api: ExternalServiceApi = {
createRecord: createRecordHandler,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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 { MappingConfigType } from './types';
import { getBodyForEventAction } from './helpers';

describe('Create Record Mapping', () => {
let mappingConfig: MappingConfigType;
const appId = '45678';

beforeAll(() => {
mappingConfig = {
alertSourceConfig: {
id: 'adnjls',
name: 'Alert Source',
key: 'alert-source',
fieldType: 'text',
},
severityConfig: {
id: 'adnlas',
name: 'Severity',
key: 'severity',
fieldType: 'text',
},
alertNameConfig: {
id: 'adnfls',
name: 'Alert Name',
key: 'alert-name',
fieldType: 'text',
},
caseIdConfig: {
id: 'a6sst',
name: 'Case Id',
key: 'case-id-name',
fieldType: 'text',
},
caseNameConfig: {
id: 'a6fst',
name: 'Case Name',
key: 'case-name',
fieldType: 'text',
},
commentsConfig: {
id: 'a6fdf',
name: 'Comments',
key: 'comments',
fieldType: 'text',
},
};
});

test('Mapping is Successful', () => {
const params = {
alertName: 'Alert Name',
severity: 'Critical',
alertSource: 'Elastic',
caseName: 'Case Name',
caseId: 'es3456789',
comments: 'This is a comment',
};
const data = getBodyForEventAction(appId, mappingConfig, params);
expect(data?.values?.[mappingConfig.alertSourceConfig.id]).toEqual(params.alertSource);
expect(data?.values?.[mappingConfig.alertNameConfig.id]).toEqual(params.alertName);
// @ts-ignore
expect(data?.values?.[mappingConfig.caseNameConfig.id]).toEqual(params.caseName);
expect(data?.values?.[mappingConfig.caseIdConfig.id]).toEqual(params.caseId);
// @ts-ignore
expect(data?.values?.[mappingConfig.commentsConfig.id]).toEqual(params.comments);
expect(data?.values?.[mappingConfig.severityConfig.id]).toEqual(params.severity);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* 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 { CreateRecordParams, MappingConfigType, SwimlaneRecordPayload } from './types';

export const getBodyForEventAction = (
applicationId: string,
mappingConfig: MappingConfigType,
params: CreateRecordParams
): SwimlaneRecordPayload => {
const data: SwimlaneRecordPayload = {
applicationId,
};

const values: Record<string, string | number> = {};

for (const mappingsKey in mappingConfig) {
if (!Object.hasOwnProperty.call(mappingConfig, mappingsKey)) {
continue;
}

const fieldMap = mappingConfig[mappingsKey];

if (!fieldMap) {
continue;
}

const { id, fieldType } = fieldMap;
const paramName = mappingsKey.replace('Config', '');
if (params[paramName]) {
const value = params[paramName];
if (value) {
switch (fieldType) {
case 'numeric': {
values[id] = +value;
break;
}
default: {
values[id] = value;
break;
}
}
}
}
}

data.values = values;

return data;
};
117 changes: 117 additions & 0 deletions x-pack/plugins/actions/server/builtin_action_types/swimlane/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* 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 { curry } from 'lodash';
import { i18n } from '@kbn/i18n';
import { schema } from '@kbn/config-schema';
import { Logger } from '@kbn/logging';
import { ActionType, ActionTypeExecutorOptions, ActionTypeExecutorResult } from '../../types';
import { ActionsConfigurationUtilities } from '../../actions_config';
import {
SwimlaneExecutorResultData,
SwimlanePublicConfigurationType,
SwimlaneSecretConfigurationType,
ExecutorParams,
ExecutorSubActionCreateRecordParams,
} from './types';
import { validate } from './validators';
import {
ExecutorParamsSchema,
SwimlaneSecretsConfiguration,
SwimlaneServiceConfiguration,
} from './schema';
import { createExternalService } from './service';
import { api } from './api';

interface GetActionTypeParams {
logger: Logger;
configurationUtilities: ActionsConfigurationUtilities;
}

const supportedSubActions: string[] = ['application', 'createRecord'];

// action type definition
export function getActionType(
params: GetActionTypeParams
): ActionType<
SwimlanePublicConfigurationType,
SwimlaneSecretConfigurationType,
ExecutorParams,
SwimlaneExecutorResultData | {}
> {
const { logger, configurationUtilities } = params;

return {
id: '.swimlane',
minimumLicenseRequired: 'gold',
name: i18n.translate('xpack.actions.builtin.swimlaneTitle', {
defaultMessage: 'Swimlane',
}),
validate: {
config: schema.object(SwimlaneServiceConfiguration, {
validate: curry(validate.config)(configurationUtilities),
}),
secrets: schema.object(SwimlaneSecretsConfiguration, {
validate: curry(validate.secrets)(configurationUtilities),
}),
params: ExecutorParamsSchema,
},
executor: curry(executor)({ logger, configurationUtilities }),
};
}

async function executor(
{
logger,
configurationUtilities,
}: { logger: Logger; configurationUtilities: ActionsConfigurationUtilities },
execOptions: ActionTypeExecutorOptions<
SwimlanePublicConfigurationType,
SwimlaneSecretConfigurationType,
ExecutorParams
>
): Promise<ActionTypeExecutorResult<SwimlaneExecutorResultData | {}>> {
const { actionId, config, params, secrets } = execOptions;
const { subAction, subActionParams } = params as ExecutorParams;

let data: SwimlaneExecutorResultData | null = null;

const externalService = createExternalService(
{
config,
secrets,
},
logger,
configurationUtilities
);

if (!api[subAction]) {
const errorMessage = `[Action][ExternalService] -> [Swimlane] Unsupported subAction type ${subAction}.`;
logger.error(errorMessage);
throw new Error(errorMessage);
}

if (!supportedSubActions.includes(subAction)) {
const errorMessage = `[Action][ExternalService] -> [Swimlane] subAction ${subAction} not implemented.`;
logger.error(errorMessage);
throw new Error(errorMessage);
}

if (subAction === 'createRecord') {
const createRecordParams = subActionParams as ExecutorSubActionCreateRecordParams;

data = await api.createRecord({
externalService,
params: createRecordParams,
logger,
});

logger.debug(`Swimlane new record id ${data.id}`);
}

return { status: 'ok', data: data ?? {}, actionId };
}
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 {
CreateRecordApiParams,
ExecutorSubActionCreateRecordParams,
ExternalService,
} from './types';

const createMock = (): jest.Mocked<ExternalService> => {
return {
createRecord: jest.fn().mockImplementation(() =>
Promise.resolve({
id: '123456',
})
),
};
};

const externalServiceMock = {
create: createMock,
};

const executorParams: ExecutorSubActionCreateRecordParams = {
alertName: 'alert-name',
alertSource: 'alert-source',
caseId: 'case-id',
caseName: 'case-name',
comments: 'comments',
severity: 'severity',
};

const apiParams: CreateRecordApiParams = {
...executorParams,
};

export { externalServiceMock, executorParams, apiParams };
Loading