Skip to content

Commit

Permalink
[SIEM] [DETECTION ENGINE] Details and Edit view for a rule (elastic#5…
Browse files Browse the repository at this point in the history
…3252) (elastic#53698)

* re-structure detection engine + change routing name

* add editing/details feature for a rule
add feature to not edit immutable rule

* review I

* review II

* change constant

* review III
  • Loading branch information
XavierM authored Dec 20, 2019
1 parent 6ac1726 commit 0a57403
Show file tree
Hide file tree
Showing 85 changed files with 2,188 additions and 1,528 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
FetchRulesResponse,
NewRule,
Rule,
FetchRuleProps,
} from './types';
import { throwIfNotOk } from '../../../hooks/api/api';
import { DETECTION_ENGINE_RULES_URL } from '../../../../common/constants';
Expand All @@ -27,7 +28,7 @@ import { DETECTION_ENGINE_RULES_URL } from '../../../../common/constants';
*/
export const addRule = async ({ rule, kbnVersion, signal }: AddRulesProps): Promise<NewRule> => {
const response = await fetch(`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}`, {
method: 'POST',
method: rule.id != null ? 'PUT' : 'POST',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
Expand Down Expand Up @@ -96,6 +97,28 @@ export const fetchRules = async ({
: response.json();
};

/**
* Fetch a Rule by providing a Rule ID
*
* @param id Rule ID's (not rule_id)
* @param kbnVersion current Kibana Version to use for headers
*/
export const fetchRuleById = async ({ id, kbnVersion, signal }: FetchRuleProps): Promise<Rule> => {
const response = await fetch(`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}?id=${id}`, {
method: 'GET',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
signal,
});
await throwIfNotOk(response);
const rule: Rule = await response.json();
return rule;
};

/**
* Enables/Disables provided Rule ID's
*
Expand Down Expand Up @@ -177,11 +200,14 @@ export const duplicateRules = async ({
body: JSON.stringify({
...rule,
name: `${rule.name} [Duplicate]`,
created_at: undefined,
created_by: undefined,
id: undefined,
rule_id: undefined,
updated_at: undefined,
updated_by: undefined,
enabled: rule.enabled,
immutable: false,
}),
})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { isEmpty, get } from 'lodash/fp';
import { isEmpty, isEqual, get } from 'lodash/fp';
import { useEffect, useState, Dispatch, SetStateAction } from 'react';
import { IIndexPattern } from 'src/plugins/data/public';

import { IIndexPattern } from '../../../../../../../../src/plugins/data/public';
import {
BrowserFields,
getBrowserFields,
Expand Down Expand Up @@ -40,6 +40,12 @@ export const useFetchIndexPatterns = (defaultIndices: string[] = []): Return =>
const [isLoading, setIsLoading] = useState(false);
const [, dispatchToaster] = useStateToaster();

useEffect(() => {
if (!isEqual(defaultIndices, indices)) {
setIndices(defaultIndices);
}
}, [defaultIndices, indices]);

useEffect(() => {
let isSubscribed = true;
const abortCtrl = new AbortController();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* 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.
*/

export * from './api';
export * from './fetch_index_patterns';
export * from './persist_rule';
export * from './types';
export * from './use_rule';
export * from './use_rules';
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ export const NewRuleSchema = t.intersection([
t.type({
description: t.string,
enabled: t.boolean,
filters: t.array(t.unknown),
index: t.array(t.string),
interval: t.string,
language: t.string,
name: t.string,
query: t.string,
risk_score: t.number,
severity: t.string,
type: t.union([t.literal('query'), t.literal('saved_query')]),
}),
Expand All @@ -26,7 +28,9 @@ export const NewRuleSchema = t.intersection([
max_signals: t.number,
references: t.array(t.string),
rule_id: t.string,
saved_id: t.string,
tags: t.array(t.string),
threats: t.array(t.unknown),
to: t.string,
updated_by: t.string,
}),
Expand All @@ -41,29 +45,41 @@ export interface AddRulesProps {
signal: AbortSignal;
}

const MetaRule = t.type({
from: t.string,
});

export const RuleSchema = t.intersection([
t.type({
created_at: t.string,
created_by: t.string,
description: t.string,
enabled: t.boolean,
false_positives: t.array(t.string),
filters: t.array(t.unknown),
from: t.string,
id: t.string,
index: t.array(t.string),
interval: t.string,
immutable: t.boolean,
language: t.string,
name: t.string,
max_signals: t.number,
meta: MetaRule,
query: t.string,
references: t.array(t.string),
risk_score: t.number,
rule_id: t.string,
severity: t.string,
type: t.string,
tags: t.array(t.string),
to: t.string,
threats: t.array(t.unknown),
updated_at: t.string,
updated_by: t.string,
}),
t.partial({
false_positives: t.array(t.string),
from: t.string,
max_signals: t.number,
references: t.array(t.string),
tags: t.array(t.string),
to: t.string,
saved_id: t.string,
}),
]);

Expand Down Expand Up @@ -99,6 +115,12 @@ export interface FetchRulesResponse {
data: Rule[];
}

export interface FetchRuleProps {
id: string;
kbnVersion: string;
signal: AbortSignal;
}

export interface EnableRulesProps {
ids: string[];
enabled: boolean;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* 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 { useEffect, useState } from 'react';

import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting';
import { DEFAULT_KBN_VERSION } from '../../../../common/constants';
import { useStateToaster } from '../../../components/toasters';
import { errorToToaster } from '../../../components/ml/api/error_to_toaster';
import { fetchRuleById } from './api';
import * as i18n from './translations';
import { Rule } from './types';

type Return = [boolean, Rule | null];

/**
* Hook for using to get a Rule from the Detection Engine API
*
* @param id desired Rule ID's (not rule_id)
*
*/
export const useRule = (id: string | undefined): Return => {
const [rule, setRule] = useState<Rule | null>(null);
const [loading, setLoading] = useState(true);
const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION);
const [, dispatchToaster] = useStateToaster();

useEffect(() => {
let isSubscribed = true;
const abortCtrl = new AbortController();

async function fetchData(idToFetch: string) {
try {
setLoading(true);
const ruleResponse = await fetchRuleById({
id: idToFetch,
kbnVersion,
signal: abortCtrl.signal,
});

if (isSubscribed) {
setRule(ruleResponse);
}
} catch (error) {
if (isSubscribed) {
setRule(null);
errorToToaster({ title: i18n.RULE_FETCH_FAILURE, error, dispatchToaster });
}
}
if (isSubscribed) {
setLoading(false);
}
}
if (id != null) {
fetchData(id);
}
return () => {
isSubscribed = false;
abortCtrl.abort();
};
}, [id]);

return [loading, rule];
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,46 @@
*/

import chrome from 'ui/chrome';
import { UpdateSignalStatusProps } from './types';

import { throwIfNotOk } from '../../../hooks/api/api';
import { DETECTION_ENGINE_SIGNALS_STATUS_URL } from '../../../../common/constants';
import {
DETECTION_ENGINE_QUERY_SIGNALS_URL,
DETECTION_ENGINE_SIGNALS_STATUS_URL,
} from '../../../../common/constants';
import { QuerySignals, SignalSearchResponse, UpdateSignalStatusProps } from './types';

/**
* Fetch Signals by providing a query
*
* @param query String to match a dsl
* @param kbnVersion current Kibana Version to use for headers
*/
export const fetchQuerySignals = async <Hit, Aggregations>({
query,
kbnVersion,
signal,
}: QuerySignals): Promise<SignalSearchResponse<Hit, Aggregations>> => {
const response = await fetch(`${chrome.getBasePath()}${DETECTION_ENGINE_QUERY_SIGNALS_URL}`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
body: query,
signal,
});
await throwIfNotOk(response);
const signals = await response.json();
return signals;
};

/**
* Update signal status by query
*
* @param query of signals to update
* @param status to update to ('open' / 'closed')
* @param status to update to('open' / 'closed')
* @param kbnVersion current Kibana Version to use for headers
* @param signal to cancel request
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

import { i18n } from '@kbn/i18n';

export const PAGE_TITLE = i18n.translate('xpack.siem.detectionEngine.editRule.pageTitle', {
defaultMessage: 'Edit rule settings',
});
export const SIGNAL_FETCH_FAILURE = i18n.translate(
'xpack.siem.containers.detectionEngine.signals.errorFetchingSignalsDescription',
{
defaultMessage: 'Failed to query signals',
}
);
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,34 @@
* you may not use this file except in compliance with the Elastic License.
*/

export interface QuerySignals {
query: string;
kbnVersion: string;
signal: AbortSignal;
}

export interface SignalsResponse {
took: number;
timeout: boolean;
}

export interface SignalSearchResponse<Hit = {}, Aggregations = undefined> extends SignalsResponse {
_shards: {
total: number;
successful: number;
skipped: number;
failed: number;
};
aggregations?: Aggregations;
hits: {
total: {
value: number;
relation: string;
};
hits: Hit[];
};
}

export interface UpdateSignalStatusProps {
query: object;
status: 'open' | 'closed';
Expand Down
Loading

0 comments on commit 0a57403

Please sign in to comment.