Skip to content

Commit

Permalink
[7.17] [Fleet] Fix reset one preconfiguration API (#122963) (#122994)
Browse files Browse the repository at this point in the history
* [Fleet] Fix reset one preconfiguration API (#122963)

(cherry picked from commit cfd7cc3)

# Conflicts:
#	x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts
#	x-pack/plugins/fleet/server/routes/preconfiguration/index.ts

* fix linting
  • Loading branch information
nchaulet authored Jan 13, 2022
1 parent 9e4f88b commit ae2052d
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ describe.skip('Fleet preconfiguration rest', () => {
{
xpack: {
fleet: {
// Preconfigure two policies test-12345 and test-456789
agentPolicies: [
{
name: 'Elastic Cloud agent policy 0001',
Expand Down Expand Up @@ -84,6 +85,36 @@ describe.skip('Fleet preconfiguration rest', () => {
},
],
},
{
name: 'Second preconfigured policy',
description: 'second policy',
is_default: false,
is_managed: true,
id: 'test-456789',
namespace: 'default',
monitoring_enabled: [],
package_policies: [
{
name: 'fleet_server987654321',
package: {
name: 'fleet_server',
},
inputs: [
{
type: 'fleet-server',
keep_enabled: true,
vars: [
{
name: 'host',
value: '127.0.0.1',
frozen: true,
},
],
},
],
},
],
},
],
},
},
Expand Down Expand Up @@ -139,11 +170,12 @@ describe.skip('Fleet preconfiguration rest', () => {
await new Promise((res) => setTimeout(res, 10000));
};

beforeEach(async () => {
// Share the same servers for all the test to make test a lot faster (but test are not isolated anymore)
beforeAll(async () => {
await startServers();
});

afterEach(async () => {
afterAll(async () => {
await stopServers();
});

Expand All @@ -162,12 +194,15 @@ describe.skip('Fleet preconfiguration rest', () => {
type: 'ingest-agent-policies',
perPage: 10000,
});
expect(agentPolicies.saved_objects).toHaveLength(1);
expect(agentPolicies.saved_objects).toHaveLength(2);
expect(agentPolicies.saved_objects.map((ap) => ap.attributes)).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'Elastic Cloud agent policy 0001',
}),
expect.objectContaining({
name: 'Second preconfigured policy',
}),
])
);
});
Expand All @@ -181,6 +216,13 @@ describe.skip('Fleet preconfiguration rest', () => {

await soClient.delete('ingest-agent-policies', POLICY_ID);

const oldAgentPolicies = await soClient.find<AgentPolicySOAttributes>({
type: 'ingest-agent-policies',
perPage: 10000,
});

const secondAgentPoliciesUpdatedAt = oldAgentPolicies.saved_objects[0].updated_at;

const resetAPI = kbnTestServer.getSupertest(
kbnServer.root,
'post',
Expand All @@ -194,12 +236,18 @@ describe.skip('Fleet preconfiguration rest', () => {
type: 'ingest-agent-policies',
perPage: 10000,
});
expect(agentPolicies.saved_objects).toHaveLength(1);
expect(agentPolicies.saved_objects.map((ap) => ap.attributes)).toEqual(
expect(agentPolicies.saved_objects).toHaveLength(2);
expect(
agentPolicies.saved_objects.map((ap) => ({ ...ap.attributes, updated_at: ap.updated_at }))
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'Elastic Cloud agent policy 0001',
}),
expect.objectContaining({
name: 'Second preconfigured policy',
updated_at: secondAgentPoliciesUpdatedAt, // Check that policy was not updated
}),
])
);
});
Expand All @@ -222,13 +270,16 @@ describe.skip('Fleet preconfiguration rest', () => {
type: 'ingest-agent-policies',
perPage: 10000,
});
expect(agentPolicies.saved_objects).toHaveLength(1);
expect(agentPolicies.saved_objects).toHaveLength(2);
expect(agentPolicies.saved_objects.map((ap) => ap.attributes)).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'Elastic Cloud agent policy 0001',
package_policies: expect.arrayContaining([expect.stringMatching(/.*/)]),
}),
expect.objectContaining({
name: 'Second preconfigured policy',
}),
])
);
});
Expand Down
10 changes: 5 additions & 5 deletions x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { PreconfiguredAgentPolicy } from '../../../common';
import type { FleetRequestHandler } from '../../types';
import type {
PutPreconfigurationSchema,
PostResetOnePreconfiguredAgentPolicies,
PostResetOnePreconfiguredAgentPoliciesSchema,
} from '../../types';
import { defaultIngestErrorHandler } from '../../errors';
import { ensurePreconfiguredPackagesAndPolicies, outputService } from '../../services';
Expand Down Expand Up @@ -42,23 +42,23 @@ export const updatePreconfigurationHandler: FleetRequestHandler<
}
};

export const resetPreconfigurationHandler: FleetRequestHandler<
TypeOf<typeof PostResetOnePreconfiguredAgentPolicies.params>,
export const resetOnePreconfigurationHandler: FleetRequestHandler<
TypeOf<typeof PostResetOnePreconfiguredAgentPoliciesSchema.params>,
undefined,
undefined
> = async (context, request, response) => {
const soClient = context.core.savedObjects.client;
const esClient = context.core.elasticsearch.client.asInternalUser;

try {
await resetPreconfiguredAgentPolicies(soClient, esClient, request.params.agentPolicyid);
await resetPreconfiguredAgentPolicies(soClient, esClient, request.params.agentPolicyId);
return response.ok({});
} catch (error) {
return defaultIngestErrorHandler({ error, response });
}
};

export const resetOnePreconfigurationHandler: FleetRequestHandler<undefined, undefined, undefined> =
export const resetPreconfigurationHandler: FleetRequestHandler<undefined, undefined, undefined> =
async (context, request, response) => {
const soClient = context.core.savedObjects.client;
const esClient = context.core.elasticsearch.client.asInternalUser;
Expand Down
7 changes: 5 additions & 2 deletions x-pack/plugins/fleet/server/routes/preconfiguration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import type { IRouter, RequestHandler } from 'src/core/server';

import { PLUGIN_ID, PRECONFIGURATION_API_ROUTES } from '../../constants';
import { PutPreconfigurationSchema } from '../../types';
import {
PutPreconfigurationSchema,
PostResetOnePreconfiguredAgentPoliciesSchema,
} from '../../types';

import {
updatePreconfigurationHandler,
Expand All @@ -28,7 +31,7 @@ export const registerRoutes = (router: IRouter) => {
router.post(
{
path: PRECONFIGURATION_API_ROUTES.RESET_ONE_PATTERN,
validate: false,
validate: PostResetOnePreconfiguredAgentPoliciesSchema,
options: { tags: [`access:${PLUGIN_ID}-all`] },
},
resetOnePreconfigurationHandler as RequestHandler
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ class AgentPolicyService {
await this.triggerAgentPolicyUpdatedEvent(soClient, esClient, 'deleted', id);

if (options?.removeFleetServerDocuments) {
this.deleteFleetServerPoliciesForPolicyId(esClient, id);
await this.deleteFleetServerPoliciesForPolicyId(esClient, id);
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,22 @@ async function _deleteExistingData(
logger: Logger,
agentPolicyId?: string
) {
let existingPolicies: AgentPolicy[];
let existingPolicies: AgentPolicy[] = [];

if (agentPolicyId) {
const policy = await agentPolicyService.get(soClient, agentPolicyId);
if (!policy || !policy.is_preconfigured) {
const policy = await agentPolicyService.get(soClient, agentPolicyId).catch((err) => {
if (err.output?.statusCode === 404) {
return undefined;
}
throw err;
});
if (policy && !policy.is_preconfigured) {
throw new Error('Invalid policy');
}
existingPolicies = [policy];
}
{
if (policy) {
existingPolicies = [policy];
}
} else {
existingPolicies = (
await agentPolicyService.list(soClient, {
perPage: SO_SEARCH_LIMIT,
Expand All @@ -120,6 +126,7 @@ async function _deleteExistingData(
const { items: enrollmentApiKeys } = await listEnrollmentApiKeys(esClient, {
perPage: SO_SEARCH_LIMIT,
showInactive: true,
kuery: existingPolicies.map((policy) => `policy_id:"${policy.id}"`).join(' or '),
});

if (enrollmentApiKeys.length > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export const PutPreconfigurationSchema = {
}),
};

export const PostResetOnePreconfiguredAgentPolicies = {
export const PostResetOnePreconfiguredAgentPoliciesSchema = {
params: schema.object({
agentPolicyid: schema.string(),
agentPolicyId: schema.string(),
}),
};

0 comments on commit ae2052d

Please sign in to comment.