Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fleet] backfill agentless package policies with supports_agentless field #204410

Merged
merged 4 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
backfill agentless package policies
  • Loading branch information
juliaElastic committed Dec 16, 2024
commit b93ddac841d0270a32f2497728fe1027b4d09236
66 changes: 66 additions & 0 deletions x-pack/plugins/fleet/server/services/backfill_agentless.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 { backfillPackagePolicySupportsAgentless } from './backfill_agentless';
import { packagePolicyService } from './package_policy';

jest.mock('.', () => ({
appContextService: {
getLogger: () => ({
debug: jest.fn(),
}),
getInternalUserSOClientForSpaceId: jest.fn(),
getInternalUserSOClientWithoutSpaceExtension: () => ({
find: jest.fn().mockImplementation((options) => {
if (options.type === 'ingest-agent-policies') {
return {
saved_objects: [{ id: 'agent_policy_1' }, { id: 'agent_policy_2' }],
};
} else {
return {
saved_objects: [
{
id: 'package_policy_1',
attributes: {
inputs: [],
policy_ids: ['agent_policy_1'],
supports_agentless: false,
},
},
],
};
}
}),
}),
},
}));

jest.mock('./package_policy', () => ({
packagePolicyService: {
update: jest.fn(),
},
getPackagePolicySavedObjectType: jest.fn().mockResolvedValue('ingest-package-policies'),
}));

describe('backfill agentless package policies', () => {
it('should backfill package policies missing supports_agentless', async () => {
await backfillPackagePolicySupportsAgentless(undefined as any);

expect(packagePolicyService.update).toHaveBeenCalledWith(
undefined,
undefined,
'package_policy_1',
{
enabled: undefined,
inputs: [],
name: undefined,
policy_ids: ['agent_policy_1'],
supports_agentless: true,
}
);
});
});
95 changes: 95 additions & 0 deletions x-pack/plugins/fleet/server/services/backfill_agentless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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 type { ElasticsearchClient } from '@kbn/core/server';

import pMap from 'p-map';

import { MAX_CONCURRENT_AGENT_POLICIES_OPERATIONS, SO_SEARCH_LIMIT } from '../constants';

import type { AgentPolicySOAttributes, PackagePolicy, PackagePolicySOAttributes } from '../types';

import { getAgentPolicySavedObjectType } from './agent_policy';

import { appContextService } from '.';
import { getPackagePolicySavedObjectType, packagePolicyService } from './package_policy';
import { mapPackagePolicySavedObjectToPackagePolicy } from './package_policies';

export async function backfillPackagePolicySupportsAgentless(esClient: ElasticsearchClient) {
const apSavedObjectType = await getAgentPolicySavedObjectType();
const internalSoClientWithoutSpaceExtension =
appContextService.getInternalUserSOClientWithoutSpaceExtension();
const findRes = await internalSoClientWithoutSpaceExtension.find<AgentPolicySOAttributes>({
type: apSavedObjectType,
page: 1,
perPage: SO_SEARCH_LIMIT,
filter: `${apSavedObjectType}.attributes.supports_agentless:true`,
fields: [`id`],
namespaces: ['*'],
});

const agentPolicyIds = findRes.saved_objects.map((so) => so.id);

const savedObjectType = await getPackagePolicySavedObjectType();
const packagePoliciesToUpdate = (
await appContextService
.getInternalUserSOClientWithoutSpaceExtension()
.find<PackagePolicySOAttributes>({
type: savedObjectType,
fields: [
'name',
'policy_ids',
'supports_agentless',
'enabled',
'policy_ids',
'inputs',
'package',
],
filter: `${savedObjectType}.attributes.package.name:cloud_security_posture AND (NOT ${savedObjectType}.attributes.supports_agentless:true) AND ${savedObjectType}.attributes.policy_ids:(${agentPolicyIds.join(
' OR '
)})`,
perPage: SO_SEARCH_LIMIT,
namespaces: ['*'],
})
).saved_objects.map((so) => mapPackagePolicySavedObjectToPackagePolicy(so, so.namespaces));

appContextService
.getLogger()
.debug(
`Backfilling supports_agentless on package policies: ${packagePoliciesToUpdate.map(
(policy) => policy.id
)}`
);

if (packagePoliciesToUpdate.length > 0) {
const getPackagePolicyUpdate = (packagePolicy: PackagePolicy) => ({
name: packagePolicy.name,
enabled: packagePolicy.enabled,
policy_ids: packagePolicy.policy_ids,
inputs: packagePolicy.inputs,
supports_agentless: true,
});

await pMap(
packagePoliciesToUpdate,
(packagePolicy) => {
const soClient = appContextService.getInternalUserSOClientForSpaceId(
packagePolicy.spaceIds?.[0]
);
return packagePolicyService.update(
soClient,
esClient,
packagePolicy.id,
getPackagePolicyUpdate(packagePolicy)
);
},
{
concurrency: MAX_CONCURRENT_AGENT_POLICIES_OPERATIONS,
}
);
}
}
4 changes: 4 additions & 0 deletions x-pack/plugins/fleet/server/services/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
ensureDeleteUnenrolledAgentsSetting,
getPreconfiguredDeleteUnenrolledAgentsSettingFromConfig,
} from './preconfiguration/delete_unenrolled_agent_setting';
import { backfillPackagePolicySupportsAgentless } from './backfill_agentless';

export interface SetupStatus {
isInitialized: boolean;
Expand Down Expand Up @@ -305,6 +306,9 @@ async function createSetupSideEffects(
await ensureAgentPoliciesFleetServerKeysAndPolicies({ soClient, esClient, logger });
stepSpan?.end();

logger.debug('Backfilling package policy supports_agentless field');
await backfillPackagePolicySupportsAgentless(esClient);

const nonFatalErrors = [
...preconfiguredPackagesNonFatalErrors,
...(messageSigningServiceNonFatalError ? [messageSigningServiceNonFatalError] : []),
Expand Down