Skip to content

Commit

Permalink
[SIEM] Use import/export API instead of client implementation (#54680)
Browse files Browse the repository at this point in the history
## Summary

This PR switches the Rule Import / Export functionality away from the client-side implementation (that was leveraging the create/read Rule API) to the new explicit `/rules/_import` & `/rules/_export` API introduced in #54332.

Note: This PR also disables the ability to export `immutable` rules.

![image](https://user-images.githubusercontent.com/2946766/72311962-c0963680-3643-11ea-812f-237bc51be7dc.png)


Sample error message:

<img width="800" alt="Screen Shot 2020-01-13 at 20 22 45" src="https://user-images.githubusercontent.com/2946766/72311909-8cbb1100-3643-11ea-94ab-023a5ff56e20.png">


### Checklist

Use ~~strikethroughs~~ to remove checklist items you don't feel are applicable to this PR.

- [X] This was checked for cross-browser compatibility, [including a check against IE11](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility)
- [X] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/master/packages/kbn-i18n/README.md)
- [ ] ~[Documentation](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#writing-documentation) was added for features that require explanation or tutorials~
- [X] [Unit or functional tests](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility) were updated or added to match the most common scenarios
- [ ] ~This was checked for [keyboard-only and screenreader accessibility](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#Accessibility_testing_checklist)~

### For maintainers

- [ ] ~This was checked for breaking API changes and was [labeled appropriately](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#release-notes-process)~
- [ ] ~This includes a feature addition or change that requires a release note and was [labeled appropriately](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#release-notes-process)~
  • Loading branch information
spong authored Jan 14, 2020
1 parent 643912e commit 569b1f6
Show file tree
Hide file tree
Showing 18 changed files with 325 additions and 213 deletions.
28 changes: 25 additions & 3 deletions x-pack/legacy/plugins/siem/public/components/toasters/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { EuiGlobalToastList, EuiGlobalToastListToast as Toast, EuiButton } from '@elastic/eui';
import { EuiButton, EuiGlobalToastList, EuiGlobalToastListToast as Toast } from '@elastic/eui';
import { noop } from 'lodash/fp';
import React, { createContext, Dispatch, useReducer, useContext, useState } from 'react';
import React, { createContext, Dispatch, useContext, useReducer, useState } from 'react';
import styled from 'styled-components';
import uuid from 'uuid';

Expand Down Expand Up @@ -143,7 +143,7 @@ export const displayErrorToast = (
errorTitle: string,
errorMessages: string[],
dispatchToaster: React.Dispatch<ActionToaster>
) => {
): void => {
const toast: AppToast = {
id: uuid.v4(),
title: errorTitle,
Expand All @@ -156,3 +156,25 @@ export const displayErrorToast = (
toast,
});
};

/**
* Displays a success toast for the provided title and message
*
* @param title success message to display in toaster and modal
* @param dispatchToaster provided by useStateToaster()
*/
export const displaySuccessToast = (
title: string,
dispatchToaster: React.Dispatch<ActionToaster>
): void => {
const toast: AppToast = {
id: uuid.v4(),
title,
color: 'success',
iconType: 'check',
};
dispatchToaster({
type: 'addToaster',
toast,
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ import {
Rule,
FetchRuleProps,
BasicFetchProps,
ImportRulesProps,
ExportRulesProps,
RuleError,
ImportRulesResponse,
} from './types';
import { throwIfNotOk } from '../../../hooks/api/api';
import {
DETECTION_ENGINE_RULES_URL,
DETECTION_ENGINE_PREPACKAGED_URL,
} from '../../../../common/constants';
import * as i18n from '../../../pages/detection_engine/rules/translations';

/**
* Add provided Rule
Expand Down Expand Up @@ -223,3 +227,78 @@ export const createPrepackagedRules = async ({ signal }: BasicFetchProps): Promi
await throwIfNotOk(response);
return true;
};

/**
* Imports rules in the same format as exported via the _export API
*
* @param fileToImport File to upload containing rules to import
* @param overwrite whether or not to overwrite rules with the same ruleId
* @param signal AbortSignal for cancelling request
*
* @throws An error if response is not OK
*/
export const importRules = async ({
fileToImport,
overwrite = false,
signal,
}: ImportRulesProps): Promise<ImportRulesResponse> => {
const formData = new FormData();
formData.append('file', fileToImport);

const response = await fetch(
`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}/_import?overwrite=${overwrite}`,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'kbn-xsrf': 'true',
},
body: formData,
signal,
}
);

await throwIfNotOk(response);
return response.json();
};

/**
* Export rules from the server as a file download
*
* @param excludeExportDetails whether or not to exclude additional details at bottom of exported file (defaults to false)
* @param filename of exported rules. Be sure to include `.ndjson` extension! (defaults to localized `rules_export.ndjson`)
* @param ruleIds array of rule_id's (not id!) to export (empty array exports _all_ rules)
* @param signal AbortSignal for cancelling request
*
* @throws An error if response is not OK
*/
export const exportRules = async ({
excludeExportDetails = false,
filename = `${i18n.EXPORT_FILENAME}.ndjson`,
ruleIds = [],
signal,
}: ExportRulesProps): Promise<Blob> => {
const body =
ruleIds.length > 0
? JSON.stringify({ objects: ruleIds.map(rule => ({ rule_id: rule })) })
: undefined;

const response = await fetch(
`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}/_export?exclude_export_details=${excludeExportDetails}&file_name=${encodeURIComponent(
filename
)}`,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-xsrf': 'true',
},
body,
signal,
}
);

await throwIfNotOk(response);
return response.blob();
};
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,30 @@ export interface DuplicateRulesProps {
export interface BasicFetchProps {
signal: AbortSignal;
}

export interface ImportRulesProps {
fileToImport: File;
overwrite?: boolean;
signal: AbortSignal;
}

export interface ImportRulesResponseError {
rule_id: string;
error: {
status_code: number;
message: string;
};
}

export interface ImportRulesResponse {
success: boolean;
success_count: number;
errors: ImportRulesResponseError[];
}

export interface ExportRulesProps {
ruleIds?: string[];
filename?: string;
excludeExportDetails?: boolean;
signal: AbortSignal;
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const getBatchItems = (
<EuiContextMenuItem
key={i18n.BATCH_ACTION_EXPORT_SELECTED}
icon="exportAction"
disabled={containsLoading || selectedState.length === 0}
disabled={containsImmutable || containsLoading || selectedState.length === 0}
onClick={async () => {
closePopover();
await exportRulesAction(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const getActions = (
icon: 'exportAction',
name: i18n.EXPORT_RULE,
onClick: (rowItem: TableData) => exportRulesAction([rowItem.sourceRule], dispatch),
enabled: (rowItem: TableData) => !rowItem.immutable,
},
{
description: i18n.DELETE_RULE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { getBatchItems } from './batch_actions';
import { EuiBasicTableOnChange, TableData } from '../types';
import { allRulesReducer, State } from './reducer';
import * as i18n from '../translations';
import { JSONDownloader } from '../components/json_downloader';
import { RuleDownloader } from '../components/rule_downloader';
import { useStateToaster } from '../../../../components/toasters';

const initialState: State = {
Expand Down Expand Up @@ -150,9 +150,9 @@ export const AllRules = React.memo<{

return (
<>
<JSONDownloader
<RuleDownloader
filename={`${i18n.EXPORT_FILENAME}.ndjson`}
payload={exportPayload}
rules={exportPayload}
onExportComplete={exportCount => {
dispatchToaster({
type: 'addToaster',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ export interface State {
filterOptions: FilterOptions;
refreshToggle: boolean;
tableData: TableData[];
exportPayload?: object[];
exportPayload?: Rule[];
}

export type Action =
| { type: 'refresh' }
| { type: 'loading'; isLoading: boolean }
| { type: 'deleteRules'; rules: Rule[] }
| { type: 'duplicate'; rule: Rule }
| { type: 'setExportPayload'; exportPayload?: object[] }
| { type: 'setExportPayload'; exportPayload?: Rule[] }
| { type: 'setSelected'; selectedItems: TableData[] }
| { type: 'updateLoading'; ids: string[]; isLoading: boolean }
| { type: 'updateRules'; rules: Rule[]; appendRuleId?: string; pagination?: PaginationOptions }
Expand Down Expand Up @@ -143,7 +143,7 @@ export const allRulesReducer = (state: State, action: Action): State => {
case 'setExportPayload': {
return {
...state,
exportPayload: action.exportPayload,
exportPayload: [...(action.exportPayload ?? [])],
};
}
default:
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 569b1f6

Please sign in to comment.