diff --git a/src/platform/packages/shared/kbn-test/src/kbn_client/kbn_client_saved_objects.ts b/src/platform/packages/shared/kbn-test/src/kbn_client/kbn_client_saved_objects.ts index 620572ba23dea..4744f81e97332 100644 --- a/src/platform/packages/shared/kbn-test/src/kbn_client/kbn_client_saved_objects.ts +++ b/src/platform/packages/shared/kbn-test/src/kbn_client/kbn_client_saved_objects.ts @@ -111,6 +111,7 @@ const STANDARD_LIST_TYPES = [ 'uptime-dynamic-settings', 'synthetics-privates-locations', 'synthetics-private-location', + 'synthetics-param', 'osquery-saved-query', 'osquery-pack', diff --git a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_private_locations.ts b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_private_locations.ts index 344a52f1195ec..294a2ea086b0b 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_private_locations.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_private_locations.ts @@ -22,11 +22,12 @@ import { } from '../runtime_types/private_locations'; export const getPrivateLocations = async ( - client: SavedObjectsClientContract + client: SavedObjectsClientContract, + spaceId?: string ): Promise => { try { const [results, legacyLocations] = await Promise.all([ - getNewPrivateLocations(client), + getNewPrivateLocations(client, spaceId), getLegacyPrivateLocations(client), ]); @@ -39,10 +40,11 @@ export const getPrivateLocations = async ( } }; -const getNewPrivateLocations = async (client: SavedObjectsClientContract) => { +const getNewPrivateLocations = async (client: SavedObjectsClientContract, spaceId?: string) => { const finder = client.createPointInTimeFinder({ type: privateLocationSavedObjectName, perPage: 1000, + ...(spaceId ? { namespaces: [spaceId] } : {}), }); const results: Array< diff --git a/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.test.ts b/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.test.ts index ed21e5520e2ff..d647e40886d27 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.test.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.test.ts @@ -454,7 +454,7 @@ describe('runSynPrivateLocationMonitorsTaskSoon', () => { const error = new Error('Failed to run soon'); mockTaskManagerStart.runSoon.mockRejectedValue(error); - await runSynPrivateLocationMonitorsTaskSoon({ server: mockServerSetup as any }); + await runSynPrivateLocationMonitorsTaskSoon({ server: mockServerSetup as any, retries: 0 }); expect(mockLogger.error).toHaveBeenCalledWith( `Error scheduling Synthetics sync private location monitors task: ${error.message}`, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.ts b/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.ts index 012b3554a6d62..62cb08b95a278 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/tasks/sync_private_locations_monitors_task.ts @@ -15,6 +15,7 @@ import { ALL_SPACES_ID } from '@kbn/spaces-plugin/common/constants'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; import moment from 'moment'; import { MAINTENANCE_WINDOW_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/common'; +import pRetry from 'p-retry'; import { syntheticsParamType } from '../../common/types/saved_objects'; import { normalizeSecrets } from '../synthetics_service/utils'; import type { PrivateLocationAttributes } from '../runtime_types/private_locations'; @@ -92,7 +93,7 @@ export class SyncPrivateLocationMonitorsTask { const soClient = savedObjects.createInternalRepository([ MAINTENANCE_WINDOW_SAVED_OBJECT_TYPE, ]); - const allPrivateLocations = await getPrivateLocations(soClient); + const allPrivateLocations = await getPrivateLocations(soClient, ALL_SPACES_ID); const { totalMWs, totalParams, hasDataChanged } = await this.hasAnyDataChanged({ soClient, taskInstance, @@ -384,19 +385,28 @@ export class SyncPrivateLocationMonitorsTask { export const runSynPrivateLocationMonitorsTaskSoon = async ({ server, + retries = 5, }: { server: SyntheticsServerSetup; + retries?: number; }) => { - const { - logger, - pluginsStart: { taskManager }, - } = server; try { - logger.debug(`Scheduling Synthetics sync private location monitors task soon`); - await taskManager.runSoon(TASK_ID); - logger.debug(`Synthetics sync private location task scheduled successfully`); + await pRetry( + async () => { + const { + logger, + pluginsStart: { taskManager }, + } = server; + logger.debug(`Scheduling Synthetics sync private location monitors task soon`); + await taskManager.runSoon(TASK_ID); + logger.debug(`Synthetics sync private location task scheduled successfully`); + }, + { + retries, + } + ); } catch (error) { - logger.error( + server.logger.error( `Error scheduling Synthetics sync private location monitors task: ${error.message}`, { error } ); diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor.ts index 40368e7d350e5..93a67dfc8d034 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor.ts @@ -5,7 +5,6 @@ * 2.0. */ import expect from '@kbn/expect'; -import moment from 'moment/moment'; import { v4 as uuidv4 } from 'uuid'; import { omit, omitBy } from 'lodash'; import { format as formatUrl } from 'url'; @@ -22,29 +21,6 @@ import { import { FtrProviderContext } from '../../ftr_provider_context'; import { getFixtureJson } from './helper/get_fixture_json'; -export const addMonitorAPIHelper = async (supertestAPI: any, monitor: any, statusCode = 200) => { - const result = await supertestAPI - .post(SYNTHETICS_API_URLS.SYNTHETICS_MONITORS) - .set('kbn-xsrf', 'true') - .send(monitor); - - expect(result.status).eql(statusCode, JSON.stringify(result.body)); - - if (statusCode === 200) { - const { created_at: createdAt, updated_at: updatedAt, id, config_id: configId } = result.body; - expect(id).not.empty(); - expect(configId).not.empty(); - expect([createdAt, updatedAt].map((d) => moment(d).isValid())).eql([true, true]); - return { - rawBody: result.body, - body: { - ...omit(result.body, ['created_at', 'updated_at', 'id', 'config_id', 'form_monitor_type']), - }, - }; - } - return result.body; -}; - export const keyToOmitList = [ 'created_at', 'updated_at', diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_private_location.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_private_location.ts index bd26fa7e4f5b9..ef4a78d24b836 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_private_location.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_private_location.ts @@ -54,7 +54,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('add a test private location', async () => { - pvtLoc = await testPrivateLocations.addPrivateLocation(); + pvtLoc = await testPrivateLocations.createPrivateLocation(); testFleetPolicyID = pvtLoc.agentPolicyId; const apiResponse = await supertestAPI.get(SYNTHETICS_API_URLS.SERVICE_LOCATIONS); diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_project.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_project.ts index a39289bf04331..62012320e5063 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_project.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/add_monitor_project.ts @@ -68,7 +68,7 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'true') .expect(200); await testPrivateLocations.installSyntheticsPackage(); - await testPrivateLocations.addPrivateLocation(); + await testPrivateLocations.createPrivateLocation(); await supertest .post(SYNTHETICS_API_URLS.PARAMS) diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/edit_monitor.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/edit_monitor.ts index ad7047ca39b41..57916b69714c4 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/edit_monitor.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/edit_monitor.ts @@ -57,7 +57,7 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'true') .expect(200); - const loc = await testPrivateLocations.addPrivateLocation(); + const loc = await testPrivateLocations.createPrivateLocation(); testPolicyId = loc.id; }); diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/index.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/index.ts index 4b9a5851351ed..5a44d2dd865e1 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/index.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/index.ts @@ -23,6 +23,7 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./add_monitor_private_location')); loadTestFile(require.resolve('./edit_monitor')); loadTestFile(require.resolve('./sync_global_params')); + loadTestFile(require.resolve('./sync_global_params_spaces')); loadTestFile(require.resolve('./add_edit_params')); loadTestFile(require.resolve('./private_location_apis')); loadTestFile(require.resolve('./list_monitors')); diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/private_location_apis.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/private_location_apis.ts index 7f55ef4cf064f..9dd6f6daf3dd0 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/private_location_apis.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/private_location_apis.ts @@ -42,7 +42,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('adds a test private location', async () => { - await testPrivateLocations.addPrivateLocation(); + await testPrivateLocations.createPrivateLocation(); }); it('list all locations', async () => { diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/private_location_test_service.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/private_location_test_service.ts index 537cb66fdb887..d494c4f738625 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/private_location_test_service.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/private_location_test_service.ts @@ -12,6 +12,8 @@ import { legacyPrivateLocationsSavedObjectId, legacyPrivateLocationsSavedObjectName, } from '@kbn/synthetics-plugin/common/saved_objects/private_locations'; +import { PackagePolicy } from '@kbn/fleet-plugin/common'; +import { omit } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; export const INSTALLED_VERSION = '1.4.2'; @@ -53,7 +55,11 @@ export class PrivateLocationTestService { .expect(200); } - async addPrivateLocation({ policyId, label }: { policyId?: string; label?: string } = {}) { + async createPrivateLocation({ + policyId, + label, + spaceId, + }: { policyId?: string; label?: string; spaceId?: string } = {}) { let agentPolicyId = policyId; if (!agentPolicyId) { @@ -68,6 +74,7 @@ export class PrivateLocationTestService { lat: 0, lon: 0, }, + ...(spaceId ? { spaces: [spaceId] } : {}), }; const response = await this.supertest @@ -79,6 +86,10 @@ export class PrivateLocationTestService { const { isInvalid, ...loc } = response.body; + if (spaceId) { + return omit(loc, ['spaces']); + } + return loc; } @@ -121,4 +132,22 @@ export class PrivateLocationTestService { .set('kbn-xsrf', 'true') .expect(200); } + + async getPackagePolicy({ + monitorId, + locId, + spaceId = 'default', + }: { + monitorId: string; + locId: string; + spaceId?: string; + }) { + const apiResponse = await this.supertest.get( + '/api/fleet/package_policies?page=1&perPage=2000&kuery=ingest-package-policies.package.name%3A%20synthetics' + ); + + return apiResponse.body.items.find( + (pkgPolicy: PackagePolicy) => pkgPolicy.id === `${monitorId}-${locId}-${spaceId}` + ); + } } diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/synthetics_monitor_test_service.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/synthetics_monitor_test_service.ts index c959955a08b82..d0619cbe51149 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/synthetics_monitor_test_service.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/services/synthetics_monitor_test_service.ts @@ -6,12 +6,8 @@ */ import { SYNTHETICS_API_URLS } from '@kbn/synthetics-plugin/common/constants'; -import { legacySyntheticsMonitorTypeSingle } from '@kbn/synthetics-plugin/common/types/saved_objects'; -import { EncryptedSyntheticsSavedMonitor } from '@kbn/synthetics-plugin/common/runtime_types'; -import { MonitorInspectResponse } from '@kbn/synthetics-plugin/public/apps/synthetics/state/monitor_management/api'; import { v4 as uuidv4 } from 'uuid'; import expect from '@kbn/expect'; -import { ProjectAPIKeyResponse } from '@kbn/synthetics-plugin/server/routes/monitor_cruds/get_api_key'; import moment from 'moment/moment'; import { omit } from 'lodash'; import { KibanaSupertestProvider } from '@kbn/ftr-common-functional-services'; @@ -20,33 +16,14 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export class SyntheticsMonitorTestService { private supertest: ReturnType; private getService: FtrProviderContext['getService']; - private supertestWithoutAuth: ReturnType; public apiKey: string | undefined = ''; constructor(getService: FtrProviderContext['getService']) { this.supertest = getService('supertest'); this.supertest = getService('supertest'); this.getService = getService; - this.supertestWithoutAuth = getService('supertestWithoutAuth'); } - generateProjectAPIKey = async (accessToPublicLocations = true) => { - const res = await this.supertest - .get( - SYNTHETICS_API_URLS.SYNTHETICS_PROJECT_APIKEY + - '?accessToElasticManagedLocations=' + - accessToPublicLocations - ) - .set('kbn-xsrf', 'true') - .expect(200); - const result = res.body as ProjectAPIKeyResponse; - expect(result).to.have.property('apiKey'); - const apiKey = result.apiKey?.encoded; - expect(apiKey).to.not.be.empty(); - this.apiKey = apiKey; - return apiKey; - }; - async getMonitor( monitorId: string, { @@ -99,80 +76,40 @@ export class SyntheticsMonitorTestService { return apiResponse.body; } - async addMonitor(monitor: any) { - const res = await this.supertest - .post(SYNTHETICS_API_URLS.SYNTHETICS_MONITORS) - .set('kbn-xsrf', 'true') - .send(monitor) - .expect(200); - - return res.body as EncryptedSyntheticsSavedMonitor; - } - - async inspectMonitor(monitor: any, hideParams: boolean = true) { - const res = await this.supertest - .post(SYNTHETICS_API_URLS.SYNTHETICS_MONITOR_INSPECT) - .set('kbn-xsrf', 'true') - .send(monitor) - .expect(200); - - // remove the id and config_id from the response - delete res.body.result?.publicConfigs?.[0].monitors[0].id; - delete res.body.result?.publicConfigs?.[0].monitors[0].streams[0].id; - delete res.body.result?.publicConfigs?.[0].monitors[0].streams[0].config_id; - delete res.body.result?.publicConfigs?.[0].monitors[0].streams[0].fields.config_id; - delete res.body.result?.publicConfigs?.[0].output.api_key; - delete res.body.result?.publicConfigs?.[0].license_issued_to; - delete res.body.result?.publicConfigs?.[0].stack_version; - - return res.body as { result: MonitorInspectResponse; decodedCode: string }; - } - - async addProjectMonitors(project: string, monitors: any) { - if (this.apiKey) { - return this.supertestWithoutAuth - .put( - SYNTHETICS_API_URLS.SYNTHETICS_MONITORS_PROJECT_UPDATE.replace('{projectName}', project) - ) - .set('kbn-xsrf', 'true') - .set('authorization', `ApiKey ${this.apiKey}`) - .send({ monitors }); - } else { - return this.supertest - .put( - SYNTHETICS_API_URLS.SYNTHETICS_MONITORS_PROJECT_UPDATE.replace('{projectName}', project) - ) - .set('kbn-xsrf', 'true') - .send({ monitors }); - } - } + async createMonitor({ + monitor, + spaceId, + statusCode = 200, + }: { + monitor: any; + statusCode?: number; + spaceId?: string; + }) { + let url = SYNTHETICS_API_URLS.SYNTHETICS_MONITORS as string; + if (spaceId) url = `/s/${spaceId}` + url; + const result = await this.supertest.post(url).set('kbn-xsrf', 'true').send(monitor); + + expect(result.status).eql(statusCode, JSON.stringify(result.body)); - async deleteMonitorByJourney( - projectMonitors: any, - journeyId: string, - projectId: string, - space: string = 'default' - ) { - try { - const response = await this.supertest - .get(`/s/${space}${SYNTHETICS_API_URLS.SYNTHETICS_MONITORS}`) - .query({ - filter: `${legacySyntheticsMonitorTypeSingle}.attributes.journey_id: "${journeyId}" AND ${legacySyntheticsMonitorTypeSingle}.attributes.project_id: "${projectId}"`, - }) - .set('kbn-xsrf', 'true') - .expect(200); - const { monitors } = response.body; - if (monitors[0]?.id) { - await this.supertest - .delete(`/s/${space}${SYNTHETICS_API_URLS.SYNTHETICS_MONITORS}/${monitors[0].id}`) - .set('kbn-xsrf', 'true') - .send(projectMonitors) - .expect(200); - } - } catch (e) { - // eslint-disable-next-line no-console - console.error(e); + if (statusCode === 200) { + const { created_at: createdAt, updated_at: updatedAt, id, config_id: configId } = result.body; + expect(id).not.empty(); + expect(configId).not.empty(); + expect([createdAt, updatedAt].map((d) => moment(d).isValid())).eql([true, true]); + return { + rawBody: result.body, + body: { + ...omit(result.body, [ + 'created_at', + 'updated_at', + 'id', + 'config_id', + 'form_monitor_type', + ]), + }, + }; } + return result.body; } async addsNewSpace(uptimePermissions: string[] = ['all']) { @@ -218,30 +155,4 @@ export class SyntheticsMonitorTestService { expect(deleteResponse.status).to.eql(statusCode); return deleteResponse; } - - async deleteMonitorByIdParam(monitorId?: string, statusCode = 200, spaceId?: string) { - const deleteResponse = await this.supertest - .delete( - spaceId - ? `/s/${spaceId}${SYNTHETICS_API_URLS.SYNTHETICS_MONITORS}/${monitorId}` - : SYNTHETICS_API_URLS.SYNTHETICS_MONITORS + '/' + monitorId - ) - .send() - .set('kbn-xsrf', 'true'); - expect(deleteResponse.status).to.eql(statusCode); - return deleteResponse; - } - - async deleteMonitorBulk(monitorIds: string[], statusCode = 200, spaceId?: string) { - const deleteResponse = await this.supertest - .post( - spaceId - ? `/s/${spaceId}${SYNTHETICS_API_URLS.SYNTHETICS_MONITORS}/_bulk_delete` - : SYNTHETICS_API_URLS.SYNTHETICS_MONITORS + '/_bulk_delete' - ) - .send({ ids: monitorIds }) - .set('kbn-xsrf', 'true'); - expect(deleteResponse.status).to.eql(statusCode); - return deleteResponse; - } } diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params.ts index b7fee543e7015..d381c5496e623 100644 --- a/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params.ts +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params.ts @@ -16,11 +16,12 @@ import { SYNTHETICS_API_URLS } from '@kbn/synthetics-plugin/common/constants'; import { PackagePolicy } from '@kbn/fleet-plugin/common'; import expect from '@kbn/expect'; import { syntheticsParamType } from '@kbn/synthetics-plugin/common/types/saved_objects'; +import { SyntheticsMonitorTestService } from './services/synthetics_monitor_test_service'; import { FtrProviderContext } from '../../ftr_provider_context'; import { getFixtureJson } from './helper/get_fixture_json'; import { PrivateLocationTestService } from './services/private_location_test_service'; import { comparePolicies, getTestSyntheticsPolicy } from './sample_data/test_policy'; -import { addMonitorAPIHelper, omitMonitorKeys } from './add_monitor'; +import { omitMonitorKeys } from './add_monitor'; export const LOCAL_LOCATION = { id: 'dev', @@ -47,15 +48,13 @@ export default function ({ getService }: FtrProviderContext) { let _httpMonitorJson: HTTPFields; let httpMonitorJson: HTTPFields; - let newMonitorId: string; + let newBrowserMonitorId: string; let newHttpMonitorId: string; const testPrivateLocations = new PrivateLocationTestService(getService); - const params: Record = {}; + const monitorTestService = new SyntheticsMonitorTestService(getService); - const addMonitorAPI = async (monitor: any, statusCode = 200) => { - return addMonitorAPIHelper(supertestAPI, monitor, statusCode); - }; + const params: Record = {}; before(async () => { await kServer.savedObjects.cleanStandardList(); @@ -71,12 +70,10 @@ export default function ({ getService }: FtrProviderContext) { httpMonitorJson = _httpMonitorJson; }); - it('add a test private location', async () => { - loc = await testPrivateLocations.addPrivateLocation(); + it('create test private location', async () => { + loc = await testPrivateLocations.createPrivateLocation(); testFleetPolicyID = loc.agentPolicyId; - const apiResponse = await supertestAPI.get(SYNTHETICS_API_URLS.SERVICE_LOCATIONS); - const testLocations: Array = [ { id: 'dev', @@ -109,7 +106,6 @@ export default function ({ getService }: FtrProviderContext) { spaces: ['*'], }, ]; - expect(apiResponse.body.locations).eql(testLocations); }); @@ -129,7 +125,7 @@ export default function ({ getService }: FtrProviderContext) { newMonitor.locations.push(pvtLoc); - const apiResponse = await addMonitorAPI(newMonitor); + const apiResponse = await monitorTestService.createMonitor({ monitor: newMonitor }); expect(apiResponse.body).eql( omitMonitorKeys({ @@ -140,28 +136,22 @@ export default function ({ getService }: FtrProviderContext) { spaces: ['default'], }) ); - newMonitorId = apiResponse.rawBody.id; + newBrowserMonitorId = apiResponse.rawBody.id; }); it('added an integration for previously added monitor', async () => { - const apiResponse = await supertestAPI.get( - '/api/fleet/package_policies?page=1&perPage=2000&kuery=ingest-package-policies.package.name%3A%20synthetics' - ); - - const packagePolicy = apiResponse.body.items.find( - (pkgPolicy: PackagePolicy) => pkgPolicy.id === newMonitorId + '-' + loc.id + '-default' - ); + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: loc.id, + }); - expect(packagePolicy?.policy_id).eql( - testFleetPolicyID, - JSON.stringify({ testFleetPolicyID, newMonitorId }) - ); + expect(packagePolicy?.policy_id).eql(testFleetPolicyID); comparePolicies( packagePolicy, getTestSyntheticsPolicy({ name: browserMonitorJson.name, - id: newMonitorId, + id: newBrowserMonitorId, isBrowser: true, location: { id: testFleetPolicyID }, }) @@ -203,7 +193,8 @@ export default function ({ getService }: FtrProviderContext) { ); const packagePolicy = apiResponse.body.items.find( - (pkgPolicy: PackagePolicy) => pkgPolicy.id === newMonitorId + '-' + loc.id + '-default' + (pkgPolicy: PackagePolicy) => + pkgPolicy.id === newBrowserMonitorId + '-' + loc.id + '-default' ); expect(packagePolicy.policy_id).eql(testFleetPolicyID); @@ -212,7 +203,7 @@ export default function ({ getService }: FtrProviderContext) { packagePolicy, getTestSyntheticsPolicy({ name: browserMonitorJson.name, - id: newMonitorId, + id: newBrowserMonitorId, params, isBrowser: true, location: { id: testFleetPolicyID }, @@ -236,7 +227,7 @@ export default function ({ getService }: FtrProviderContext) { newMonitor.proxy_url = '${test}'; - const apiResponse = await addMonitorAPI(newMonitor); + const apiResponse = await monitorTestService.createMonitor({ monitor: newMonitor }); expect(apiResponse.body).eql( omitMonitorKeys({ @@ -251,13 +242,10 @@ export default function ({ getService }: FtrProviderContext) { }); it('parsed params for previously added http monitors', async () => { - const apiResponse = await supertestAPI.get( - '/api/fleet/package_policies?page=1&perPage=2000&kuery=ingest-package-policies.package.name%3A%20synthetics' - ); - - const packagePolicy = apiResponse.body.items.find( - (pkgPolicy: PackagePolicy) => pkgPolicy.id === newHttpMonitorId + '-' + loc.id + '-default' - ); + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newHttpMonitorId, + locId: loc.id, + }); expect(packagePolicy.policy_id).eql(testFleetPolicyID); @@ -303,13 +291,29 @@ export default function ({ getService }: FtrProviderContext) { expect(getResponseAfterDelete.body.length).eql(0); - const apiResponse = await supertestAPI.get( - '/api/fleet/package_policies?page=1&perPage=2000&kuery=ingest-package-policies.package.name%3A%20synthetics' - ); + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: loc.id, + }); - const packagePolicy = apiResponse.body.items.find( - (pkgPolicy: PackagePolicy) => pkgPolicy.id === newMonitorId + '-' + loc.id + '-default' + expect(packagePolicy.policy_id).eql(testFleetPolicyID); + + comparePolicies( + packagePolicy, + getTestSyntheticsPolicy({ + name: browserMonitorJson.name, + id: newBrowserMonitorId, + isBrowser: true, + location: { id: loc.id }, + }) ); + }); + + it('check browser monitor again after deleting params', async () => { + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: loc.id, + }); expect(packagePolicy.policy_id).eql(testFleetPolicyID); @@ -317,7 +321,7 @@ export default function ({ getService }: FtrProviderContext) { packagePolicy, getTestSyntheticsPolicy({ name: browserMonitorJson.name, - id: newMonitorId, + id: newBrowserMonitorId, isBrowser: true, location: { id: loc.id }, }) diff --git a/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params_spaces.ts b/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params_spaces.ts new file mode 100644 index 0000000000000..15acfafa7e47e --- /dev/null +++ b/x-pack/solutions/observability/test/api_integration/apis/synthetics/sync_global_params_spaces.ts @@ -0,0 +1,213 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { + ConfigKey, + HTTPFields, + PrivateLocation, + SyntheticsParams, +} from '@kbn/synthetics-plugin/common/runtime_types'; +import { SYNTHETICS_API_URLS } from '@kbn/synthetics-plugin/common/constants'; +import expect from '@kbn/expect'; +import { SyntheticsMonitorTestService } from './services/synthetics_monitor_test_service'; +import { FtrProviderContext } from '../../ftr_provider_context'; +import { getFixtureJson } from './helper/get_fixture_json'; +import { PrivateLocationTestService } from './services/private_location_test_service'; +import { comparePolicies, getTestSyntheticsPolicy } from './sample_data/test_policy'; +import { omitMonitorKeys } from './add_monitor'; + +export default function ({ getService }: FtrProviderContext) { + describe('SyncGlobalParamsSpaces', function () { + this.tags('skipCloud'); + const supertestAPI = getService('supertest'); + const retry = getService('retry'); + + const kServer = getService('kibanaServer'); + let locWithSpace: PrivateLocation; + let _browserMonitorJson: HTTPFields; + let browserMonitorJson: HTTPFields; + let newBrowserMonitorId: string; + let spaceId = ''; + + const testPrivateLocations = new PrivateLocationTestService(getService); + const monitorTestService = new SyntheticsMonitorTestService(getService); + + const params: Record = {}; + + before(async () => { + await kServer.savedObjects.cleanStandardList(); + await testPrivateLocations.installSyntheticsPackage(); + _browserMonitorJson = getFixtureJson('browser_monitor'); + }); + + beforeEach(() => { + browserMonitorJson = _browserMonitorJson; + }); + + it('create test private locations', async () => { + const data = await monitorTestService.addsNewSpace(); + spaceId = data.SPACE_ID; + locWithSpace = await testPrivateLocations.createPrivateLocation({ + spaceId, + label: 'Test private location 1', + }); + }); + + it('create monitors in private locations', async () => { + const newMonitor = browserMonitorJson; + newMonitor.locations = [locWithSpace]; + + const res = await monitorTestService.createMonitor({ + monitor: newMonitor, + spaceId, + }); + + expect(res.body).eql( + omitMonitorKeys({ + ...newMonitor, + [ConfigKey.MONITOR_QUERY_ID]: res.body.id, + [ConfigKey.CONFIG_ID]: res.body.id, + spaces: [spaceId], + }) + ); + newBrowserMonitorId = res.rawBody.id; + }); + + it('added an integration for previously added monitor', async () => { + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + spaceId, + monitorId: newBrowserMonitorId, + locId: locWithSpace.id, + }); + + expect(packagePolicy?.policy_id).eql(locWithSpace.agentPolicyId); + + comparePolicies( + packagePolicy, + getTestSyntheticsPolicy({ + name: browserMonitorJson.name, + id: newBrowserMonitorId, + isBrowser: true, + location: { id: locWithSpace.agentPolicyId }, + }) + ); + }); + + it('add few test params', async () => { + await supertestAPI + .post(`/s/${spaceId}` + SYNTHETICS_API_URLS.PARAMS) + .set('kbn-xsrf', 'true') + .send([ + { key: 'test', value: 'http://proxy.com' }, + { key: 'username', value: 'elastic' }, + ]) + .expect(200); + }); + + it('get list of params', async () => { + const apiResponse = await supertestAPI + .get(`/s/${spaceId}` + SYNTHETICS_API_URLS.PARAMS) + .set('kbn-xsrf', 'true') + .send(); + + expect(apiResponse.status).eql(200); + + apiResponse.body.forEach(({ key, value }: SyntheticsParams) => { + params[key] = value; + }); + }); + + it('added params to for previously added integration', async () => { + let packagePolicy; + await retry.try(async () => { + packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: locWithSpace.id, + spaceId, + }); + expect(packagePolicy.policy_id).eql(locWithSpace.agentPolicyId); + expect(packagePolicy.inputs[0].streams[0].compiled_stream.params).eql(params); + }); + + comparePolicies( + packagePolicy!, + getTestSyntheticsPolicy({ + name: browserMonitorJson.name, + id: newBrowserMonitorId, + isBrowser: true, + location: { id: locWithSpace.agentPolicyId }, + }) + ); + }); + + it('delete all params and sync again', async () => { + const getResponse = await supertestAPI + .get(`/s/${spaceId}` + SYNTHETICS_API_URLS.PARAMS) + .set('kbn-xsrf', 'true') + .expect(200); + expect(getResponse.body.length).eql(2); + + const paramsResponse = getResponse.body || []; + const ids = paramsResponse.map((param: any) => param.id); + + const deleteResponse = await supertestAPI + .delete(`/s/${spaceId}` + SYNTHETICS_API_URLS.PARAMS) + .set('kbn-xsrf', 'true') + .send({ ids }); + + expect(deleteResponse.status).eql(200); + expect(deleteResponse.body).to.have.length(2); + + const getResponseAfterDelete = await supertestAPI + .get(`/s/${spaceId}` + SYNTHETICS_API_URLS.PARAMS) + .set('kbn-xsrf', 'true') + .expect(200); + + expect(getResponseAfterDelete.body.length).eql(0); + + const packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: locWithSpace.id, + spaceId, + }); + + expect(packagePolicy.policy_id).eql(locWithSpace.agentPolicyId); + + comparePolicies( + packagePolicy, + getTestSyntheticsPolicy({ + name: browserMonitorJson.name, + id: newBrowserMonitorId, + isBrowser: true, + location: { id: locWithSpace.id }, + }) + ); + }); + + it('check browser monitor again after deleting params', async () => { + let packagePolicy; + await retry.try(async () => { + packagePolicy = await testPrivateLocations.getPackagePolicy({ + monitorId: newBrowserMonitorId, + locId: locWithSpace.id, + spaceId, + }); + expect(packagePolicy.policy_id).eql(locWithSpace.agentPolicyId); + expect(packagePolicy.inputs[0].streams[0].compiled_stream.params).eql(undefined); + }); + + comparePolicies( + packagePolicy!, + getTestSyntheticsPolicy({ + name: browserMonitorJson.name, + id: newBrowserMonitorId, + isBrowser: true, + location: { id: locWithSpace.id }, + }) + ); + }); + }); +}