[8.12] [Security Solution] Only query security alerts with the current user (#175903) (#176395)

# Backport

This will backport the following commits from `main` to `8.12`:
- [[Security Solution] Only query security alerts with the current user
(#175903)](https://github.com/elastic/kibana/pull/175903)

<!--- Backport version: 8.9.8 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Pablo
Machado","email":"pablo.nevesmachado@elastic.co"},"sourceCommit":{"committedDate":"2024-02-02T11:24:34Z","message":"[Security
Solution] Only query security alerts with the current user
(#175903)\n\n## Summary\r\n\r\nFix risk score query to only search
security alerts with the
current\r\nuser.\r\n\r\n---------\r\n\r\nCo-authored-by: Kibana Machine
<42973632+kibanamachine@users.noreply.github.com>","sha":"5b5df2e58b6dc0a6e3e734688b8c2591f42312c4","branchLabelMapping":{"^v8.13.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["bug","release_note:fix","impact:low","backport
missing","Team: SecuritySolution","v8.12.1","Team:Entity
Analytics","v8.13.0"],"number":175903,"url":"https://github.com/elastic/kibana/pull/175903","mergeCommit":{"message":"[Security
Solution] Only query security alerts with the current user
(#175903)\n\n## Summary\r\n\r\nFix risk score query to only search
security alerts with the
current\r\nuser.\r\n\r\n---------\r\n\r\nCo-authored-by: Kibana Machine
<42973632+kibanamachine@users.noreply.github.com>","sha":"5b5df2e58b6dc0a6e3e734688b8c2591f42312c4"}},"sourceBranch":"main","suggestedTargetBranches":["8.12"],"targetPullRequestStates":[{"branch":"8.12","label":"v8.12.1","labelRegex":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v8.13.0","labelRegex":"^v8.13.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/175903","number":175903,"mergeCommit":{"message":"[Security
Solution] Only query security alerts with the current user
(#175903)\n\n## Summary\r\n\r\nFix risk score query to only search
security alerts with the
current\r\nuser.\r\n\r\n---------\r\n\r\nCo-authored-by: Kibana Machine
<42973632+kibanamachine@users.noreply.github.com>","sha":"5b5df2e58b6dc0a6e3e734688b8c2591f42312c4"}}]}]
BACKPORT-->
This commit is contained in:
Pablo Machado 2024-02-07 15:52:15 +01:00 committed by GitHub
parent 0be4e96091
commit 5a4ad2651f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 25 additions and 11 deletions

View file

@ -59,19 +59,21 @@ export const mockSearchStrategyResponse: IEsSearchResponse<HostRiskScore> = {
};
const searchMock = jest.fn();
const ALERT_INDEX_PATTERN = '.test-alerts-security.alerts';
const TEST_SPACE_ID = 'test-default';
const mockDeps = {
esClient: {} as IScopedClusterClient,
ruleDataClient: {
...(ruleRegistryMocks.createRuleDataClient('.alerts-security.alerts') as IRuleDataClient),
getReader: jest.fn((_options?: { namespace?: string }) => ({
esClient: {
asCurrentUser: {
search: searchMock,
getDynamicIndexPattern: jest.fn(),
})),
},
} as unknown as IScopedClusterClient,
ruleDataClient: {
...(ruleRegistryMocks.createRuleDataClient(ALERT_INDEX_PATTERN) as IRuleDataClient),
},
savedObjectsClient: {} as SavedObjectsClientContract,
endpointContext: createMockEndpointAppContext(),
request: {} as KibanaRequest,
spaceId: TEST_SPACE_ID,
};
export const mockOptions: RiskScoreRequestOptions = {
@ -105,6 +107,12 @@ describe('buildRiskScoreQuery search strategy', () => {
expect(get('data[0].alertsCount', result)).toBeUndefined();
});
test('should search alerts on the alerts index pattern', async () => {
await riskScore.parse(mockOptions, mockSearchStrategyResponse, mockDeps);
expect(searchMock.mock.calls[0][0].index).toEqual(`${ALERT_INDEX_PATTERN}${TEST_SPACE_ID}`);
});
test('should enhance data with alerts count', async () => {
const alertsCunt = 9999;
searchMock.mockReturnValue({

View file

@ -9,6 +9,7 @@ import type { IEsSearchResponse, SearchRequest, TimeRange } from '@kbn/data-plug
import { get, getOr } from 'lodash/fp';
import type { IRuleDataClient } from '@kbn/rule-registry-plugin/server';
import type { AggregationsMinAggregate } from '@elastic/elasticsearch/lib/api/types';
import type { IScopedClusterClient } from '@kbn/core-elasticsearch-server';
import type { SecuritySolutionFactory } from '../../types';
import type {
RiskQueries,
@ -37,6 +38,7 @@ export const riskScore: SecuritySolutionFactory<
response: IEsSearchResponse,
deps?: {
spaceId?: string;
esClient: IScopedClusterClient;
ruleDataClient?: IRuleDataClient | null;
}
) => {
@ -56,6 +58,7 @@ export const riskScore: SecuritySolutionFactory<
data,
names,
nameField,
deps.esClient,
deps.ruleDataClient,
deps.spaceId,
options.alertsTimerange
@ -79,13 +82,14 @@ async function enhanceData(
data: Array<HostRiskScore | UserRiskScore>,
names: string[],
nameField: string,
esClient: IScopedClusterClient,
ruleDataClient?: IRuleDataClient | null,
spaceId?: string,
timerange?: TimeRange
): Promise<Array<HostRiskScore | UserRiskScore>> {
const ruleDataReader = ruleDataClient?.getReader({ namespace: spaceId });
const query = getAlertsQueryForEntity(names, nameField, timerange);
const response = await ruleDataReader?.search(query);
const indexPattern = ruleDataClient?.indexNameWithNamespace(spaceId ?? 'default');
const query = getAlertsQueryForEntity(names, nameField, timerange, indexPattern);
const response = await esClient.asCurrentUser.search(query);
const buckets: EnhancedDataBucket[] = getOr([], 'aggregations.alertsByEntity.buckets', response);
const enhancedAlertsDataByEntityName = buckets.reduce<
@ -106,10 +110,12 @@ async function enhanceData(
const getAlertsQueryForEntity = (
names: string[],
nameField: string,
timerange: TimeRange | undefined
timerange: TimeRange | undefined,
indexPattern: string | undefined
): SearchRequest => {
return {
size: 0,
index: indexPattern,
query: {
bool: {
filter: [