Skip to content

Commit

Permalink
Create push client method
Browse files Browse the repository at this point in the history
  • Loading branch information
cnasikas committed Feb 3, 2021
1 parent 97c6913 commit f8c4c49
Show file tree
Hide file tree
Showing 13 changed files with 324 additions and 268 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
CommentResponse,
CommentType,
ConnectorMappingsAttributes,
} from '../../../../common/api';
} from '../../../common/api';

export const updateUser = {
updatedAt: '2020-03-13T08:34:53.450Z',
Expand Down
225 changes: 225 additions & 0 deletions x-pack/plugins/case/server/client/cases/push.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { isEmpty } from 'lodash/fp';
import Boom from '@hapi/boom';

import { flattenCaseSavedObject } from '../../routes/api/utils';

import {
ActionConnector,
CaseResponseRt,
CaseResponse,
CaseStatuses,
ExternalServiceResponse,
} from '../../../common/api';
import { buildCaseUserActionItem } from '../../services/user_actions/helpers';

import { CaseClientPush, CaseClientFactoryArguments } from '../types';
import { createIncident, getCommentContextFromAttributes, isCommentAlertType } from './utils';

export const push = ({
savedObjectsClient,
caseService,
caseConfigureService,
userActionService,
request,
response,
}: CaseClientFactoryArguments) => async ({
actionsClient,
caseClient,
caseId,
connectorId,
}: CaseClientPush): Promise<CaseResponse> => {
/* Start of push to external service */
const connector = await actionsClient.get({ id: connectorId });
const theCase = await caseClient.get({ id: caseId, includeComments: true });
const userActions = await caseClient.getUserActions({ caseId });
const alerts = await caseClient.getAlerts({
ids: theCase.comments?.filter(isCommentAlertType).map((comment) => comment.alertId) ?? [],
});

const connectorMappings = await caseClient.getMappings({
actionsClient,
caseClient,
connectorId: connector.id,
connectorType: connector.actionTypeId,
});

const res = await createIncident({
actionsClient,
theCase,
userActions,
connector: connector as ActionConnector,
mappings: connectorMappings,
alerts,
});

const pushRes = await actionsClient.execute({
actionId: params.connector_id,
params: {
subAction: 'pushToService',
subActionParams: res,
},
});

if (pushRes.status === 'error') {
throw new Error(pushRes.serviceMessage ?? pushRes.message ?? 'Error pushing to service');
}

/* End of push to external service */

/* Start of update case with push information */
// eslint-disable-next-line @typescript-eslint/naming-convention
const { username, full_name, email } = await caseService.getUser({ request, response });

const pushedDate = new Date().toISOString();

const [myCase, myCaseConfigure, totalCommentsFindByCases, connectors] = await Promise.all([
caseService.getCase({
client: savedObjectsClient,
caseId,
}),
caseConfigureService.find({ client: savedObjectsClient }),
caseService.getAllCaseComments({
client: savedObjectsClient,
caseId,
options: {
fields: [],
page: 1,
perPage: 1,
},
}),
actionsClient.getAll(),
]);

if (myCase.attributes.status === CaseStatuses.closed) {
throw Boom.conflict(
`This case ${myCase.attributes.title} is closed. You can not pushed if the case is closed.`
);
}

const comments = await caseService.getAllCaseComments({
client: savedObjectsClient,
caseId,
options: {
fields: [],
page: 1,
perPage: totalCommentsFindByCases.total,
},
});

const externalServiceResponse = pushRes.data as ExternalServiceResponse;

const externalService = {
pushed_at: pushedDate,
pushed_by: { username, full_name, email },
connector_id: connector.id,
connector_name: connector.name,
external_id: externalServiceResponse.id,
external_title: externalServiceResponse.title,
external_url: externalServiceResponse.url,
};

const updateConnector = myCase.attributes.connector;

if (
isEmpty(updateConnector) ||
(updateConnector != null && updateConnector.id === 'none') ||
!connectors.some((c) => c.id === updateConnector.id)
) {
throw Boom.notFound('Connector not found or set to none');
}

const [updatedCase, updatedComments] = await Promise.all([
caseService.patchCase({
client: savedObjectsClient,
caseId,
updatedAttributes: {
...(myCaseConfigure.total > 0 &&
myCaseConfigure.saved_objects[0].attributes.closure_type === 'close-by-pushing'
? {
status: CaseStatuses.closed,
closed_at: pushedDate,
closed_by: { email, full_name, username },
}
: {}),
external_service: externalService,
updated_at: pushedDate,
updated_by: { username, full_name, email },
},
version: myCase.version,
}),

caseService.patchComments({
client: savedObjectsClient,
comments: comments.saved_objects
.filter((comment) => comment.attributes.pushed_at == null)
.map((comment) => ({
commentId: comment.id,
updatedAttributes: {
pushed_at: pushedDate,
pushed_by: { username, full_name, email },
},
version: comment.version,
})),
}),

userActionService.postUserActions({
client: savedObjectsClient,
actions: [
...(myCaseConfigure.total > 0 &&
myCaseConfigure.saved_objects[0].attributes.closure_type === 'close-by-pushing'
? [
buildCaseUserActionItem({
action: 'update',
actionAt: pushedDate,
actionBy: { username, full_name, email },
caseId,
fields: ['status'],
newValue: CaseStatuses.closed,
oldValue: myCase.attributes.status,
}),
]
: []),
buildCaseUserActionItem({
action: 'push-to-service',
actionAt: pushedDate,
actionBy: { username, full_name, email },
caseId,
fields: ['pushed'],
newValue: JSON.stringify(externalService),
}),
],
}),
]);
/* End of update case with push information */

return CaseResponseRt.encode(
flattenCaseSavedObject({
savedObject: {
...myCase,
...updatedCase,
attributes: { ...myCase.attributes, ...updatedCase?.attributes },
references: myCase.references,
},
comments: comments.saved_objects.map((origComment) => {
const updatedComment = updatedComments.saved_objects.find((c) => c.id === origComment.id);
return {
...origComment,
...updatedComment,
attributes: {
...origComment.attributes,
...updatedComment?.attributes,
...getCommentContextFromAttributes(origComment.attributes),
},
version: updatedComment?.version ?? origComment.version,
references: origComment?.references ?? [],
};
}),
})
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { BasicParams, ExternalServiceParams, Incident } from '../../../../common/api';
import { BasicParams, ExternalServiceParams, Incident } from '../../../common/api';

import {
createIncident,
Expand All @@ -15,9 +15,9 @@ import {
} from './utils';

import { comment as commentObj, mappings, defaultPipes, basicParams, updateUser } from './mock';
import { actionsClientMock } from '../../../../../actions/server/actions_client.mock';
import { flattenCaseSavedObject } from '../utils';
import { mockCases } from '../__fixtures__';
import { actionsClientMock } from '../../../../actions/server/actions_client.mock';
import { flattenCaseSavedObject } from '../../routes/api/utils';
import { mockCases } from '../../routes/api/__fixtures__';

const formatComment = {
commentId: commentObj.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,14 @@ import {
Transformer,
TransformerArgs,
TransformFieldsArgs,
} from '../../../../common/api';
import { ActionsClient } from '../../../../../actions/server';
import { externalServiceFormatters, FormatterConnectorTypes } from '../../../connectors';
import { CaseClientGetAlertsResponse } from '../../../client/alerts/types';
CommentAttributes,
CommentRequestUserType,
CommentRequestAlertType,
} from '../../../common/api';
import { ActionsClient } from '../../../../actions/server';
import { externalServiceFormatters, FormatterConnectorTypes } from '../../connectors';
import { CaseClientGetAlertsResponse } from '../../client/alerts/types';
import { isUserContext } from '../../routes/api/utils';

export const getLatestPushInfo = (
connectorId: string,
Expand Down Expand Up @@ -289,3 +293,17 @@ export const transformComments = (
export const isCommentAlertType = (
comment: CommentResponse
): comment is CommentResponseAlertsType => comment.type === CommentType.alert;

export const getCommentContextFromAttributes = (
attributes: CommentAttributes
): CommentRequestUserType | CommentRequestAlertType =>
isUserContext(attributes)
? {
type: CommentType.user,
comment: attributes.comment,
}
: {
type: CommentType.alert,
alertId: attributes.alertId,
index: attributes.index,
};
21 changes: 21 additions & 0 deletions x-pack/plugins/case/server/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { CaseClientFactoryArguments, CaseClient } from './types';
import { create } from './cases/create';
import { get } from './cases/get';
import { update } from './cases/update';
import { push } from './cases/push';
import { addComment } from './comments/add';
import { getFields } from './configure/get_fields';
import { getMappings } from './configure/get_mappings';
Expand All @@ -23,6 +24,7 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
alertsService,
Expand All @@ -35,6 +37,7 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -44,6 +47,7 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -53,15 +57,28 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
push: push({
alertsService,
caseConfigureService,
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
context,
}),
addComment: addComment({
alertsService,
caseConfigureService,
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -72,6 +89,7 @@ export const createCaseClient = ({
connectorMappingsService,
context,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -82,6 +100,7 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -91,6 +110,7 @@ export const createCaseClient = ({
caseService,
connectorMappingsService,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand All @@ -101,6 +121,7 @@ export const createCaseClient = ({
connectorMappingsService,
context,
request,
response,
savedObjectsClient,
userActionService,
}),
Expand Down
Loading

0 comments on commit f8c4c49

Please sign in to comment.