Skip to content

Commit

Permalink
[ResponseOps][Cases] Add additional fields to ServiceNow cases integr…
Browse files Browse the repository at this point in the history
…ation (elastic#201948)

Closes elastic/enhancements#22091

## Summary

The ServiceNow ITSM and SecOps connector for cases now supports the
`Additional fields` JSON field. This is an object where the keys
correspond to the internal names of the table columns in ServiceNow.

## How to test

1. Cases with an existing ServiceNow connector configuration should not
break.
2. The additional fields' validation works as expected.
3. Adding additional fields to the ServiceNow connector works as
expected and these fields are sent to ServiceNow.

Testing can be tricky because ServiceNow ignores additional fields where
the key is not known or the value is not accepted. You need to make sure
the key matches an existing column and that the value is allowed **on
ServiceNow**.

### SecOps

The original issue concerned the fields `Configuration item`, `Affected
user`, and `Location` so these must work.

An example request **for SecOps** with these fields' keys is the
following:

```
{
  "u_cmdb_ci": "*ANNIE-IBM",
  "u_location": "815 E Street, San Diego,CA",
  "u_affected_user": "Antonio Coelho"
}
```

This should result in:

<img width="901" alt="Screenshot 2024-11-27 at 12 52 37"
src="https://github.com/user-attachments/assets/6734a50b-b413-4587-b5e2-2caf2e30ad67">

**The tricky part here is that they should be the names of existing
resources in ServiceNow so the values cannot be arbitrary.**

### ITSM

ITSM fields are different than the ones in SecOps. An example object is:

```
{
  "u_assignment_group": "Database" 
}
```

This results in:

<img width="1378" alt="Screenshot 2024-11-27 at 13 46 56"
src="https://github.com/user-attachments/assets/8064f882-2ab5-4fd6-b123-90938ab3bb83">

## Release Notes

Pass any field to ServiceNow using the ServiceNow SecOps connector with
a JSON field called "additional fields".

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
2 people authored and viduni94 committed Jan 2, 2025
1 parent 236f72d commit d686a3f
Show file tree
Hide file tree
Showing 27 changed files with 576 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,20 @@ const ConnectorResilientTypeFieldsRt = rt.strict({
* ServiceNow
*/

export const ServiceNowITSMFieldsRt = rt.strict({
impact: rt.union([rt.string, rt.null]),
severity: rt.union([rt.string, rt.null]),
urgency: rt.union([rt.string, rt.null]),
category: rt.union([rt.string, rt.null]),
subcategory: rt.union([rt.string, rt.null]),
});
export const ServiceNowITSMFieldsRt = rt.intersection([
rt.strict({
impact: rt.union([rt.string, rt.null]),
severity: rt.union([rt.string, rt.null]),
urgency: rt.union([rt.string, rt.null]),
category: rt.union([rt.string, rt.null]),
subcategory: rt.union([rt.string, rt.null]),
}),
rt.exact(
rt.partial({
additionalFields: rt.union([rt.string, rt.null]),
})
),
]);

export type ServiceNowITSMFieldsType = rt.TypeOf<typeof ServiceNowITSMFieldsRt>;

Expand All @@ -81,15 +88,22 @@ const ConnectorServiceNowITSMTypeFieldsRt = rt.strict({
fields: rt.union([ServiceNowITSMFieldsRt, rt.null]),
});

export const ServiceNowSIRFieldsRt = rt.strict({
category: rt.union([rt.string, rt.null]),
destIp: rt.union([rt.boolean, rt.null]),
malwareHash: rt.union([rt.boolean, rt.null]),
malwareUrl: rt.union([rt.boolean, rt.null]),
priority: rt.union([rt.string, rt.null]),
sourceIp: rt.union([rt.boolean, rt.null]),
subcategory: rt.union([rt.string, rt.null]),
});
export const ServiceNowSIRFieldsRt = rt.intersection([
rt.strict({
category: rt.union([rt.string, rt.null]),
destIp: rt.union([rt.boolean, rt.null]),
malwareHash: rt.union([rt.boolean, rt.null]),
malwareUrl: rt.union([rt.boolean, rt.null]),
priority: rt.union([rt.string, rt.null]),
sourceIp: rt.union([rt.boolean, rt.null]),
subcategory: rt.union([rt.string, rt.null]),
}),
rt.exact(
rt.partial({
additionalFields: rt.union([rt.string, rt.null]),
})
),
]);

export type ServiceNowSIRFieldsType = rt.TypeOf<typeof ServiceNowSIRFieldsRt>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,7 @@ describe('CommonFlyout ', () => {
impact: null,
category: 'software',
subcategory: null,
additionalFields: null,
},
},
settings: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,32 @@ describe('ConnectorCard ', () => {
expect(getByText(`${item.title}: ${item.description}`)).toBeInTheDocument();
}
});

it('shows a codeblock when applicable', async () => {
render(
<ConnectorCard
connectorType={ConnectorTypes.none}
title="My connector"
listItems={[{ title: 'some title', description: 'some code', displayAsCodeBlock: true }]}
isLoading={false}
/>
);

expect(await screen.findByTestId('card-list-item')).toBeInTheDocument();
expect(await screen.findByTestId('card-list-code-block')).toBeInTheDocument();
});

it('does not show a codeblock when not necessary', async () => {
render(
<ConnectorCard
connectorType={ConnectorTypes.none}
title="My connector"
listItems={[{ title: 'some title', description: 'some code' }]}
isLoading={false}
/>
);

expect(await screen.findByTestId('card-list-item')).toBeInTheDocument();
expect(screen.queryByTestId('card-list-code-block')).not.toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
*/

import React, { memo } from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiSkeletonText, EuiText } from '@elastic/eui';
import {
EuiFlexGroup,
EuiFlexItem,
EuiIcon,
EuiSkeletonText,
EuiText,
EuiCodeBlock,
} from '@elastic/eui';

import type { ConnectorTypes } from '../../../common/types/domain';
import { useKibana } from '../../common/lib/kibana';
Expand All @@ -15,7 +22,7 @@ import { getConnectorIcon } from '../utils';
interface ConnectorCardProps {
connectorType: ConnectorTypes;
title: string;
listItems: Array<{ title: string; description: React.ReactNode }>;
listItems: Array<{ title: string; description: React.ReactNode; displayAsCodeBlock?: boolean }>;
isLoading: boolean;
}

Expand Down Expand Up @@ -47,12 +54,28 @@ const ConnectorCardDisplay: React.FC<ConnectorCardProps> = ({
</EuiFlexGroup>
<EuiFlexItem data-test-subj="connector-card-details">
{listItems.length > 0 &&
listItems.map((item, i) => (
<EuiText size="xs" data-test-subj="card-list-item" key={`${item.title}-${i}`}>
<strong>{`${item.title}: `}</strong>
{`${item.description}`}
</EuiText>
))}
listItems.map((item, i) =>
item.displayAsCodeBlock ? (
<>
<EuiText size="xs" data-test-subj="card-list-item" key={`${item.title}-${i}`}>
<strong>{`${item.title}:`}</strong>
</EuiText>
<EuiCodeBlock
data-test-subj="card-list-code-block"
language="json"
fontSize="s"
paddingSize="s"
>
{`${item.description}`}
</EuiCodeBlock>
</>
) : (
<EuiText size="xs" data-test-subj="card-list-item" key={`${item.title}-${i}`}>
<strong>{`${item.title}: `}</strong>
{`${item.description}`}
</EuiText>
)
)}
</EuiFlexItem>
</EuiFlexGroup>
</EuiSkeletonText>
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, { type ComponentProps } from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { JsonEditorField } from './json_editor_field';
import { MockedCodeEditor } from '@kbn/code-editor-mock';
import type { FieldHook } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import type { MockedMonacoEditor } from '@kbn/code-editor-mock/monaco_mock';

jest.mock('@kbn/code-editor', () => {
const original = jest.requireActual('@kbn/code-editor');
return {
...original,
CodeEditor: (props: ComponentProps<typeof MockedMonacoEditor>) => (
<MockedCodeEditor {...props} />
),
};
});

const setXJson = jest.fn();
const XJson = {
useXJsonMode: (value: unknown) => ({
convertToJson: (toJson: unknown) => toJson,
setXJson,
xJson: value,
}),
};

jest.mock('@kbn/es-ui-shared-plugin/public', () => {
const original = jest.requireActual('@kbn/es-ui-shared-plugin/public');
return {
...original,
XJson,
};
});

describe('JsonEditorField', () => {
const setValue = jest.fn();
const props = {
field: {
label: 'my label',
helpText: 'help',
value: 'foobar',
setValue,
errors: [],
} as unknown as FieldHook<unknown, string>,
paramsProperty: 'myField',
label: 'label',
dataTestSubj: 'foobarTestSubj',
};

beforeEach(() => jest.resetAllMocks());

it('renders as expected', async () => {
render(<JsonEditorField {...props} />);

expect(await screen.findByTestId('foobarTestSubj')).toBeInTheDocument();
expect(await screen.findByTestId('myFieldJsonEditor')).toBeInTheDocument();
expect(await screen.findByText('my label')).toBeInTheDocument();
});

it('calls setValue and xJson on editor change', async () => {
render(<JsonEditorField {...props} />);

await userEvent.click(await screen.findByTestId('myFieldJsonEditor'));
await userEvent.paste('JSON');

await waitFor(() => {
expect(setValue).toBeCalledWith('foobarJSON');
});

expect(setXJson).toBeCalledWith('foobarJSON');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* 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, { useCallback, useEffect } from 'react';
import { EuiFormRow } from '@elastic/eui';

import { XJsonLang } from '@kbn/monaco';

import { XJson } from '@kbn/es-ui-shared-plugin/public';
import { CodeEditor } from '@kbn/code-editor';

import {
getFieldValidityAndErrorMessage,
type FieldHook,
} from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import { i18n } from '@kbn/i18n';

interface Props {
field: FieldHook<unknown, string>;
paramsProperty: string;
ariaLabel?: string;
onBlur?: () => void;
dataTestSubj?: string;
euiCodeEditorProps?: { [key: string]: unknown };
}

const { useXJsonMode } = XJson;

export const JsonEditorField: React.FunctionComponent<Props> = ({
field,
paramsProperty,
ariaLabel,
dataTestSubj,
euiCodeEditorProps = {},
}) => {
const { label: fieldLabel, helpText, value: inputTargetValue, setValue } = field;
const { errorMessage } = getFieldValidityAndErrorMessage(field);

const onDocumentsChange = useCallback(
(updatedJson: string) => {
setValue(updatedJson);
},
[setValue]
);
const errors = errorMessage ? [errorMessage] : [];

const label =
fieldLabel ??
i18n.translate('xpack.cases.jsonEditorField.defaultLabel', {
defaultMessage: 'JSON Editor',
});

const { convertToJson, setXJson, xJson } = useXJsonMode(inputTargetValue ?? null);

useEffect(() => {
if (!xJson && inputTargetValue) {
setXJson(inputTargetValue);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inputTargetValue]);

return (
<EuiFormRow
data-test-subj={dataTestSubj}
fullWidth
error={errors}
isInvalid={errors && errors.length > 0 && inputTargetValue !== undefined}
label={label}
helpText={helpText}
>
<CodeEditor
languageId={XJsonLang.ID}
options={{
renderValidationDecorations: xJson ? 'on' : 'off', // Disable error underline when empty
lineNumbers: 'on',
fontSize: 14,
minimap: {
enabled: false,
},
scrollBeyondLastLine: false,
folding: true,
wordWrap: 'on',
wrappingIndent: 'indent',
automaticLayout: true,
}}
value={xJson}
width="100%"
height="200px"
data-test-subj={`${paramsProperty}JsonEditor`}
aria-label={ariaLabel}
{...euiCodeEditorProps}
onChange={(xjson: string) => {
setXJson(xjson);
// Keep the documents in sync with the editor content
onDocumentsChange(convertToJson(xjson));
}}
/>
</EuiFormRow>
);
};

JsonEditorField.displayName = 'JsonEditorField';
Loading

0 comments on commit d686a3f

Please sign in to comment.