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

[7.x] [SIEM] [DETECTION ENGINE] Details and Edit view for a rule (#53252) #53698

Merged
merged 1 commit into from
Dec 20, 2019
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -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