Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

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 @@ -278,6 +278,7 @@ type CombinedExternalCallback = PutPackagePolicyUpdateCallback | PostPackagePoli

const mockAgentPolicyGet = (spaceIds: string[] = ['default'], additionalProps?: any) => {
const basePolicy = {
id: 'agentPolicy1',
name: 'Test Agent Policy',
namespace: 'test',
status: 'active',
Expand Down Expand Up @@ -4267,19 +4268,190 @@ describe('Package policy service', () => {
});

describe('delete', () => {
// TODO: Add tests
it('should allow to delete a package policy', async () => {});
const mockPackagePolicy = {
id: 'test-package-policy',
type: LEGACY_PACKAGE_POLICY_SAVED_OBJECT_TYPE,
attributes: createPackagePolicyMock(),
references: [],
};

it('should call audit logger', async () => {
it('should allow to delete package policies from ES index', async () => {
const soClient = createSavedObjectClientMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;

const mockPackagePolicy = {
id: 'test-package-policy',
type: LEGACY_PACKAGE_POLICY_SAVED_OBJECT_TYPE,
attributes: {},
references: [],
};
soClient.bulkGet.mockResolvedValue({
saved_objects: [
{
id: 'test',
type: 'abcd',
references: [],
version: 'test',
attributes: createPackagePolicyMock(),
},
],
});

soClient.get.mockResolvedValueOnce({
...mockPackagePolicy,
});

mockAgentPolicyGet();

(getPackageInfo as jest.Mock).mockImplementation(async (params) => {
return Promise.resolve({
...(await mockedGetPackageInfo(params)),
elasticsearch: {
privileges: {
cluster: ['monitor'],
},
},
} as PackageInfo);
});
const idToDelete = 'c6d16e42-c32d-4dce-8a88-113cfe276ad1';
soClient.bulkDelete.mockResolvedValue({
statuses: [
{ id: idToDelete, type: LEGACY_PACKAGE_POLICY_SAVED_OBJECT_TYPE, success: true },
],
});

await packagePolicyService.delete(soClient, esClient, [idToDelete]);

expect(soClient.bulkDelete).toHaveBeenCalledWith(
[{ id: idToDelete, type: 'ingest-package-policies' }],
{ force: true }
);
});
it('should allow to delete orphaned package policies from ES index', async () => {
const soClient = createSavedObjectClientMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;

soClient.bulkGet.mockResolvedValue({
saved_objects: [
{
id: 'test',
type: 'abcd',
references: [],
version: 'test',
attributes: createPackagePolicyMock(),
},
],
});

soClient.get.mockResolvedValueOnce({
...mockPackagePolicy,
});

// agent policy not found
mockAgentPolicyService.get.mockRejectedValueOnce({
output: { statusCode: 404, payload: { message: 'policy not found' } },
});

mockAgentPolicyService.getByIds.mockResolvedValueOnce([
{
id: 'agentPolicy1',
name: 'Test Agent Policy',
namespace: 'test',
status: 'active',
is_managed: false,
updated_at: new Date().toISOString(),
updated_by: 'test',
revision: 1,
is_protected: false,
space_ids: ['default'],
},
]);

(getPackageInfo as jest.Mock).mockImplementation(async (params) => {
return Promise.resolve({
...(await mockedGetPackageInfo(params)),
elasticsearch: {
privileges: {
cluster: ['monitor'],
},
},
} as PackageInfo);
});
const idToDelete = 'c6d16e42-c32d-4dce-8a88-113cfe276ad1';
soClient.bulkDelete.mockResolvedValue({
statuses: [
{ id: idToDelete, type: LEGACY_PACKAGE_POLICY_SAVED_OBJECT_TYPE, success: true },
],
});

await packagePolicyService.delete(soClient, esClient, [idToDelete]);

expect(soClient.bulkDelete).toHaveBeenCalledWith(
[{ id: idToDelete, type: 'ingest-package-policies' }],
{ force: true }
);
});

it('should not allow to delete managed package policies', async () => {
const soClient = createSavedObjectClientMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;

soClient.bulkGet.mockResolvedValue({
saved_objects: [
{
id: 'test',
type: 'abcd',
references: [],
version: 'test',
attributes: createPackagePolicyMock(),
},
],
});

soClient.get.mockResolvedValueOnce({
...mockPackagePolicy,
});
const managedAgentPolicy = {
id: 'agentPolicy1',
name: 'Test Agent Policy',
namespace: 'test',
status: 'active',
is_managed: true,
updated_at: new Date().toISOString(),
updated_by: 'test',
revision: 1,
is_protected: false,
space_ids: ['default'],
} as any;
// agent policy not found
mockAgentPolicyService.get.mockResolvedValueOnce(managedAgentPolicy);

mockAgentPolicyService.getByIds.mockResolvedValueOnce([managedAgentPolicy]);

(getPackageInfo as jest.Mock).mockImplementation(async (params) => {
return Promise.resolve({
...(await mockedGetPackageInfo(params)),
elasticsearch: {
privileges: {
cluster: ['monitor'],
},
},
} as PackageInfo);
});
const idToDelete = 'c6d16e42-c32d-4dce-8a88-113cfe276ad1';

expect(await packagePolicyService.delete(soClient, esClient, [idToDelete])).toEqual([
{
body: {
message:
'Cannot remove integrations of hosted agent policy in Fleet because the agent policy is managed by an external orchestration solution, such as Elastic Cloud, Kubernetes, etc. Please make changes using your orchestration solution.',
},
id: 'c6d16e42-c32d-4dce-8a88-113cfe276ad1',
statusCode: 400,
success: false,
},
]);

expect(soClient.bulkDelete).not.toHaveBeenCalled();
});

it('should call audit logger', async () => {
const soClient = createSavedObjectClientMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;

soClient.bulkGet.mockResolvedValueOnce({
saved_objects: [{ ...mockPackagePolicy }],
Expand All @@ -4301,6 +4473,13 @@ describe('Package policy service', () => {
savedObjectType: LEGACY_PACKAGE_POLICY_SAVED_OBJECT_TYPE,
});
});

it('should return empty array if no package policies are found', async () => {
const soClient = createSavedObjectClientMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
const res = await packagePolicyService.delete(soClient, esClient, ['test-package-policy']);
expect(res).toEqual([]);
});
});

describe('runPostDeleteExternalCallbacks', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1974,7 +1974,9 @@ class PackagePolicyClientImpl implements PackagePolicyClient {
ignoreMissing: true,
spaceIds: options?.spaceIds,
});

if (!packagePolicies || packagePolicies.length === 0) {
logger.debug(`No package policies to delete`);
return [];
}

Expand Down Expand Up @@ -2015,7 +2017,11 @@ class PackagePolicyClientImpl implements PackagePolicyClient {
agentlessAgentPolicies.push(agentPolicyId);
}
} catch (e) {
hostedAgentPolicies.push(agentPolicyId);
logger.error(
`An error occurred while checking if policies are hosted: ${e?.output?.payload?.message}`
);
// in case of orphaned policies don't add the id to the hostedAgentPolicies array
if (e?.output?.statusCode !== 404) hostedAgentPolicies.push(agentPolicyId);
}
}

Expand Down
Loading