Skip to content

Commit

Permalink
add utils for mapping field conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
Omolola-Akinleye committed Nov 21, 2023
1 parent eaebc40 commit 58485f1
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types';

export const benchmarkScoreMapping: MappingTypeMapping = {
dynamic: false, // TODO: before commit we need to verify this is the correct move
properties: {
'@timestamp': {
type: 'date',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* 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.
*/

export const DELIMITER = ';';
export const MAPPING_VERSION_DELIMITER = '_';
export const DOC_FIELD_VERSION_DELIMITER = '.';

export const toBenchmarkDocFieldKey = (benchmarkId: string, benchmarkVersion: string) => {
if (benchmarkVersion.includes(MAPPING_VERSION_DELIMITER))
return `${benchmarkId}${DELIMITER}${benchmarkVersion.replaceAll(
`${MAPPING_VERSION_DELIMITER}`,
DOC_FIELD_VERSION_DELIMITER
)}`;
return `${benchmarkId}${DELIMITER}${benchmarkVersion}`;
};

export const toBenchmarkMappingFieldKey = (benchmarkId: string, benchmarkVersion: string) => {
if (benchmarkVersion.includes(DOC_FIELD_VERSION_DELIMITER))
return `${benchmarkId}${DELIMITER}${benchmarkVersion.replaceAll(
`${DOC_FIELD_VERSION_DELIMITER}`,
MAPPING_VERSION_DELIMITER
)}`;
return `${benchmarkId}${DELIMITER}${benchmarkVersion}`;
};
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { getStats } from './get_stats';
import { CspRouter } from '../../types';
import { getTrends, Trends } from './get_trends';
import { BenchmarkWithoutTrend, getBenchmarks } from './get_benchmarks';
import { toBenchmarkDocFieldKey } from '../../lib/mapping_field_util';

export interface KeyDocCount<TKey = string> {
key: TKey;
Expand All @@ -40,12 +41,16 @@ const getClustersTrends = (clustersWithoutTrends: ClusterWithoutTrend[], trends:
const getBenchmarksTrends = (benchmarksWithoutTrends: BenchmarkWithoutTrend[], trends: Trends) =>
benchmarksWithoutTrends.map((benchmark) => ({
...benchmark,
trend: trends
.map(({ timestamp, benchmarks: benchmarksTrendData }) => ({
trend: trends.map(({ timestamp, benchmarks: benchmarksTrendData }) => {
const benchmarkIdVersion = toBenchmarkDocFieldKey(
benchmark.meta.benchmarkId,
benchmark.meta.benchmarkName
);
return {
timestamp,
...benchmarksTrendData[`${benchmark.meta.benchmarkId}_${benchmark.meta.benchmarkVersion}`],
}))
.filter((doc) => Object.keys(doc).length > 1),
...benchmarksTrendData[benchmarkIdVersion],
};
}),
}));

const getSummaryTrend = (trends: Trends) =>
Expand Down Expand Up @@ -111,7 +116,6 @@ export const defineGetComplianceDashboardRoute = (router: CspRouter) =>

const clusters = getClustersTrends(clustersWithoutTrends, trends);
const benchmarks = getBenchmarksTrends(benchmarksWithoutTrends, trends);

const trend = getSummaryTrend(trends);

const body: ComplianceDashboardData = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ElasticsearchClient } from '@kbn/core/server';
import { calculatePostureScore } from '../../../common/utils/helpers';
import { BENCHMARK_SCORE_INDEX_DEFAULT_NS } from '../../../common/constants';
import type { PosturePolicyTemplate, Stats } from '../../../common/types';
import { toBenchmarkDocFieldKey } from '../../lib/mapping_field_util';

export interface ScoreTrendDoc {
'@timestamp': string;
Expand Down Expand Up @@ -45,8 +46,8 @@ export type Trends = Array<{

export const getTrendsQuery = (policyTemplate: PosturePolicyTemplate) => ({
index: BENCHMARK_SCORE_INDEX_DEFAULT_NS,
// large number that should be sufficient for 24 hours considering we write to the score index every 5 minutes
size: 999,
// Amount of samples of the last 24 hours (accounting that we take a sample every 5 minutes)
size: (24 * 60) / 5,
sort: '@timestamp:desc',
query: {
bool: {
Expand Down Expand Up @@ -88,9 +89,9 @@ export const getTrendsFromQueryResult = (scoreTrendDocs: ScoreTrendDoc[]): Trend
? Object.fromEntries(
Object.entries(data.score_by_benchmark_id).flatMap(([benchmarkId, benchmark]) =>
Object.entries(benchmark).map(([benchmarkVersion, benchmarkStats]) => {
const benchmarkVersionFieldFormat = benchmarkVersion.split('_').join('.');
const benchmarkIdVersion = toBenchmarkDocFieldKey(benchmarkId, benchmarkVersion);
return [
`${benchmarkId}_${benchmarkVersionFieldFormat}`,
benchmarkIdVersion,
{
totalFindings: benchmarkStats.total_findings,
totalFailed: benchmarkStats.failed_findings,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
type LatestTaskStateSchema,
type TaskHealthStatus,
} from './task_state';
import { toBenchmarkMappingFieldKey } from '../lib/mapping_field_util';

const CSPM_FINDINGS_STATS_TASK_ID = 'cloud_security_posture-findings_stats';
const CSPM_FINDINGS_STATS_TASK_TYPE = 'cloud_security_posture-stats_task';
Expand Down Expand Up @@ -294,9 +295,12 @@ const getFindingsScoresDocIndexingPromises = (
const benchmarkId = benchmarkIdBucket.key;
const benchmarkVersions = Object.fromEntries(
benchmarkIdBucket.benchmark_versions.buckets.map((benchmarkVersionBucket) => {
const benchmarkVersion = benchmarkVersionBucket.key.split('.').join('_');
const benchmarkIdVersion = toBenchmarkMappingFieldKey(
benchmarkId,
benchmarkVersionBucket.key
);
return [
benchmarkVersion,
benchmarkIdVersion,
{
total_findings: benchmarkVersionBucket.total_findings.value,
passed_findings: benchmarkVersionBucket.passed_findings.doc_count,
Expand Down

0 comments on commit 58485f1

Please sign in to comment.