Skip to content

Commit

Permalink
Add utility function to check if index exist
Browse files Browse the repository at this point in the history
  • Loading branch information
nkhristinin committed Dec 21, 2023
1 parent 35a9be3 commit c296a4c
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,10 @@ import {
ALERT_USER_CRITICALITY,
} from '../../../../../../../common/field_maps/field_names';
import { createSingleFieldMatchEnrichment } from '../create_single_field_match_enrichment';
import type {
CreateCriticalityEnrichment,
DoesAssetCriticalityAvailable,
CreateEnrichmentFunction,
} from '../types';
import type { CreateCriticalityEnrichment, CreateEnrichmentFunction } from '../types';
import { getFieldValue } from '../utils/events';
import { getAssetCriticalityIndex } from '../../../../../../../common/entity_analytics/asset_criticality';

export const doesAssetCriticalityIndexExist: DoesAssetCriticalityAvailable = async ({
spaceId,
services,
}) => {
const isAssetCriticalityIndexExist =
await services.scopedClusterClient.asInternalUser.indices.exists({
index: getAssetCriticalityIndex(spaceId),
});

return isAssetCriticalityIndexExist;
};

const enrichmentResponseFields = ['id_value', 'criticality_level'];

const getExtraFiltersForEnrichment = (field: string) => [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,9 @@ import { cloneDeep } from 'lodash';
import { getHostRiskIndex } from '../../../../../../../common/search_strategy/security_solution/risk_score/common';
import { RiskScoreFields } from '../../../../../../../common/search_strategy/security_solution/risk_score/all';
import { createSingleFieldMatchEnrichment } from '../create_single_field_match_enrichment';
import type { CreateRiskEnrichment, GetIsRiskScoreAvailable } from '../types';
import type { CreateRiskEnrichment } from '../types';
import { getFieldValue } from '../utils/events';

export const getIsHostRiskScoreAvailable: GetIsRiskScoreAvailable = async ({
spaceId,
services,
isNewRiskScoreModuleInstalled,
}) => {
const isHostRiskScoreIndexExist = await services.scopedClusterClient.asCurrentUser.indices.exists(
{
index: getHostRiskIndex(spaceId, true, isNewRiskScoreModuleInstalled),
}
);

return isHostRiskScoreIndexExist;
};

export const createHostRiskEnrichments: CreateRiskEnrichment = async ({
services,
logger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,9 @@ import { cloneDeep } from 'lodash';
import { getUserRiskIndex } from '../../../../../../../common/search_strategy/security_solution/risk_score/common';
import { RiskScoreFields } from '../../../../../../../common/search_strategy/security_solution/risk_score/all';
import { createSingleFieldMatchEnrichment } from '../create_single_field_match_enrichment';
import type { CreateRiskEnrichment, GetIsRiskScoreAvailable } from '../types';
import type { CreateRiskEnrichment } from '../types';
import { getFieldValue } from '../utils/events';

export const getIsUserRiskScoreAvailable: GetIsRiskScoreAvailable = async ({
services,
spaceId,
isNewRiskScoreModuleInstalled,
}) => {
const isUserRiskScoreIndexExist = await services.scopedClusterClient.asCurrentUser.indices.exists(
{
index: getUserRiskIndex(spaceId, true, isNewRiskScoreModuleInstalled),
}
);

return isUserRiskScoreIndexExist;
};

export const createUserRiskEnrichments: CreateRiskEnrichment = async ({
services,
logger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,20 @@ import { enrichEvents } from '.';
import { searchEnrichments } from './search_enrichments';
import { ruleExecutionLogMock } from '../../../rule_monitoring/mocks';
import { createAlert } from './__mocks__/alerts';
import { getIsHostRiskScoreAvailable } from './enrichment_by_type/host_risk';
import { getIsUserRiskScoreAvailable } from './enrichment_by_type/user_risk';
import { doesAssetCriticalityIndexExist } from './enrichment_by_type/asset_criticality';

import { isIndexExist } from './utils/isIndexExist';

import { allowedExperimentalValues } from '../../../../../../common';

jest.mock('./search_enrichments', () => ({
searchEnrichments: jest.fn(),
}));
const mockSearchEnrichments = searchEnrichments as jest.Mock;

jest.mock('./enrichment_by_type/host_risk', () => ({
...jest.requireActual('./enrichment_by_type/host_risk'),
getIsHostRiskScoreAvailable: jest.fn(),
}));
const mockGetIsHostRiskScoreAvailable = getIsHostRiskScoreAvailable as jest.Mock;

jest.mock('./enrichment_by_type/user_risk', () => ({
...jest.requireActual('./enrichment_by_type/user_risk'),
getIsUserRiskScoreAvailable: jest.fn(),
jest.mock('./utils/isIndexExist', () => ({
isIndexExist: jest.fn(),
}));

jest.mock('./enrichment_by_type/asset_criticality', () => ({
...jest.requireActual('./enrichment_by_type/asset_criticality'),
doesAssetCriticalityIndexExist: jest.fn(),
}));

const mockGetIsUserRiskScoreAvailable = getIsUserRiskScoreAvailable as jest.Mock;
const mockDoesAssetCriticalityIndexExist = doesAssetCriticalityIndexExist as jest.Mock;
const mockIsIndexExist = isIndexExist as jest.Mock;

const hostEnrichmentResponse = [
{
Expand Down Expand Up @@ -109,15 +95,12 @@ describe('enrichEvents', () => {
alertServices = alertsMock.createRuleExecutorServices();
});
afterEach(() => {
mockGetIsUserRiskScoreAvailable.mockClear();
mockGetIsUserRiskScoreAvailable.mockClear();
mockDoesAssetCriticalityIndexExist.mockClear();
mockIsIndexExist.mockClear();
});

it('return the same events, if risk indexes are not available', async () => {
mockSearchEnrichments.mockImplementation(() => []);
mockGetIsUserRiskScoreAvailable.mockImplementation(() => false);
mockGetIsHostRiskScoreAvailable.mockImplementation(() => false);
mockIsIndexExist.mockImplementation(() => false);
const events = [
createAlert('1', createEntity('host', 'host name')),
createAlert('2', createEntity('user', 'user name')),
Expand All @@ -134,8 +117,7 @@ describe('enrichEvents', () => {

it('return the same events, if there no fields', async () => {
mockSearchEnrichments.mockImplementation(() => []);
mockGetIsUserRiskScoreAvailable.mockImplementation(() => true);
mockGetIsHostRiskScoreAvailable.mockImplementation(() => true);
mockIsIndexExist.mockImplementation(() => true);
const events = [createAlert('1'), createAlert('2')];
const enrichedEvents = await enrichEvents({
logger: ruleExecutionLogger,
Expand All @@ -151,8 +133,7 @@ describe('enrichEvents', () => {
mockSearchEnrichments
.mockReturnValueOnce(hostEnrichmentResponse)
.mockReturnValueOnce(userEnrichmentResponse);
mockGetIsUserRiskScoreAvailable.mockImplementation(() => true);
mockGetIsHostRiskScoreAvailable.mockImplementation(() => true);
mockIsIndexExist.mockImplementation(() => true);

const enrichedEvents = await enrichEvents({
logger: ruleExecutionLogger,
Expand Down Expand Up @@ -201,9 +182,12 @@ describe('enrichEvents', () => {
.mockReturnValueOnce(assetCriticalityUserResponse)
.mockReturnValueOnce(assetCriticalityHostResponse);

mockGetIsUserRiskScoreAvailable.mockImplementation(() => false);
mockGetIsHostRiskScoreAvailable.mockImplementation(() => false);
mockDoesAssetCriticalityIndexExist.mockImplementation(() => true);
// disable risk score enrichments
mockIsIndexExist.mockImplementationOnce(() => false);
mockIsIndexExist.mockImplementationOnce(() => false);
mockIsIndexExist.mockImplementationOnce(() => false);
// enable for asset criticality
mockIsIndexExist.mockImplementation(() => true);

const enrichedEvents = await enrichEvents({
logger: ruleExecutionLogger,
Expand Down Expand Up @@ -242,8 +226,8 @@ describe('enrichEvents', () => {
throw new Error('1');
})
.mockImplementationOnce(() => userEnrichmentResponse);
mockGetIsUserRiskScoreAvailable.mockImplementation(() => true);
mockGetIsHostRiskScoreAvailable.mockImplementation(() => true);
mockIsIndexExist.mockImplementation(() => true);
mockIsIndexExist.mockImplementation(() => true);

const enrichedEvents = await enrichEvents({
logger: ruleExecutionLogger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,26 @@
* 2.0.
*/

import {
createHostRiskEnrichments,
getIsHostRiskScoreAvailable,
} from './enrichment_by_type/host_risk';
import { createHostRiskEnrichments } from './enrichment_by_type/host_risk';

import {
createUserRiskEnrichments,
getIsUserRiskScoreAvailable,
} from './enrichment_by_type/user_risk';
import { createUserRiskEnrichments } from './enrichment_by_type/user_risk';

import {
createHostAssetCriticalityEnrichments,
createUserAssetCriticalityEnrichments,
doesAssetCriticalityIndexExist,
} from './enrichment_by_type/asset_criticality';

import { getAssetCriticalityIndex } from '../../../../../../common/entity_analytics/asset_criticality';
import type {
EnrichEventsFunction,
EventsMapByEnrichments,
CreateEnrichEventsFunction,
} from './types';
import { applyEnrichmentsToEvents } from './utils/transforms';
import { isIndexExist } from './utils/isIndexExist';
import {
getHostRiskIndex,
getUserRiskIndex,
} from '../../../../../../common/search_strategy/security_solution/risk_score/common';

export const enrichEvents: EnrichEventsFunction = async ({
services,
Expand All @@ -45,16 +43,21 @@ export const enrichEvents: EnrichEventsFunction = async ({

let isNewRiskScoreModuleInstalled = false;
if (isNewRiskScoreModuleAvailable) {
isNewRiskScoreModuleInstalled = await getIsHostRiskScoreAvailable({
spaceId,
isNewRiskScoreModuleInstalled = await isIndexExist({
services,
isNewRiskScoreModuleInstalled: true,
index: getHostRiskIndex(spaceId, true, true),
});
}

const [isHostRiskScoreIndexExist, isUserRiskScoreIndexExist] = await Promise.all([
getIsHostRiskScoreAvailable({ spaceId, services, isNewRiskScoreModuleInstalled }),
getIsUserRiskScoreAvailable({ spaceId, services, isNewRiskScoreModuleInstalled }),
isIndexExist({
services,
index: getHostRiskIndex(spaceId, true, isNewRiskScoreModuleInstalled),
}),
isIndexExist({
services,
index: getUserRiskIndex(spaceId, true, isNewRiskScoreModuleInstalled),
}),
]);

if (isHostRiskScoreIndexExist) {
Expand Down Expand Up @@ -82,9 +85,9 @@ export const enrichEvents: EnrichEventsFunction = async ({
}

if (isAssetCriticalityEnabled) {
const assetCriticalityIndexExist = await doesAssetCriticalityIndexExist({
spaceId,
const assetCriticalityIndexExist = await isIndexExist({
services,
index: getAssetCriticalityIndex(spaceId),
});
if (assetCriticalityIndexExist) {
enrichments.push(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,7 @@ export type GetIsRiskScoreAvailable = (params: {
isNewRiskScoreModuleInstalled: boolean;
}) => Promise<boolean>;

export type DoesAssetCriticalityAvailable = (params: {
spaceId: string;
services: RuleServices;
}) => Promise<boolean>;
export type IsIndexExist = (params: { services: RuleServices; index: string }) => Promise<boolean>;

export type CreateRiskEnrichment = <T extends BaseFieldsLatest>(
params: BasedEnrichParamters<T> & {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* 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 type { IsIndexExist } from '../types';

export const isIndexExist: IsIndexExist = async ({ services, index }) => {
const isAssetCriticalityIndexExist =
await services.scopedClusterClient.asInternalUser.indices.exists({
index,
});

return isAssetCriticalityIndexExist;
};

0 comments on commit c296a4c

Please sign in to comment.