diff --git a/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts index ff20e25e5bf0d9..4ddb3cfb6a6a52 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts @@ -4,11 +4,27 @@ * you may not use this file except in compliance with the Elastic License. */ -import { SavedObjectsClientContract } from 'src/core/server'; +import { KibanaRequest, SavedObjectsClientContract } from 'src/core/server'; import { generateEnrollmentAPIKey, deleteEnrollmentApiKeyForAgentPolicyId } from './api_keys'; import { unenrollForAgentPolicyId } from './agents'; import { outputService } from './output'; import { agentPolicyService } from './agent_policy'; +import { appContextService } from './app_context'; + +const fakeRequest = ({ + headers: {}, + getBasePath: () => '', + path: '/', + route: { settings: {} }, + url: { + href: '/', + }, + raw: { + req: { + url: '/', + }, + }, +} as unknown) as KibanaRequest; export async function agentPolicyUpdateEventHandler( soClient: SavedObjectsClientContract, @@ -17,20 +33,25 @@ export async function agentPolicyUpdateEventHandler( ) { const adminUser = await outputService.getAdminUser(soClient); const outputId = await outputService.getDefaultOutputId(soClient); + // If no admin user and no default output fleet is not enabled just skip this hook if (!adminUser || !outputId) { return; } + // `soClient` from ingest `appContextService` is used to create policy change actions + // to ensure encrypted SOs are handled correctly + const internalSoClient = appContextService.getInternalUserSOClient(fakeRequest); + if (action === 'created') { await generateEnrollmentAPIKey(soClient, { agentPolicyId, }); - await agentPolicyService.createFleetPolicyChangeAction(soClient, agentPolicyId); + await agentPolicyService.createFleetPolicyChangeAction(internalSoClient, agentPolicyId); } if (action === 'updated') { - await agentPolicyService.createFleetPolicyChangeAction(soClient, agentPolicyId); + await agentPolicyService.createFleetPolicyChangeAction(internalSoClient, agentPolicyId); } if (action === 'deleted') {