diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts index b432399553dfb..b8a24a006a674 100644 --- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts @@ -181,6 +181,13 @@ export async function generateEnrollmentAPIKey( .createApiKey({ body: { name, + // @ts-expect-error Metadata in api keys + metadata: { + managed_by: 'fleet', + managed: true, + type: 'enroll', + policy_id: data.agentPolicyId, + }, role_descriptors: { // Useless role to avoid to have the privilege of the user that created the key 'fleet-apikey-enroll': { diff --git a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts index 071f06a3c495b..d9946bb174f5d 100644 --- a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts +++ b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts @@ -115,6 +115,28 @@ export default function (providerContext: FtrProviderContext) { expect(apiResponse.item).to.have.keys('id', 'api_key', 'api_key_id', 'name', 'policy_id'); }); + it('should create an ES ApiKey with metadata', async () => { + const { body: apiResponse } = await supertest + .post(`/api/fleet/enrollment-api-keys`) + .set('kbn-xsrf', 'xxx') + .send({ + policy_id: 'policy1', + }) + .expect(200); + + const { body: apiKeyRes } = await es.security.getApiKey({ + id: apiResponse.item.api_key_id, + }); + + // @ts-expect-error Metadata not yet in the client type + expect(apiKeyRes.api_keys[0].metadata).eql({ + policy_id: 'policy1', + managed_by: 'fleet', + managed: true, + type: 'enroll', + }); + }); + it('should create an ES ApiKey with limited privileges', async () => { const { body: apiResponse } = await supertest .post(`/api/fleet/enrollment-api-keys`)