Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
61cc974
re-Added Misconfiguration Preview Component as well the test
animehart Aug 28, 2024
89eb0e7
[CI] Auto-commit changed files from 'node scripts/notice'
kibanamachine Aug 28, 2024
199b8d0
[CI] Auto-commit changed files from 'node scripts/lint_ts_projects --…
kibanamachine Aug 28, 2024
0aa00d8
added jest config file
animehart Aug 28, 2024
a683d21
will include test later
animehart Aug 29, 2024
750fa9b
addressing comments from original PR about convention on setting size…
animehart Aug 29, 2024
0423a29
addressing pr comments
animehart Aug 30, 2024
a31584c
add more cypress stuff
animehart Aug 30, 2024
1d6b486
fix cypress log message
animehart Aug 30, 2024
f5656f6
update type
animehart Aug 30, 2024
574f2c4
update cypress test to be more stable
animehart Aug 30, 2024
292a222
[CI] Auto-commit changed files from 'node scripts/lint_ts_projects --…
kibanamachine Aug 30, 2024
62379d0
Merge branch 'main' into misconfiguration-preview-refactor-phase-4-im…
animehart Aug 30, 2024
a303ddf
more PR Comments, renaming file name and fixes
animehart Aug 30, 2024
733111e
Merge branch 'misconfiguration-preview-refactor-phase-4-implementatio…
animehart Aug 30, 2024
cae20ab
removed Cypress test for now, because there are multiple steps that n…
animehart Aug 30, 2024
3ddc7b7
fix tsconfig
animehart Aug 30, 2024
def06a5
Merge branch 'main' into misconfiguration-preview-refactor-phase-4-im…
animehart Aug 30, 2024
fb41b2f
addressing Max comments: removing useless field and renaming weird fi…
animehart Sep 3, 2024
60bc1bf
Merge branch 'misconfiguration-preview-refactor-phase-4-implementatio…
animehart Sep 3, 2024
6609c40
Merge branch 'main' into misconfiguration-preview-refactor-phase-4-im…
animehart Sep 3, 2024
3d5b126
addressing pr comments
animehart Sep 4, 2024
1f95ac2
Merge branch 'misconfiguration-preview-refactor-phase-4-implementatio…
animehart Sep 4, 2024
842c829
Merge branch 'main' into misconfiguration-preview-refactor-phase-4-im…
animehart Sep 4, 2024
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
6 changes: 5 additions & 1 deletion x-pack/packages/kbn-cloud-security-posture-common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,8 @@ export type {
export type { CspFinding } from './types/findings';
export type { BenchmarksCisId } from './types/benchmark';
export * from './constants';
export { extractErrorMessage, buildMutedRulesFilter } from './utils/helpers';
export {
extractErrorMessage,
buildMutedRulesFilter,
buildMisconfigurationPreviewQuery,
} from './utils/helpers';
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
* 2.0.
*/

import { extractErrorMessage, defaultErrorMessage, buildMutedRulesFilter } from './helpers';
import {
extractErrorMessage,
defaultErrorMessage,
buildMutedRulesFilter,
buildMisconfigurationPreviewQuery,
} from './helpers';

const fallbackMessage = 'thisIsAFallBackMessage';

Expand Down Expand Up @@ -138,4 +143,49 @@ describe('test helper methods', () => {
expect(buildMutedRulesFilter(rulesStates)).toEqual(expectedQuery);
});
});

describe('buildMisconfigurationPreviewQuery Test', () => {
it('should return the correct query when given field and query', () => {
const field = 'host.name';
const query = 'exampleHost';
const expectedQuery = {
bool: {
must: [],
filter: [
{
bool: {
should: [{ term: { 'host.name': { value: 'exampleHost' } } }],
minimum_should_match: 1,
},
},
],
should: [],
must_not: [],
},
};

expect(buildMisconfigurationPreviewQuery(field, query)).toEqual(expectedQuery);
});

it('should return the correct query when given field and empty query', () => {
const field = 'host.name';
const expectedQuery = {
bool: {
must: [],
filter: [
{
bool: {
should: [{ term: { 'host.name': { value: '' } } }],
minimum_should_match: 1,
},
},
],
should: [],
must_not: [],
},
};

expect(buildMisconfigurationPreviewQuery(field)).toEqual(expectedQuery);
});
});
});
18 changes: 18 additions & 0 deletions x-pack/packages/kbn-cloud-security-posture-common/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,21 @@ export const buildMutedRulesFilter = (

return mutedRulesFilterQuery;
};

export const buildMisconfigurationPreviewQuery = (field: string, queryValue?: string) => {
Comment thread
maxcold marked this conversation as resolved.
Outdated
return {
bool: {
must: [],
Comment thread
maxcold marked this conversation as resolved.
Outdated
filter: [
{
bool: {
should: [{ term: { [field]: { value: `${queryValue || ''}` } } }],
minimum_should_match: 1,
},
},
],
should: [],
must_not: [],
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import { lastValueFrom } from 'rxjs';
import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CDR_MISCONFIGURATIONS_INDEX_PATTERN,
LATEST_FINDINGS_RETENTION_POLICY,
MAX_FINDINGS_TO_LOAD,
CspFinding,
} from '@kbn/cloud-security-posture-common';
import type { CspBenchmarkRulesStates } from '@kbn/cloud-security-posture-common/schema/rules/latest';
import { buildMutedRulesFilter } from '@kbn/cloud-security-posture-common';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { CoreStart } from '@kbn/core/public';
import { showErrorToast } from '../..';
import type { CspClientPluginStartDeps } from '../../type';
import type { FindingsBaseEsQuery } from '../../type';
import { useGetCspBenchmarkRulesStatesApi } from './use_get_benchmark_rules_state_api';

interface UseFindingsOptions extends FindingsBaseEsQuery {
sort: string[][];
enabled: boolean;
pageSize: number;
}

type LatestFindingsRequest = IKibanaSearchRequest<estypes.SearchRequest>;
type LatestFindingsResponse = IKibanaSearchResponse<
estypes.SearchResponse<CspFinding, FindingsAggs>
>;

interface FindingsAggs {
count: estypes.AggregationsMultiBucketAggregateBase<estypes.AggregationsStringRareTermsBucketKeys>;
}

export const getFindingsCountAggQueryMisconfigurationPreview = () => ({
count: {
filters: {
other_bucket_key: 'other_messages',
Comment thread
maxcold marked this conversation as resolved.
Outdated
filters: {
passed: { match: { 'result.evaluation': 'passed' } },
failed: { match: { 'result.evaluation': 'failed' } },
},
},
},
});

export const getMisconfigurationAggregationCount = (
buckets: Array<estypes.AggregationsStringRareTermsBucketKeys | undefined>
) => {
const passed = buckets.find((bucket) => bucket?.key === 'passed');
const failed = buckets.find((bucket) => bucket?.key === 'failed');
const noStatus = buckets.find((bucket) => bucket?.key === 'other_messages');

return {
passed: passed?.doc_count || 0,
failed: failed?.doc_count || 0,
no_status: noStatus?.doc_count || 0,
};
};

export const getFindingsQuery = (
{ query, sort }: UseFindingsOptions,
rulesStates: CspBenchmarkRulesStates,
pageParam: any
Comment thread
animehart marked this conversation as resolved.
Outdated
) => {
const mutedRulesFilterQuery = buildMutedRulesFilter(rulesStates);

return {
index: CDR_MISCONFIGURATIONS_INDEX_PATTERN,
size: MAX_FINDINGS_TO_LOAD,
Comment thread
maxcold marked this conversation as resolved.
Outdated
aggs: getFindingsCountAggQueryMisconfigurationPreview(),
ignore_unavailable: false,
query: {
...query,
bool: {
...query?.bool,
filter: [
...(query?.bool?.filter ?? []),
{
range: {
'@timestamp': {
gte: `now-${LATEST_FINDINGS_RETENTION_POLICY}`,
lte: 'now',
},
},
},
],
must_not: [...(query?.bool?.must_not ?? []), ...mutedRulesFilterQuery],
},
},
...(pageParam ? { from: pageParam } : {}),
};
};
Comment thread
animehart marked this conversation as resolved.
Outdated

export const useMisconfigurationPreview = (options: UseFindingsOptions) => {
const {
data,
notifications: { toasts },
} = useKibana<CoreStart & CspClientPluginStartDeps>().services;
const { data: rulesStates } = useGetCspBenchmarkRulesStatesApi();

return useQuery(
['csp_findings', { params: options }, rulesStates],
Comment thread
maxcold marked this conversation as resolved.
Outdated
async ({ pageParam }) => {
const {
rawResponse: { aggregations },
} = await lastValueFrom(
data.search.search<LatestFindingsRequest, LatestFindingsResponse>({
params: getFindingsQuery(options, rulesStates!, pageParam),
})
);
if (!aggregations) throw new Error('expected aggregations to be defined');

return {
count: getMisconfigurationAggregationCount(
Object.entries(aggregations.count.buckets).map(([key, value]) => ({
key,
doc_count: value.doc_count || 0,
}))
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we already have a getMisconfigurationAggregationCount function, it's better to have it handle the object parsing so the function is easier to consume:

return {
    count: getMisconfigurationAggregationCount(aggregations.count.buckets)
};

};
},
{
enabled: options.enabled && !!rulesStates,
keepPreviousData: true,
onError: (err: Error) => showErrorToast(toasts, err),
}
);
};
1 change: 1 addition & 0 deletions x-pack/packages/kbn-cloud-security-posture/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@
"@kbn/kibana-react-plugin",
"@kbn/cloud-security-posture-common",
"@kbn/i18n",
"@kbn/search-types",
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* 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 { EuiAccordion, EuiSpacer, EuiTitle, useEuiTheme } from '@elastic/eui';

import React from 'react';
import { css } from '@emotion/react';
import { FormattedMessage } from '@kbn/i18n-react';
import { useCspSetupStatusApi } from '@kbn/cloud-security-posture/src/hooks/use_csp_setup_status_api';
import { MisconfigurationsOverview } from './misconfiguration/misconfiguration_overview';

export const EntityInsight = <T,>({ hostName }: { hostName: string }) => {
const { euiTheme } = useEuiTheme();
const getSetupStatus = useCspSetupStatusApi();
const hasMisconfigurationFindings = getSetupStatus.data?.hasMisconfigurationsFindings;

return (
<>
{hasMisconfigurationFindings && (
<EuiAccordion
initialIsOpen={true}
id="observedEntity-accordion"
data-test-subj="entityInsightTestSubj"
buttonProps={{
'data-test-subj': 'observedEntity-accordion-button',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better avoid using existing identifiers:

Suggested change
id="observedEntity-accordion"
data-test-subj="entityInsightTestSubj"
buttonProps={{
'data-test-subj': 'observedEntity-accordion-button',
id="entityInsight-accordion"
data-test-subj="entityInsightTestSubj"
buttonProps={{
'data-test-subj': 'entityInsight-accordion-button',

css: css`
color: ${euiTheme.colors.primary};
`,
}}
buttonContent={
<EuiTitle size="xs">
<h3>
<FormattedMessage
id="xpack.securitySolution.flyout.entityDetails.insightsTitle"
defaultMessage="Insights"
/>
</h3>
</EuiTitle>
}
css={css`
.euiAccordion__optionalAction {
margin-left: auto;
}
Comment thread
animehart marked this conversation as resolved.
Outdated
`}
>
<EuiSpacer size="m" />
<MisconfigurationsOverview hostName={hostName} />
<EuiSpacer size="m" />
</EuiAccordion>
)}
</>
);
};
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.
*/

// Add stuff here
import { TestProviders } from '../../../common/mock';
import { render } from '@testing-library/react';
import React from 'react';
import { MisconfigurationsOverview } from './misconfiguration_overview';

const mockProps = {
hostName: 'testContextID',
};

describe('MisconfigurationsOverview', () => {
it('renders', () => {
const { queryByTestId } = render(<MisconfigurationsOverview {...mockProps} />, {
wrapper: TestProviders,
});
expect(
queryByTestId('securitySolutionFlyoutInsightsMisconfigurationsContent')
).toBeInTheDocument();
expect(queryByTestId('noFindingsDataTestSubj')).toBeInTheDocument();
});
});
Loading