[8.0] [Fleet] Fix reset one preconfiguration API (#122963) (#122992)

* [Fleet] Fix reset one preconfiguration API (#122963)

(cherry picked from commit cfd7cc330b)

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

* fix linting
This commit is contained in:
Nicolas Chaulet 2022-01-13 16:21:57 -05:00 committed by GitHub
parent 9d547ec18a
commit 229921bf3f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 83 additions and 22 deletions

View file

@ -53,6 +53,7 @@ describe('Fleet preconfiguration rest', () => {
{
xpack: {
fleet: {
// Preconfigure two policies test-12345 and test-456789
agentPolicies: [
{
name: 'Elastic Cloud agent policy 0001',
@ -84,6 +85,36 @@ describe('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,
},
],
},
],
},
],
},
],
},
},
@ -139,11 +170,12 @@ describe('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();
});
@ -162,12 +194,15 @@ describe('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',
}),
])
);
});
@ -181,6 +216,13 @@ describe('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',
@ -194,12 +236,18 @@ describe('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
}),
])
);
});
@ -222,13 +270,16 @@ describe('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',
}),
])
);
});

View file

@ -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';
@ -44,8 +44,8 @@ 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) => {
@ -53,14 +53,14 @@ export const resetPreconfigurationHandler: FleetRequestHandler<
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;

View file

@ -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,
@ -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

View file

@ -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 {

View file

@ -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,
@ -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) {

View file

@ -16,8 +16,8 @@ export const PutPreconfigurationSchema = {
}),
};
export const PostResetOnePreconfiguredAgentPolicies = {
export const PostResetOnePreconfiguredAgentPoliciesSchema = {
params: schema.object({
agentPolicyid: schema.string(),
agentPolicyId: schema.string(),
}),
};