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] Prevent deletion of agent policies with inactive agents from UI #175815

Merged
merged 7 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -12,15 +12,15 @@ import { FormattedMessage } from '@kbn/i18n-react';

import { useHistory } from 'react-router-dom';

import { AGENTS_PREFIX } from '../../../constants';
import { SO_SEARCH_LIMIT } from '../../../../../constants';

import {
useStartServices,
useConfig,
sendRequest,
useLink,
useDeleteAgentPolicyMutation,
sendGetAgents,
} from '../../../hooks';
import { API_VERSIONS } from '../../../../../../common/constants';

interface Props {
children: (deleteAgentPolicy: DeleteAgentPolicy) => React.ReactElement;
Expand Down Expand Up @@ -111,15 +111,13 @@ export const AgentPolicyDeleteProvider: React.FunctionComponent<Props> = ({
return;
}
setIsLoadingAgentsCount(true);
const { data } = await sendRequest<{ total: number }>({
path: `/api/fleet/agents`,
method: 'get',
query: {
kuery: `${AGENTS_PREFIX}.policy_id : ${agentPolicyToCheck}`,
},
version: API_VERSIONS.public.v1,
// filtering out the unenrolled agents assigned to this policy
const agents = await sendGetAgents({
showInactive: true,
kuery: `policy_id:"${agentPolicyToCheck}" and not status: unenrolled`,
perPage: SO_SEARCH_LIMIT,
});
setAgentsCount(data?.total || 0);
setAgentsCount(agents.data?.total ?? 0);
setIsLoadingAgentsCount(false);
};

Expand Down Expand Up @@ -168,6 +166,7 @@ export const AgentPolicyDeleteProvider: React.FunctionComponent<Props> = ({
) : agentsCount ? (
<EuiCallOut
color="danger"
iconType="warning"
title={i18n.translate(
'xpack.fleet.deleteAgentPolicy.confirmModal.affectedAgentsTitle',
{
Expand Down
12 changes: 12 additions & 0 deletions x-pack/plugins/fleet/server/services/agent_policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,18 @@ describe('agent policy', () => {
savedObjectType: AGENT_POLICY_SAVED_OBJECT_TYPE,
});
});

it('should throw error if active agents are assigned to the policy', async () => {
(getAgentsByKuery as jest.Mock).mockResolvedValue({
agents: [],
total: 2,
page: 1,
perPage: 10,
});
await expect(agentPolicyService.delete(soClient, esClient, 'mocked')).rejects.toThrowError(
'Cannot delete an agent policy that is assigned to any active or inactive agents'
);
});
});

describe('bumpRevision', () => {
Expand Down
8 changes: 5 additions & 3 deletions x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -853,16 +853,18 @@ class AgentPolicyService {
if (agentPolicy.is_managed && !options?.force) {
throw new HostedAgentPolicyRestrictionRelatedError(`Cannot delete hosted agent policy ${id}`);
}

// Prevent deleting policy when assigned agents are inactive
const { total } = await getAgentsByKuery(esClient, soClient, {
showInactive: false,
showInactive: true,
perPage: 0,
page: 1,
kuery: `${AGENTS_PREFIX}.policy_id:${id}`,
Copy link
Member

Choose a reason for hiding this comment

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

Should we add the unenrolled condition here too and not status: unenrolled?

});

if (total > 0) {
throw new FleetError('Cannot delete agent policy that is assigned to agent(s)');
throw new FleetError(
'Cannot delete an agent policy that is assigned to any active or inactive agents'
);
}

const packagePolicies = await packagePolicyService.findAllForAgentPolicy(soClient, id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import expect from '@kbn/expect';
import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '@kbn/fleet-plugin/common';
import { FLEET_AGENT_POLICIES_SCHEMA_VERSION } from '@kbn/fleet-plugin/server/constants';
import { skipIfNoDockerRegistry } from '../../helpers';
import { skipIfNoDockerRegistry, generateAgent } from '../../helpers';
import { setupFleetAndAgents } from '../agents/services';
import { FtrProviderContext } from '../../../api_integration/ftr_provider_context';

Expand Down Expand Up @@ -1186,6 +1186,68 @@ export default function (providerContext: FtrProviderContext) {
name: 'Regular policy',
});
});

describe.only('Errors when trying to delete', () => {
it('should prevent policies having agents from being deleted', async () => {
const {
body: { item: policyWithAgents },
} = await supertest
.post(`/api/fleet/agent_policies`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'Policy with agents',
namespace: 'default',
})
.expect(200);
await generateAgent(providerContext, 'healhty', `agent-inactive-1`, policyWithAgents.id);
const { body } = await supertest
.post('/api/fleet/agent_policies/delete')
.set('kbn-xsrf', 'xxx')
.send({ agentPolicyId: policyWithAgents.id })
.expect(400);

expect(body.message).to.contain(
'Cannot delete an agent policy that is assigned to any active or inactive agents'
);
await supertest
.delete(`/api/fleet/agents/${policyWithAgents.id}`)
.set('kbn-xsrf', 'xx')
.expect(200);
});

it('should prevent policies having inactive agents from being deleted', async () => {
const {
body: { item: policyWithInactiveAgents },
} = await supertest
.post(`/api/fleet/agent_policies`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'Policy with inactive agents',
namespace: 'default',
})
.expect(200);
await generateAgent(
providerContext,
'inactive',
`agent-inactive-1`,
policyWithInactiveAgents.id
);

const { body } = await supertest
.post('/api/fleet/agent_policies/delete')
.set('kbn-xsrf', 'xxx')
.send({ agentPolicyId: policyWithInactiveAgents.id })
.expect(400);

expect(body.message).to.contain(
'Cannot delete an agent policy that is assigned to any active or inactive agents'
);
await supertest
.delete(`/api/fleet/agents/${policyWithInactiveAgents.id}`)
.set('kbn-xsrf', 'xx')
.expect(200);
});
});
});

describe('POST /api/fleet/agent_policies/_bulk_get', () => {
Expand Down