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] Add packagePoliceDelete callback #148509

Merged
merged 1 commit into from
Jan 10, 2023
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
6 changes: 3 additions & 3 deletions x-pack/plugins/cloud_security_posture/server/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
import {
ExternalCallback,
FleetStartContract,
PostPackagePolicyDeleteCallback,
PostPackagePolicyPostDeleteCallback,
PostPackagePolicyPostCreateCallback,
} from '@kbn/fleet-plugin/server';
import { CLOUD_SECURITY_POSTURE_PACKAGE_NAME } from '../common/constants';
Expand Down Expand Up @@ -298,9 +298,9 @@ describe('Cloud Security Posture Plugin', () => {
const deletedPackagePolicyMock = deletePackagePolicyMock();
deletedPackagePolicyMock[0].package!.name = CLOUD_SECURITY_POSTURE_PACKAGE_NAME;

const packagePolicyPostDeleteCallbacks: PostPackagePolicyDeleteCallback[] = [];
const packagePolicyPostDeleteCallbacks: PostPackagePolicyPostDeleteCallback[] = [];
fleetMock.registerExternalCallback.mockImplementation((...args) => {
if (args[0] === 'postPackagePolicyDelete') {
if (args[0] === 'packagePolicyPostDelete') {
packagePolicyPostDeleteCallbacks.push(args[1]);
}
});
Expand Down
6 changes: 3 additions & 3 deletions x-pack/plugins/cloud_security_posture/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {
} from '@kbn/core/server';
import type { DeepReadonly } from 'utility-types';
import type {
DeletePackagePoliciesResponse,
PostDeletePackagePoliciesResponse,
PackagePolicy,
NewPackagePolicy,
} from '@kbn/fleet-plugin/common';
Expand Down Expand Up @@ -145,8 +145,8 @@ export class CspPlugin
);

plugins.fleet.registerExternalCallback(
'postPackagePolicyDelete',
async (deletedPackagePolicies: DeepReadonly<DeletePackagePoliciesResponse>) => {
'packagePolicyPostDelete',
async (deletedPackagePolicies: DeepReadonly<PostDeletePackagePoliciesResponse>) => {
for (const deletedPackagePolicy of deletedPackagePolicies) {
if (isCspPackage(deletedPackagePolicy.package?.name)) {
const soClient = core.savedObjects.createInternalRepository();
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export type {
GetAgentPoliciesRequest,
GetAgentPoliciesResponse,
GetAgentPoliciesResponseItem,
DeletePackagePoliciesResponse,
PostDeletePackagePoliciesResponse,
GetPackagesResponse,
BulkInstallPackagesResponse,
FleetErrorResponse,
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/fleet/common/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import type { DeletePackagePoliciesResponse, NewPackagePolicy, PackagePolicy } from './types';
import type { PostDeletePackagePoliciesResponse, NewPackagePolicy, PackagePolicy } from './types';
import type { FleetAuthz } from './authz';
import { ENDPOINT_PRIVILEGES } from './constants';

Expand Down Expand Up @@ -47,7 +47,7 @@ export const createPackagePolicyMock = (): PackagePolicy => {
};
};

export const deletePackagePolicyMock = (): DeletePackagePoliciesResponse => {
export const deletePackagePolicyMock = (): PostDeletePackagePoliciesResponse => {
const newPackagePolicy = createNewPackagePolicyMock();
return [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ export interface DeletePackagePoliciesRequest {
};
}

export type DeletePackagePoliciesResponse = Array<{
export type DeletePackagePoliciesResponse = PackagePolicy[];

export type PostDeletePackagePoliciesResponse = Array<{
id: string;
name?: string;
success: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
} from '../../types';
import type {
DeletePackagePoliciesRequest,
DeletePackagePoliciesResponse,
PostDeletePackagePoliciesResponse,
GetPackagePoliciesRequest,
GetPackagePoliciesResponse,
GetOnePackagePolicyResponse,
Expand Down Expand Up @@ -44,7 +44,7 @@ export const sendUpdatePackagePolicy = (
};

export const sendDeletePackagePolicy = (body: DeletePackagePoliciesRequest['body']) => {
return sendRequest<DeletePackagePoliciesResponse>({
return sendRequest<PostDeletePackagePoliciesResponse>({
path: packagePolicyRouteService.getDeletePath(),
method: 'post',
body: JSON.stringify(body),
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export type { FleetSetupContract, FleetSetupDeps, FleetStartContract } from './p
export type {
ExternalCallback,
PutPackagePolicyUpdateCallback,
PostPackagePolicyDeleteCallback,
PostPackagePolicyPostDeleteCallback,
PostPackagePolicyCreateCallback,
FleetRequestHandlerContext,
PostPackagePolicyPostCreateCallback,
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/fleet/server/mocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export const createPackagePolicyServiceMock = (): jest.Mocked<PackagePolicyClien
bulkUpdate: jest.fn(),
runExternalCallbacks: jest.fn(),
runDeleteExternalCallbacks: jest.fn(),
runPostDeleteExternalCallbacks: jest.fn(),
upgrade: jest.fn(),
getUpgradeDryRunDiff: jest.fn(),
getUpgradePackagePolicyInfo: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ jest.mock(
update: jest.fn(),
// @ts-ignore
runExternalCallbacks: jest.fn((callbackType, packagePolicy, context, request) =>
callbackType === 'postPackagePolicyDelete'
callbackType === 'packagePolicyPostDelete'
? Promise.resolve(undefined)
: Promise.resolve(packagePolicy)
),
Expand Down
52 changes: 46 additions & 6 deletions x-pack/plugins/fleet/server/routes/package_policy/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import type {
import type {
BulkGetPackagePoliciesResponse,
CreatePackagePolicyResponse,
DeletePackagePoliciesResponse,
PostDeletePackagePoliciesResponse,
NewPackagePolicy,
UpgradePackagePolicyDryRunResponse,
UpgradePackagePolicyResponse,
Expand All @@ -50,6 +50,8 @@ import { simplifiedPackagePolicytoNewPackagePolicy } from '../../../common/servi

import type { SimplifiedPackagePolicy } from '../../../common/services/simplified_package_policy_helper';

export const isNotNull = <T>(value: T | null): value is T => value !== null;

export const getPackagePoliciesHandler: FleetRequestHandler<
undefined,
TypeOf<typeof GetPackagePoliciesRequestSchema.query>
Expand Down Expand Up @@ -398,22 +400,43 @@ export const deletePackagePolicyHandler: RequestHandler<
const soClient = coreContext.savedObjects.client;
const esClient = coreContext.elasticsearch.client.asInternalUser;
const user = appContextService.getSecurity()?.authc.getCurrentUser(request) || undefined;
const logger = appContextService.getLogger();

try {
const body: DeletePackagePoliciesResponse = await packagePolicyService.delete(
try {
const packagePolicies = await packagePolicyService.getByIDs(
soClient,
request.body.packagePolicyIds,
{ ignoreMissing: true }
);

if (packagePolicies) {
await packagePolicyService.runExternalCallbacks(
'packagePolicyDelete',
packagePolicies,
context,
request
);
}
} catch (error) {
logger.error(`An error occurred executing external callback: ${error}`);
logger.error(error);
}

const body: PostDeletePackagePoliciesResponse = await packagePolicyService.delete(
soClient,
esClient,
request.body.packagePolicyIds,
{ user, force: request.body.force, skipUnassignFromAgentPolicies: request.body.force }
);
try {
await packagePolicyService.runExternalCallbacks(
'postPackagePolicyDelete',
'packagePolicyPostDelete',
body,
context,
request
);
} catch (error) {
const logger = appContextService.getLogger();
logger.error(`An error occurred executing external callback: ${error}`);
logger.error(error);
}
Expand All @@ -434,7 +457,25 @@ export const deleteOnePackagePolicyHandler: RequestHandler<
const soClient = coreContext.savedObjects.client;
const esClient = coreContext.elasticsearch.client.asInternalUser;
const user = appContextService.getSecurity()?.authc.getCurrentUser(request) || undefined;
const logger = appContextService.getLogger();

try {
try {
const packagePolicy = await packagePolicyService.get(
soClient,
request.params.packagePolicyId
);
await packagePolicyService.runExternalCallbacks(
'packagePolicyDelete',
packagePolicy ? [packagePolicy] : [],
context,
request
);
} catch (error) {
logger.error(`An error occurred executing external callback: ${error}`);
logger.error(error);
}

const res = await packagePolicyService.delete(
soClient,
esClient,
Expand All @@ -454,13 +495,12 @@ export const deleteOnePackagePolicyHandler: RequestHandler<
}
try {
await packagePolicyService.runExternalCallbacks(
'postPackagePolicyDelete',
'packagePolicyPostDelete',
res,
context,
request
);
} catch (error) {
const logger = appContextService.getLogger();
logger.error(`An error occurred executing external callback: ${error}`);
logger.error(error);
}
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/fleet/server/services/agent_policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ describe('agent policy', () => {

it('should run package policy delete external callbacks', async () => {
await agentPolicyService.delete(soClient, esClient, 'mocked');
expect(packagePolicyService.runDeleteExternalCallbacks).toHaveBeenCalledWith([
expect(packagePolicyService.runPostDeleteExternalCallbacks).toHaveBeenCalledWith([
{ id: 'package-1' },
]);
});
Expand All @@ -195,7 +195,7 @@ describe('agent policy', () => {

await agentPolicyService.delete(soClient, esClient, 'mocked', { force: true });

expect(packagePolicyService.runDeleteExternalCallbacks).toHaveBeenCalledWith([
expect(packagePolicyService.runPostDeleteExternalCallbacks).toHaveBeenCalledWith([
{ id: 'package-1' },
]);
});
Expand Down
9 changes: 6 additions & 3 deletions x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import type {
FleetServerPolicy,
Installation,
Output,
DeletePackagePoliciesResponse,
PostDeletePackagePoliciesResponse,
PackageInfo,
} from '../../common/types';
import {
Expand Down Expand Up @@ -680,7 +680,10 @@ class AgentPolicyService {
`Cannot delete agent policy ${id} that contains managed package policies`
);
}
const deletedPackagePolicies: DeletePackagePoliciesResponse =

await packagePolicyService.runDeleteExternalCallbacks(packagePolicies);

const deletedPackagePolicies: PostDeletePackagePoliciesResponse =
await packagePolicyService.delete(
soClient,
esClient,
Expand All @@ -691,7 +694,7 @@ class AgentPolicyService {
}
);
try {
await packagePolicyService.runDeleteExternalCallbacks(deletedPackagePolicies);
await packagePolicyService.runPostDeleteExternalCallbacks(deletedPackagePolicies);
} catch (error) {
const logger = appContextService.getLogger();
logger.error(`An error occurred executing external callback: ${error}`);
Expand Down
11 changes: 8 additions & 3 deletions x-pack/plugins/fleet/server/services/app_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ import type { ExperimentalFeatures } from '../../common/experimental_features';
import type {
ExternalCallback,
ExternalCallbacksStorage,
PostPackagePolicyCreateCallback,
PostPackagePolicyDeleteCallback,
PostPackagePolicyCreateCallback,
PostPackagePolicyPostDeleteCallback,
PostPackagePolicyPostCreateCallback,
PutPackagePolicyUpdateCallback,
} from '../types';
Expand Down Expand Up @@ -211,8 +212,10 @@ class AppContextService {
| Set<
T extends 'packagePolicyCreate'
? PostPackagePolicyCreateCallback
: T extends 'postPackagePolicyDelete'
: T extends 'packagePolicyDelete'
? PostPackagePolicyDeleteCallback
: T extends 'packagePolicyPostDelete'
? PostPackagePolicyPostDeleteCallback
: T extends 'packagePolicyPostCreate'
? PostPackagePolicyPostCreateCallback
: PutPackagePolicyUpdateCallback
Expand All @@ -222,8 +225,10 @@ class AppContextService {
return this.externalCallbacks.get(type) as Set<
T extends 'packagePolicyCreate'
? PostPackagePolicyCreateCallback
: T extends 'postPackagePolicyDelete'
: T extends 'packagePolicyDelete'
? PostPackagePolicyDeleteCallback
: T extends 'packagePolicyPostDelete'
? PostPackagePolicyPostDeleteCallback
: T extends 'packagePolicyPostCreate'
? PostPackagePolicyPostCreateCallback
: PutPackagePolicyUpdateCallback
Expand Down
Loading