Skip to content
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 @@ -5,11 +5,12 @@
* 2.0.
*/

import { httpServerMock } from '@kbn/core-http-server-mocks';
import { securityMock } from '@kbn/security-plugin/server/mocks';
import type { UserProfileServiceStart } from '@kbn/core-user-profile-server';
import type { UserService } from '../services/user_service/user_service';
import type { CreateAlertActionBody } from '../../routes/schemas/alert_action_schema';
import { createQueryService } from '../services/query_service/query_service.mock';
import { createStorageService } from '../services/storage_service/storage_service.mock';
import { createUserProfile, createUserService } from '../services/user_service/user_service.mock';
import { AlertActionsClient } from './alert_actions_client';
import {
getBulkAlertEventsESQLResponse,
Expand All @@ -19,16 +20,17 @@ import {

describe('AlertActionsClient', () => {
jest.useFakeTimers().setSystemTime(new Date('2025-01-01T11:12:13.000Z'));
const request = httpServerMock.createKibanaRequest();
const { queryService, mockEsClient: queryServiceEsClient } = createQueryService();
const { storageService, mockEsClient: storageServiceEsClient } = createStorageService();
const security = securityMock.createStart();
let userService: UserService;
let userProfile: jest.Mocked<UserProfileServiceStart>;
let client: AlertActionsClient;

beforeEach(() => {
security.authc.getCurrentUser = jest.fn().mockReturnValue({ username: 'test-user' });
({ userService, userProfile } = createUserService());
userProfile.getCurrent.mockResolvedValue(createUserProfile('test-uid'));
storageServiceEsClient.bulk.mockResolvedValueOnce({ items: [], errors: false, took: 1 });
client = new AlertActionsClient(request, queryService, storageService, security);
client = new AlertActionsClient(queryService, storageService, userService);
});

afterEach(() => {
Expand Down Expand Up @@ -62,7 +64,7 @@ describe('AlertActionsClient', () => {
episode_id: 'episode-1',
rule_id: 'test-rule-id',
last_series_event_timestamp: '2025-01-01T00:00:00.000Z',
actor: 'test-user',
actor: 'test-uid',
});
expect(docs[0]).toHaveProperty('@timestamp');
});
Expand Down Expand Up @@ -104,14 +106,14 @@ describe('AlertActionsClient', () => {
expect(docs[0]).toMatchObject({ episode_id: 'episode-2' });
});

it('should handle null username when security is not available', async () => {
it('should handle null profile uid when security is not available', async () => {
queryServiceEsClient.esql.query.mockResolvedValueOnce(getAlertEventESQLResponse());

userProfile.getCurrent.mockResolvedValueOnce(null);
const clientWithoutSecurity = new AlertActionsClient(
request,
queryService,
storageService,
undefined
userService
);

await clientWithoutSecurity.createAction({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,8 @@
*/

import Boom from '@hapi/boom';
import { PluginStart } from '@kbn/core-di';
import { Request } from '@kbn/core-di-server';
import type { KibanaRequest } from '@kbn/core-http-server';
import { esql } from '@kbn/esql-language';
import type { SecurityPluginStart } from '@kbn/security-plugin/server';
import { inject, injectable, optional } from 'inversify';
import { inject, injectable } from 'inversify';
import { groupBy, omit } from 'lodash';
import { ALERT_ACTIONS_DATA_STREAM, type AlertAction } from '../../resources/alert_actions';
import { ALERT_EVENTS_DATA_STREAM } from '../../resources/alert_events';
Expand All @@ -23,22 +19,23 @@ import { queryResponseToRecords } from '../services/query_service/query_response
import { QueryService, type QueryServiceContract } from '../services/query_service/query_service';
import type { StorageServiceContract } from '../services/storage_service/storage_service';
import { StorageServiceScopedToken } from '../services/storage_service/tokens';
import type { UserServiceContract } from '../services/user_service/user_service';
import { UserService } from '../services/user_service/user_service';

@injectable()
export class AlertActionsClient {
constructor(
@inject(Request) private readonly request: KibanaRequest,
@inject(QueryService) private readonly queryService: QueryServiceContract,
@inject(StorageServiceScopedToken) private readonly storageService: StorageServiceContract,
@optional() @inject(PluginStart('security')) private readonly security?: SecurityPluginStart
@inject(UserService) private readonly userService: UserServiceContract
) {}

public async createAction(params: {
groupHash: string;
action: CreateAlertActionBody;
}): Promise<void> {
const [username, alertEvent] = await Promise.all([
this.getUserName(),
const [userProfileUid, alertEvent] = await Promise.all([
this.getUserProfileUid(),
this.findLastAlertEventRecordOrThrow({
groupHash: params.groupHash,
episodeId: 'episode_id' in params.action ? params.action.episode_id : undefined,
Expand All @@ -51,7 +48,7 @@ export class AlertActionsClient {
this.buildAlertActionDocument({
action: params.action,
alertEvent,
username,
userProfileUid,
}),
],
});
Expand All @@ -60,8 +57,8 @@ export class AlertActionsClient {
public async createBulkActions(
actions: BulkCreateAlertActionItemBody[]
): Promise<{ processed: number; total: number }> {
const [username, records] = await Promise.all([
this.getUserName(),
const [userProfileUid, records] = await Promise.all([
this.getUserProfileUid(),
this.fetchLastAlertEventRecordsForActions(actions),
]);

Expand All @@ -82,7 +79,7 @@ export class AlertActionsClient {
return this.buildAlertActionDocument({
action,
alertEvent: matchingAlertEventRecord,
username,
userProfileUid,
});
}
})
Expand Down Expand Up @@ -122,21 +119,21 @@ export class AlertActionsClient {
);
}

private async getUserName(): Promise<string | null> {
return this.security?.authc.getCurrentUser(this.request)?.username ?? null;
private async getUserProfileUid(): Promise<string | null> {
Comment thread
adcoelho marked this conversation as resolved.
return this.userService.getCurrentUserProfileUid();
}

private buildAlertActionDocument(params: {
action: CreateAlertActionBody;
alertEvent: AlertEventRecord;
username: string | null;
userProfileUid: string | null;
}): AlertAction {
const { action, alertEvent, username } = params;
const { action, alertEvent, userProfileUid } = params;
const actionData = omit(action, ['episode_id', 'action_type']);

return {
'@timestamp': new Date().toISOString(),
actor: username,
actor: userProfileUid,
action_type: action.action_type,
last_series_event_timestamp: alertEvent['@timestamp'],
rule_id: alertEvent.rule_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ describe('FetchRuleStep', () => {
timeField: '@timestamp',
lookbackWindow: '1m',
groupingKey: [],
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
...overrides,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

import type { SavedObjectsClientContract } from '@kbn/core/server';
import { httpServerMock, httpServiceMock } from '@kbn/core-http-server-mocks';
import { mockAuthenticatedUser } from '@kbn/core-security-common/mocks';
import { securityMock } from '@kbn/security-plugin/server/mocks';
import { createUserService } from '../services/user_service/user_service.mock';
import { taskManagerMock } from '@kbn/task-manager-plugin/server/mocks';
import { RulesClient } from './rules_client';
import { createRulesSavedObjectService } from '../services/rules_saved_object_service/rules_saved_object_service.mock';
Expand All @@ -21,20 +20,16 @@ export function createRulesClient(): {
const request = httpServerMock.createKibanaRequest();
const http = httpServiceMock.createStartContract();
const taskManager = taskManagerMock.createStart();
const security = securityMock.createStart();
const { userService } = createUserService();

http.basePath.get.mockReturnValue('/s/default');

security.authc.getCurrentUser.mockReturnValue(
mockAuthenticatedUser({ username: 'elastic', profile_uid: 'elastic_profile_uid' })
);

const rulesClient = new RulesClient(
request,
http,
rulesSavedObjectService,
taskManager,
security
userService
);

return { rulesClient, mockSavedObjectsClient };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,17 @@
* 2.0.
*/

import type { KibanaRequest } from '@kbn/core-http-server';
import { httpServerMock, httpServiceMock } from '@kbn/core-http-server-mocks';
import { taskManagerMock } from '@kbn/task-manager-plugin/server/mocks';
import { securityMock } from '@kbn/security-plugin/server/mocks';
import { SavedObjectsErrorHelpers } from '@kbn/core-saved-objects-server';
import type { KibanaRequest } from '@kbn/core-http-server';
import type { AuthenticatedUser } from '@kbn/core/server';
import { mockAuthenticatedUser } from '@kbn/core-security-common/mocks';

import type { CreateRuleParams, UpdateRuleData } from './types';
import type { UserService } from '../services/user_service/user_service';
import { RULE_SAVED_OBJECT_TYPE, type RuleSavedObjectAttributes } from '../../saved_objects';
import { RulesClient } from './rules_client';
import { createRulesSavedObjectService } from '../services/rules_saved_object_service/rules_saved_object_service.mock';

import type { CreateRuleParams, UpdateRuleData } from './types';
import { createUserService } from '../services/user_service/user_service.mock';

jest.mock('../rule_executor/schedule', () => ({
ensureRuleExecutorTaskScheduled: jest.fn(),
Expand All @@ -37,7 +35,7 @@ describe('RulesClient', () => {
const request: KibanaRequest = httpServerMock.createKibanaRequest();
const http = httpServiceMock.createStartContract();
const taskManager = taskManagerMock.createStart();
const security = securityMock.createStart();
let userService: UserService;
const { rulesSavedObjectService, mockSavedObjectsClient } = createRulesSavedObjectService();

const baseCreateData: CreateRuleParams['data'] = {
Expand All @@ -61,13 +59,7 @@ describe('RulesClient', () => {

// Default space
http.basePath.get.mockReturnValue('/s/space-1');

const user: AuthenticatedUser = mockAuthenticatedUser({
username: 'elastic',
profile_uid: 'elastic_profile_uid',
});
security.authc.getCurrentUser.mockReturnValue(user);

({ userService } = createUserService({ request }));
mockSavedObjectsClient.create.mockResolvedValue({
id: 'rule-id-default',
type: RULE_SAVED_OBJECT_TYPE,
Expand Down Expand Up @@ -100,7 +92,7 @@ describe('RulesClient', () => {
});

function createClient() {
return new RulesClient(request, http, rulesSavedObjectService, taskManager, security);
return new RulesClient(request, http, rulesSavedObjectService, taskManager, userService);
}

describe('createRule', () => {
Expand All @@ -123,7 +115,7 @@ describe('RulesClient', () => {
expect.objectContaining({
name: 'rule-1',
enabled: false,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
}),
{ id: 'rule-id-1', overwrite: false }
);
Expand All @@ -135,8 +127,8 @@ describe('RulesClient', () => {
expect.objectContaining({
id: 'rule-id-1',
enabled: false,
createdBy: 'elastic',
updatedBy: 'elastic',
createdBy: 'elastic_profile_uid',
updatedBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedAt: '2025-01-01T00:00:00.000Z',
})
Expand Down Expand Up @@ -247,9 +239,9 @@ describe('RulesClient', () => {
const existingAttributes: RuleSavedObjectAttributes = {
...baseCreateData,
enabled: true,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
};
mockSavedObjectsClient.get.mockResolvedValueOnce({
Expand Down Expand Up @@ -284,9 +276,9 @@ describe('RulesClient', () => {
const existingAttributes: RuleSavedObjectAttributes = {
...baseCreateData,
enabled: false,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
};
mockSavedObjectsClient.get.mockResolvedValueOnce({
Expand Down Expand Up @@ -317,9 +309,9 @@ describe('RulesClient', () => {
const existingAttributes: RuleSavedObjectAttributes = {
...baseCreateData,
enabled: false,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
};
mockSavedObjectsClient.get.mockResolvedValueOnce({
Expand Down Expand Up @@ -349,9 +341,9 @@ describe('RulesClient', () => {
const existingAttributes: RuleSavedObjectAttributes = {
...baseCreateData,
enabled: true,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
};
mockSavedObjectsClient.get.mockResolvedValueOnce({
Expand Down Expand Up @@ -397,9 +389,9 @@ describe('RulesClient', () => {
const existingAttributes: RuleSavedObjectAttributes = {
...baseCreateData,
enabled: true,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
};
mockSavedObjectsClient.get.mockResolvedValueOnce({
Expand Down Expand Up @@ -452,9 +444,9 @@ describe('RulesClient', () => {
...baseCreateData,
name: 'rule-1',
enabled: true,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
},
};
Expand All @@ -467,9 +459,9 @@ describe('RulesClient', () => {
...baseCreateData,
name: 'rule-2',
enabled: false,
createdBy: 'elastic',
createdBy: 'elastic_profile_uid',
createdAt: '2025-01-01T00:00:00.000Z',
updatedBy: 'elastic',
updatedBy: 'elastic_profile_uid',
updatedAt: '2025-01-01T00:00:00.000Z',
},
};
Expand Down
Loading