Skip to content

Commit

Permalink
[Fleet] Fix reset one preconfiguration API
Browse files Browse the repository at this point in the history
  • Loading branch information
nchaulet committed Jan 13, 2022
1 parent 0da9156 commit e9e3025
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('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('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('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('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('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('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('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 @@ -44,23 +44,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<
export const resetPreconfigurationHandler: FleetRequestHandler<
undefined,
undefined,
undefined
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 @@ -6,7 +6,10 @@
*/

import { PRECONFIGURATION_API_ROUTES } from '../../constants';
import { PutPreconfigurationSchema } from '../../types';
import {
PutPreconfigurationSchema,
PostResetOnePreconfiguredAgentPoliciesSchema,
} from '../../types';
import type { FleetAuthzRouter } from '../security';

import {
Expand All @@ -29,7 +32,7 @@ export const registerRoutes = (router: FleetAuthzRouter) => {
router.post(
{
path: PRECONFIGURATION_API_ROUTES.RESET_ONE_PATTERN,
validate: false,
validate: PostResetOnePreconfiguredAgentPoliciesSchema,
fleetAuthz: {
fleet: { all: true },
},
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 e9e3025

Please sign in to comment.