[Fleet] added format parameter to agent_policies APIs (#191811)

## Summary

Closes https://github.com/elastic/kibana/issues/161625

Support simplified format in `agent_policies` APIs when the response
contains `package_policies`.

API endpoints updated:
```
# Get all
GET kbn:/api/fleet/agent_policies?full=true&format=simplified
# Bulk get
POST kbn:/api/fleet/agent_policies/_bulk_get?format=simplified
     {
      "ids": ["fleet-server-policy"],
      "full": true
     }
# Get one
GET kbn:/api/fleet/agent_policies/fleet-server-policy?format=simplified
# Update
PUT kbn:/api/fleet/agent_policies/fleet-server-policy?format=simplified
    {
      "name": "Fleet Server Policy",
      "namespace": "default"
    }
# Copy
POST kbn:/api/fleet/agent_policies/fleet-server-policy/copy?format=simplified
         {
      "name": "Fleet Server Policy (copy)"
    }

# Example response

{
  "items": [
    {
      "id": "fleet-server-policy",
      "version": "WzIxMzIsMV0=",
      "description": "Fleet Server policy generated by Kibana",
      "is_default_fleet_server": true,
      "monitoring_enabled": [
        "logs",
        "metrics"
      ],
      "inactivity_timeout": 1209600,
      "schema_version": "1.1.1",
      "package_policies": [
        {
          "id": "8cb17156-d295-475e-9ec8-44ef138a5d49",
          "version": "WzIwNzYsMV0=",
          "name": "system-3",
          "namespace": "default",
          "package": {
            "name": "system",
            "title": "System",
            "version": "1.60.3",
            "requires_root": true
          },
          "enabled": true,
          "policy_id": "fleet-server-policy",
          "policy_ids": [
            "fleet-server-policy"
          ],
          "inputs": {
            "system-logfile": {
              "enabled": true,
              "streams": {
                "system.auth": {
                  "enabled": true,
                  "vars": {
                    "ignore_older": "72h",
                    "paths": [
                      "/var/log/auth.log*",
                      "/var/log/secure*"
                    ],
                    "preserve_original_event": false,
                    "tags": [
                      "system-auth"
                    ]
                  }
                },
```

Create and Delete APIs don't return package policies, so didn't change
those.
Also didn't update the
`kbn:/api/fleet/agent_policies/fleet-server-policy/full` path, it has a
different format.


### Checklist

- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
This commit is contained in:
Julia Bardi 2024-08-30 17:07:25 +02:00 committed by GitHub
parent ee28e20de8
commit cd56f4103b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 306 additions and 69 deletions

View file

@ -3417,6 +3417,9 @@
{
"$ref": "#/components/parameters/kuery"
},
{
"$ref": "#/components/parameters/format"
},
{
"schema": {
"type": "boolean"
@ -3488,6 +3491,9 @@
"name": "agentPolicyId",
"in": "path",
"required": true
},
{
"$ref": "#/components/parameters/format"
}
],
"get": {
@ -3576,6 +3582,9 @@
"name": "agentPolicyId",
"in": "path",
"required": true
},
{
"$ref": "#/components/parameters/format"
}
],
"post": {
@ -3830,7 +3839,11 @@
},
"operationId": "bulk-get-agent-policies",
"security": [],
"parameters": []
"parameters": [
{
"$ref": "#/components/parameters/format"
}
]
}
},
"/agent_policies/delete": {
@ -7595,6 +7608,7 @@
},
"policy_id": {
"type": "string",
"nullable": true,
"deprecated": true
},
"policy_ids": {
@ -8285,11 +8299,18 @@
"description": "The package policy namespace. Leave blank to inherit the agent policy's namespace.",
"example": "customnamespace"
},
"output_id": {
"type": "string",
"description": "Output ID to send package data to",
"example": "output-id",
"nullable": true
},
"policy_id": {
"type": "string",
"description": "Agent policy ID where that package policy will be added",
"example": "agent-policy-id",
"deprecated": true
"deprecated": true,
"nullable": true
},
"policy_ids": {
"type": "array",

View file

@ -24,9 +24,9 @@ info:
name: Fleet Team
license:
name: Elastic License 2.0
url: https://www.elastic.co/licensing/elastic-license
url: 'https://www.elastic.co/licensing/elastic-license'
servers:
- url: http://KIBANA_HOST:5601/api/fleet
- url: 'http://KIBANA_HOST:5601/api/fleet'
description: Public and supported Fleet API
paths:
/health_check:
@ -141,7 +141,7 @@ paths:
operationId: update-settings
/settings/enrollment:
servers:
- url: http://KIBANA_HOST:5601/internal/fleet
- url: 'http://KIBANA_HOST:5601/internal/fleet'
description: Used for Fleet internals and not supported
get:
summary: Get enrollment settings
@ -495,7 +495,7 @@ paths:
description: force install to ignore package verification errors
required:
- packages
/epm/packages/{pkgkey}:
'/epm/packages/{pkgkey}':
get:
summary: Get package
tags:
@ -653,7 +653,7 @@ paths:
force:
type: boolean
deprecated: true
/epm/packages/{pkgName}/{pkgVersion}:
'/epm/packages/{pkgName}/{pkgVersion}':
get:
summary: Get package
tags:
@ -881,7 +881,7 @@ paths:
properties:
force:
type: boolean
/epm/packages/{pkgName}/{pkgVersion}/transforms/authorize:
'/epm/packages/{pkgName}/{pkgVersion}/transforms/authorize':
post:
summary: Authorize transforms
tags:
@ -947,7 +947,7 @@ paths:
properties:
transformId:
type: string
/epm/packages/{pkgName}/{pkgVersion}/{filePath}:
'/epm/packages/{pkgName}/{pkgVersion}/{filePath}':
get:
summary: Get package file
tags:
@ -985,7 +985,7 @@ paths:
name: filePath
in: path
required: true
/epm/packages/{pkgName}/stats:
'/epm/packages/{pkgName}/stats':
get:
summary: Get package stats
tags:
@ -1013,7 +1013,7 @@ paths:
name: pkgName
in: path
required: true
/epm/templates/{pkgName}/{pkgVersion}/inputs:
'/epm/templates/{pkgName}/{pkgVersion}/inputs':
get:
summary: Get inputs template
tags:
@ -1333,12 +1333,12 @@ paths:
$ref: '#/components/schemas/bulk_upgrade_agents'
example:
version: 8.4.0
source_uri: https://artifacts.elastic.co/downloads/beats/elastic-agent
source_uri: 'https://artifacts.elastic.co/downloads/beats/elastic-agent'
rollout_duration_seconds: 3600
agents:
- agent1
- agent2
start_time: '2022-08-03T14:00:00.000Z'
start_time: 2022-08-03T14:00:00.000Z
/agents/action_status:
get:
summary: Get agent action status
@ -1454,7 +1454,7 @@ paths:
'400':
$ref: '#/components/responses/error'
operationId: agents-action-status
/agents/{agentId}:
'/agents/{agentId}':
parameters:
- schema:
type: string
@ -1539,7 +1539,7 @@ paths:
operationId: delete-agent
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/agents/{agentId}/actions:
'/agents/{agentId}/actions':
parameters:
- schema:
type: string
@ -1580,7 +1580,7 @@ paths:
properties:
action:
$ref: '#/components/schemas/agent_action'
/agents/actions/{actionId}/cancel:
'/agents/actions/{actionId}/cancel':
parameters:
- schema:
type: string
@ -1606,7 +1606,7 @@ paths:
operationId: agent-action-cancel
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/agents/files/{fileId}/{fileName}:
'/agents/files/{fileId}/{fileName}':
parameters:
- schema:
type: string
@ -1641,7 +1641,7 @@ paths:
'400':
$ref: '#/components/responses/error'
operationId: get-agent-upload-file
/agents/files/{fileId}:
'/agents/files/{fileId}':
parameters:
- schema:
type: string
@ -1670,7 +1670,7 @@ paths:
'400':
$ref: '#/components/responses/error'
operationId: delete-agent-upload-file
/agents/{agentId}/reassign:
'/agents/{agentId}/reassign':
parameters:
- schema:
type: string
@ -1732,7 +1732,7 @@ paths:
required:
- policy_id
deprecated: true
/agents/{agentId}/unenroll:
'/agents/{agentId}/unenroll':
parameters:
- schema:
type: string
@ -1778,7 +1778,7 @@ paths:
type: boolean
force:
type: boolean
/agents/{agentId}/upgrade:
'/agents/{agentId}/upgrade':
parameters:
- schema:
type: string
@ -1807,7 +1807,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/upgrade_agent'
/agents/{agentId}/uploads:
'/agents/{agentId}/uploads':
parameters:
- schema:
type: string
@ -1868,7 +1868,7 @@ paths:
agents:
oneOf:
- type: string
description: KQL query string, leave empty to action all agents
description: 'KQL query string, leave empty to action all agents'
- type: array
items:
type: string
@ -1908,7 +1908,7 @@ paths:
agents:
oneOf:
- type: string
description: KQL query string, leave empty to action all agents
description: 'KQL query string, leave empty to action all agents'
- type: array
items:
type: string
@ -1961,7 +1961,7 @@ paths:
agents:
oneOf:
- type: string
description: KQL query string, leave empty to action all agents
description: 'KQL query string, leave empty to action all agents'
- type: array
items:
type: string
@ -2001,7 +2001,7 @@ paths:
'400':
$ref: '#/components/responses/error'
operationId: get-agent-tags
/agents/{agentId}/request_diagnostics:
'/agents/{agentId}/request_diagnostics':
parameters:
- schema:
type: string
@ -2071,7 +2071,7 @@ paths:
agents:
oneOf:
- type: string
description: KQL query string, leave empty to action all agents
description: 'KQL query string, leave empty to action all agents'
- type: array
items:
type: string
@ -2122,6 +2122,7 @@ paths:
- $ref: '#/components/parameters/page_size'
- $ref: '#/components/parameters/page_index'
- $ref: '#/components/parameters/kuery'
- $ref: '#/components/parameters/format'
- schema:
type: boolean
in: query
@ -2164,13 +2165,14 @@ paths:
security: []
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/agent_policies/{agentPolicyId}:
'/agent_policies/{agentPolicyId}':
parameters:
- schema:
type: string
name: agentPolicyId
in: path
required: true
- $ref: '#/components/parameters/format'
get:
summary: Get agent policy by ID
tags:
@ -2218,13 +2220,14 @@ paths:
$ref: '#/components/schemas/agent_policy_update_request'
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/agent_policies/{agentPolicyId}/copy:
'/agent_policies/{agentPolicyId}/copy':
parameters:
- schema:
type: string
name: agentPolicyId
in: path
required: true
- $ref: '#/components/parameters/format'
post:
summary: Copy agent policy by ID
tags:
@ -2259,7 +2262,7 @@ paths:
required:
- name
description: ''
/agent_policies/{agentPolicyId}/full:
'/agent_policies/{agentPolicyId}/full':
get:
summary: Get full agent policy by ID
tags:
@ -2300,7 +2303,7 @@ paths:
name: kubernetes
in: query
required: false
/agent_policies/{agentPolicyId}/download:
'/agent_policies/{agentPolicyId}/download':
get:
summary: Download agent policy by ID
tags:
@ -2380,7 +2383,8 @@ paths:
$ref: '#/components/responses/error'
operationId: bulk-get-agent-policies
security: []
parameters: []
parameters:
- $ref: '#/components/parameters/format'
/agent_policies/delete:
post:
summary: Delete agent policy by ID
@ -2505,7 +2509,7 @@ paths:
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
deprecated: true
/enrollment-api-keys/{keyId}:
'/enrollment-api-keys/{keyId}':
parameters:
- schema:
type: string
@ -2635,7 +2639,7 @@ paths:
operationId: create-enrollment-api-keys
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/enrollment_api_keys/{keyId}:
'/enrollment_api_keys/{keyId}':
parameters:
- schema:
type: string
@ -2915,7 +2919,7 @@ paths:
- hasErrors
'400':
$ref: '#/components/responses/error'
/package_policies/{packagePolicyId}:
'/package_policies/{packagePolicyId}':
parameters:
- schema:
type: string
@ -3046,7 +3050,7 @@ paths:
schema:
$ref: '#/components/schemas/output_create_request'
operationId: post-outputs
/outputs/{outputId}:
'/outputs/{outputId}':
get:
summary: Get output by ID
tags:
@ -3115,7 +3119,7 @@ paths:
$ref: '#/components/responses/error'
parameters:
- $ref: '#/components/parameters/kbn_xsrf'
/outputs/{outputId}/health:
'/outputs/{outputId}/health':
get:
summary: Get latest output health
tags:
@ -3130,7 +3134,7 @@ paths:
properties:
state:
type: string
description: state of output, HEALTHY or DEGRADED
description: 'state of output, HEALTHY or DEGRADED'
message:
type: string
description: long message if unhealthy
@ -3227,7 +3231,7 @@ paths:
- host
- is_default
operationId: post-download-sources
/agent_download_sources/{sourceId}:
'/agent_download_sources/{sourceId}':
get:
summary: Get agent binary download source by ID
tags:
@ -3380,7 +3384,7 @@ paths:
- name
- host_urls
operationId: post-fleet-server-hosts
/fleet_server_hosts/{itemId}:
'/fleet_server_hosts/{itemId}':
get:
summary: Get Fleet Server host by ID
tags:
@ -3536,7 +3540,7 @@ paths:
- name
- url
operationId: post-fleet-proxies
/proxies/{itemId}:
'/proxies/{itemId}':
get:
summary: Get proxy by ID
tags:
@ -3714,7 +3718,7 @@ paths:
required: false
schema:
type: string
/uninstall_tokens/{uninstallTokenId}:
'/uninstall_tokens/{uninstallTokenId}':
get:
summary: Get one decrypted uninstall token by its ID
tags:
@ -3829,7 +3833,7 @@ components:
with_metrics:
name: withMetrics
in: query
description: Return agent metrics, false by default
description: 'Return agent metrics, false by default'
required: false
schema:
type: boolean
@ -4716,14 +4720,14 @@ components:
agents:
oneOf:
- type: string
description: KQL query string, leave empty to action all agents
description: 'KQL query string, leave empty to action all agents'
- type: array
items:
type: string
description: list of agent IDs
force:
type: boolean
description: Force upgrade, skipping validation (should be used with caution)
description: 'Force upgrade, skipping validation (should be used with caution)'
skipRateLimitCheck:
type: boolean
description: Skip rate limit check for upgrade
@ -4768,7 +4772,7 @@ components:
type: string
force:
type: boolean
description: Force upgrade, skipping validation (should be used with caution)
description: 'Force upgrade, skipping validation (should be used with caution)'
skipRateLimitCheck:
type: boolean
description: Skip rate limit check for upgrade
@ -4859,6 +4863,7 @@ components:
- enabled
policy_id:
type: string
nullable: true
deprecated: true
policy_ids:
type: array
@ -5342,11 +5347,17 @@ components:
The package policy namespace. Leave blank to inherit the agent
policy's namespace.
example: customnamespace
output_id:
type: string
description: Output ID to send package data to
example: output-id
nullable: true
policy_id:
type: string
description: Agent policy ID where that package policy will be added
example: agent-policy-id
deprecated: true
nullable: true
policy_ids:
type: array
items:
@ -5396,7 +5407,7 @@ components:
properties:
enabled:
type: boolean
description: enable or disable that input, (default to true)
description: 'enable or disable that input, (default to true)'
vars:
type: object
description: >-
@ -5412,7 +5423,7 @@ components:
properties:
enabled:
type: boolean
description: enable or disable that stream, (default to true)
description: 'enable or disable that stream, (default to true)'
vars:
type: object
description: >-

View file

@ -32,6 +32,7 @@ get:
- $ref: ../components/parameters/page_size.yaml
- $ref: ../components/parameters/page_index.yaml
- $ref: ../components/parameters/kuery.yaml
- $ref: ../components/parameters/format.yaml
- schema:
type: boolean
in: query

View file

@ -38,4 +38,5 @@ post:
$ref: ../components/responses/error.yaml
operationId: bulk-get-agent-policies
security: []
parameters: []
parameters:
- $ref: ../components/parameters/format.yaml

View file

@ -4,6 +4,7 @@ parameters:
name: agentPolicyId
in: path
required: true
- $ref: ../components/parameters/format.yaml
get:
summary: Get agent policy by ID
tags:

View file

@ -4,6 +4,7 @@ parameters:
name: agentPolicyId
in: path
required: true
- $ref: ../components/parameters/format.yaml
post:
summary: Copy agent policy by ID
tags:

View file

@ -10,6 +10,10 @@ import type { KibanaRequest, RequestHandler, ResponseHeaders } from '@kbn/core/s
import pMap from 'p-map';
import { safeDump } from 'js-yaml';
import { isEmpty } from 'lodash';
import { inputsFormat } from '../../../common/constants';
import { HTTPAuthorizationHeader } from '../../../common/http_authorization_header';
import { fullAgentPolicyToYaml } from '../../../common/services';
@ -52,6 +56,7 @@ import {
} from '../../errors';
import { createAgentPolicyWithPackages } from '../../services/agent_policy_create';
import { updateAgentPolicySpaces } from '../../services/spaces/agent_policy';
import { packagePolicyToSimplifiedPackagePolicy } from '../../../common/services/simplified_package_policy_helper';
export async function populateAssignedAgentsCount(
agentClient: AgentClient,
@ -129,6 +134,7 @@ export const getAgentPoliciesHandler: FleetRequestHandler<
const {
full: withPackagePolicies = false,
noAgentCount = false,
format,
...restOfQuery
} = request.query;
if (!fleetContext.authz.fleet.readAgentPolicies && withPackagePolicies) {
@ -136,20 +142,36 @@ export const getAgentPoliciesHandler: FleetRequestHandler<
'full query parameter require agent policies read permissions'
);
}
const { items, total, page, perPage } = await agentPolicyService.list(soClient, {
const agentPoliciesResponse = await agentPolicyService.list(soClient, {
withPackagePolicies,
esClient,
...restOfQuery,
});
let { items } = agentPoliciesResponse;
const { total, page, perPage } = agentPoliciesResponse;
if (fleetContext.authz.fleet.readAgents && !noAgentCount) {
await populateAssignedAgentsCount(fleetContext.agentClient.asCurrentUser, items);
}
if (!fleetContext.authz.fleet.readAgentPolicies) {
items = items.map(sanitizeItemForReadAgentOnly);
} else if (withPackagePolicies && format === inputsFormat.Simplified) {
items.map((item) => {
if (isEmpty(item.package_policies)) {
return item;
}
return {
...item,
package_policies: item.package_policies!.map((packagePolicy) =>
packagePolicyToSimplifiedPackagePolicy(packagePolicy)
),
};
});
}
const body: GetAgentPoliciesResponse = {
items: !fleetContext.authz.fleet.readAgentPolicies
? items.map(sanitizeItemForReadAgentOnly)
: items,
items,
total,
page,
perPage,
@ -162,21 +184,35 @@ export const getAgentPoliciesHandler: FleetRequestHandler<
export const bulkGetAgentPoliciesHandler: FleetRequestHandler<
undefined,
undefined,
TypeOf<typeof BulkGetAgentPoliciesRequestSchema.query>,
TypeOf<typeof BulkGetAgentPoliciesRequestSchema.body>
> = async (context, request, response) => {
try {
const fleetContext = await context.fleet;
const soClient = fleetContext.internalSoClient;
const { full: withPackagePolicies = false, ignoreMissing = false, ids } = request.body;
const items = await agentPolicyService.getByIDs(soClient, ids, {
let items = await agentPolicyService.getByIDs(soClient, ids, {
withPackagePolicies,
ignoreMissing,
});
if (!fleetContext.authz.fleet.readAgentPolicies) {
items = items.map(sanitizeItemForReadAgentOnly);
} else if (withPackagePolicies && request.query.format === inputsFormat.Simplified) {
items.map((item) => {
if (isEmpty(item.package_policies)) {
return item;
}
return {
...item,
package_policies: item.package_policies!.map((packagePolicy) =>
packagePolicyToSimplifiedPackagePolicy(packagePolicy)
),
};
});
}
const body: BulkGetAgentPoliciesResponse = {
items: !fleetContext.authz.fleet.readAgentPolicies
? items.map(sanitizeItemForReadAgentOnly)
: items,
items,
};
if (fleetContext.authz.fleet.readAgents) {
await populateAssignedAgentsCount(fleetContext.agentClient.asCurrentUser, items);
@ -197,7 +233,8 @@ export const bulkGetAgentPoliciesHandler: FleetRequestHandler<
};
export const getOneAgentPolicyHandler: FleetRequestHandler<
TypeOf<typeof GetOneAgentPolicyRequestSchema.params>
TypeOf<typeof GetOneAgentPolicyRequestSchema.params>,
TypeOf<typeof GetOneAgentPolicyRequestSchema.query>
> = async (context, request, response) => {
try {
const [coreContext, fleetContext] = await Promise.all([context.core, context.fleet]);
@ -208,10 +245,22 @@ export const getOneAgentPolicyHandler: FleetRequestHandler<
if (fleetContext.authz.fleet.readAgents) {
await populateAssignedAgentsCount(fleetContext.agentClient.asCurrentUser, [agentPolicy]);
}
let item: any = agentPolicy;
if (!fleetContext.authz.fleet.readAgentPolicies) {
item = sanitizeItemForReadAgentOnly(agentPolicy);
} else if (
request.query.format === inputsFormat.Simplified &&
!isEmpty(agentPolicy.package_policies)
) {
item = {
...agentPolicy,
package_policies: agentPolicy.package_policies!.map((packagePolicy) =>
packagePolicyToSimplifiedPackagePolicy(packagePolicy)
),
};
}
const body: GetOneAgentPolicyResponse = {
item: !fleetContext.authz.fleet.readAgentPolicies
? sanitizeItemForReadAgentOnly(agentPolicy)
: agentPolicy,
item,
};
return response.ok({
body,
@ -303,7 +352,7 @@ export const createAgentPolicyHandler: FleetRequestHandler<
export const updateAgentPolicyHandler: FleetRequestHandler<
TypeOf<typeof UpdateAgentPolicyRequestSchema.params>,
unknown,
TypeOf<typeof UpdateAgentPolicyRequestSchema.query>,
TypeOf<typeof UpdateAgentPolicyRequestSchema.body>
> = async (context, request, response) => {
const coreContext = await context.core;
@ -338,7 +387,20 @@ export const updateAgentPolicyHandler: FleetRequestHandler<
{ force, user, spaceId }
);
const body: UpdateAgentPolicyResponse = { item: agentPolicy };
let item: any = agentPolicy;
if (
request.query.format === inputsFormat.Simplified &&
!isEmpty(agentPolicy.package_policies)
) {
item = {
...agentPolicy,
package_policies: agentPolicy.package_policies!.map((packagePolicy) =>
packagePolicyToSimplifiedPackagePolicy(packagePolicy)
),
};
}
const body: UpdateAgentPolicyResponse = { item };
return response.ok({
body,
});
@ -355,7 +417,7 @@ export const updateAgentPolicyHandler: FleetRequestHandler<
export const copyAgentPolicyHandler: RequestHandler<
TypeOf<typeof CopyAgentPolicyRequestSchema.params>,
unknown,
TypeOf<typeof CopyAgentPolicyRequestSchema.query>,
TypeOf<typeof CopyAgentPolicyRequestSchema.body>
> = async (context, request, response) => {
const coreContext = await context.core;
@ -371,7 +433,20 @@ export const copyAgentPolicyHandler: RequestHandler<
{ user }
);
const body: CopyAgentPolicyResponse = { item: agentPolicy };
let item: any = agentPolicy;
if (
request.query.format === inputsFormat.Simplified &&
!isEmpty(agentPolicy.package_policies)
) {
item = {
...agentPolicy,
package_policies: agentPolicy.package_policies!.map((packagePolicy) =>
packagePolicyToSimplifiedPackagePolicy(packagePolicy)
),
};
}
const body: CopyAgentPolicyResponse = { item };
return response.ok({
body,
});

View file

@ -8,7 +8,7 @@
import { schema } from '@kbn/config-schema';
import { NewAgentPolicySchema } from '../models';
import { inputsFormat } from '../../../common/constants';
import { LEGACY_AGENT_POLICY_SAVED_OBJECT_TYPE, AGENT_POLICY_MAPPINGS } from '../../constants';
import { validateKuery } from '../../routes/utils/filter_utils';
@ -39,6 +39,9 @@ export const GetAgentPoliciesRequestSchema = {
),
noAgentCount: schema.maybe(schema.boolean()),
full: schema.maybe(schema.boolean()),
format: schema.maybe(
schema.oneOf([schema.literal(inputsFormat.Simplified), schema.literal(inputsFormat.Legacy)])
),
}),
};
@ -46,12 +49,22 @@ export const BulkGetAgentPoliciesRequestSchema = {
body: BulkRequestBodySchema.extends({
full: schema.maybe(schema.boolean()),
}),
query: schema.object({
format: schema.maybe(
schema.oneOf([schema.literal(inputsFormat.Simplified), schema.literal(inputsFormat.Legacy)])
),
}),
};
export const GetOneAgentPolicyRequestSchema = {
params: schema.object({
agentPolicyId: schema.string(),
}),
query: schema.object({
format: schema.maybe(
schema.oneOf([schema.literal(inputsFormat.Simplified), schema.literal(inputsFormat.Legacy)])
),
}),
};
export const CreateAgentPolicyRequestSchema = {

View file

@ -38,16 +38,78 @@ export default function (providerContext: FtrProviderContext) {
describe('fleet_agent_policies', () => {
skipIfNoDockerRegistry(providerContext);
let agentPolicyWithPPId: string;
async function createAgentPolicyWithPackagePolicy() {
const { body: agentPolicyResponse } = await supertest
.post(`/api/fleet/agent_policies`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'Test policy 1',
namespace: 'default',
})
.expect(200);
agentPolicyWithPPId = agentPolicyResponse.item.id;
await supertest
.post(`/api/fleet/package_policies`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'filetest-1',
description: '',
namespace: 'default',
policy_id: agentPolicyWithPPId,
enabled: true,
inputs: [
{
enabled: true,
streams: [],
type: 'single_input',
},
],
package: {
name: 'single_input_no_streams',
version: '0.1.0',
},
});
}
describe('GET /api/fleet/agent_policies', () => {
before(async () => {
await esArchiver.load('x-pack/test/functional/es_archives/fleet/empty_fleet_server');
await kibanaServer.savedObjects.cleanStandardList();
await fleetAndAgents.setup();
await createAgentPolicyWithPackagePolicy();
});
after(async () => {
await supertest
.post(`/api/fleet/agent_policies/delete`)
.set('kbn-xsrf', 'xxxx')
.send({ agentPolicyId: agentPolicyWithPPId })
.expect(200);
});
it('should get list agent policies', async () => {
await supertest.get(`/api/fleet/agent_policies`).expect(200);
});
it('should get list agent policies simplified format', async () => {
const { body } = await supertest
.get(`/api/fleet/agent_policies?full=true&format=simplified`)
.expect(200);
expect(body.items[0].package_policies[0].inputs).to.eql({
single_input: { enabled: true, streams: {} },
});
});
it('should get one agent policy simplified format', async () => {
const { body } = await supertest
.get(`/api/fleet/agent_policies/${agentPolicyWithPPId}?format=simplified`)
.expect(200);
expect(body.item.package_policies[0].inputs).to.eql({
single_input: { enabled: true, streams: {} },
});
});
it('should get a list of agent policies by kuery', async () => {
await supertest
.post(`/api/fleet/agent_policies`)
@ -476,6 +538,8 @@ export default function (providerContext: FtrProviderContext) {
before(async () => {
await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/fleet/agents');
await fleetAndAgents.setup();
await createAgentPolicyWithPackagePolicy();
createdPolicyIds.push(agentPolicyWithPPId!);
});
const createdPolicyIds: string[] = [];
after(async () => {
@ -534,6 +598,20 @@ export default function (providerContext: FtrProviderContext) {
});
});
it('should copy with simplified format', async () => {
const { body } = await supertest
.post(`/api/fleet/agent_policies/${agentPolicyWithPPId}/copy?format=simplified`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'Test policy (copy)',
description: '',
})
.expect(200);
expect(body.item.package_policies[0].inputs).to.eql({
single_input: { enabled: true, streams: {} },
});
});
it('should copy inactivity timeout', async () => {
const {
body: { item: policyWithTimeout },
@ -906,6 +984,8 @@ export default function (providerContext: FtrProviderContext) {
before(async () => {
await esArchiver.load('x-pack/test/functional/es_archives/fleet/empty_fleet_server');
await kibanaServer.savedObjects.cleanStandardList();
await createAgentPolicyWithPackagePolicy();
createdPolicyIds.push(agentPolicyWithPPId!);
});
const createdPolicyIds: string[] = [];
after(async () => {
@ -967,6 +1047,20 @@ export default function (providerContext: FtrProviderContext) {
});
});
it('should update with simplified format', async () => {
const { body } = await supertest
.put(`/api/fleet/agent_policies/${agentPolicyWithPPId}?format=simplified`)
.set('kbn-xsrf', 'xxxx')
.send({
name: 'Test policy updated',
namespace: 'default',
})
.expect(200);
expect(body.item.package_policies[0].inputs).to.eql({
single_input: { enabled: true, streams: {} },
});
});
it('should support empty space_ids', async () => {
const {
body: { item: originalPolicy },
@ -1139,9 +1233,8 @@ export default function (providerContext: FtrProviderContext) {
const listResponse = await fetchPackageList();
const installedPackages = listResponse.items.filter(
(item: any) => item.status === 'installed'
(item: any) => item.status === 'installed' && item.name === 'elastic_agent'
);
expect(installedPackages.length).to.be(0);
agentPolicyId = originalPolicy.id;
const {
@ -1460,6 +1553,7 @@ export default function (providerContext: FtrProviderContext) {
before(async () => {
await esArchiver.load('x-pack/test/functional/es_archives/fleet/empty_fleet_server');
await fleetAndAgents.setup();
await createAgentPolicyWithPackagePolicy();
});
before(async () => {
const getPkRes = await getPackage('system');
@ -1488,6 +1582,11 @@ export default function (providerContext: FtrProviderContext) {
.post('/api/fleet/agent_policies/delete')
.set('kbn-xsrf', 'xxx')
.send({ agentPolicyId: policyId });
await supertest
.post(`/api/fleet/agent_policies/delete`)
.set('kbn-xsrf', 'xxxx')
.send({ agentPolicyId: agentPolicyWithPPId })
.expect(200);
await esArchiver.unload('x-pack/test/functional/es_archives/fleet/empty_fleet_server');
});
@ -1550,6 +1649,20 @@ export default function (providerContext: FtrProviderContext) {
}).toMatch();
});
it('should bulk get with simplified format', async () => {
const { body } = await supertest
.post(`/api/fleet/agent_policies/_bulk_get?format=simplified`)
.set('kbn-xsrf', 'xxxx')
.send({
ids: [agentPolicyWithPPId!],
full: true,
})
.expect(200);
expect(body.items[0].package_policies[0].inputs).to.eql({
single_input: { enabled: true, streams: {} },
});
});
it('should return a 404 with invalid ids', async () => {
await supertest
.post(`/api/fleet/agent_policies/_bulk_get`)