From 203d3068e8ddc37fb655c1ac15d6edecaab0c949 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Tue, 23 May 2023 21:21:22 +0100 Subject: [PATCH] [ML] Versioning all ML APIs (#156949) Adds versioning to all of the ML kibana APIs. Versions are added to the server side routes and to the client side functions which call the routes. Makes some small refactors to ensure only the functions inside `ml/public/application/services/ml_api_service/` are where the ML APIs are called. Updates external plugins which call ML APIs to add the new versioning. Updates API tests to add the API version to the request headers. Our one public API has been given the version `'2023-05-15'`, all of the internal APIs have been given the version `'1'`. **Public APIs:** `/api/ml/saved_objects/sync` **Internal APIS:** `/internal/ml/alerting/preview` `/internal/ml/annotations` `/internal/ml/annotations/index` `/internal/ml/annotations/delete/{annotationId}` `/internal/ml/anomaly_detectors` `/internal/ml/anomaly_detectors/{jobId}` `/internal/ml/anomaly_detectors/_stats` `/internal/ml/anomaly_detectors/{jobId}/_stats` `/internal/ml/anomaly_detectors/{jobId}` `/internal/ml/anomaly_detectors/{jobId}/_update` `/internal/ml/anomaly_detectors/{jobId}/_open` `/internal/ml/anomaly_detectors/{jobId}/_close` `/internal/ml/anomaly_detectors/{jobId}/_reset` `/internal/ml/anomaly_detectors/{jobId}` `/internal/ml/anomaly_detectors/_validate/detector` `/internal/ml/anomaly_detectors/{jobId}/_forecast` `/internal/ml/anomaly_detectors/{jobId}/results/records` `/internal/ml/anomaly_detectors/{jobId}/results/buckets/{timestamp?}` `/internal/ml/anomaly_detectors/{jobId}/results/overall_buckets` `/internal/ml/anomaly_detectors/{jobId}/results/categories/{categoryId}` `/internal/ml/anomaly_detectors/{jobId}/model_snapshots` `/internal/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}` `/internal/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}/_update` `/internal/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}` `/internal/ml/calendars` `/internal/ml/calendars/{calendarIds}` `/internal/ml/calendars` `/internal/ml/calendars/{calendarId}` `/internal/ml/calendars/{calendarId}` `/internal/ml/data_frame/analytics` `/internal/ml/data_frame/analytics/{analyticsId}` `/internal/ml/data_frame/analytics/_stats` `/internal/ml/data_frame/analytics/{analyticsId}/_stats` `/internal/ml/data_frame/analytics/{analyticsId}` `/internal/ml/data_frame/_evaluate` `/internal/ml/data_frame/analytics/_explain` `/internal/ml/data_frame/analytics/{analyticsId}` `/internal/ml/data_frame/analytics/{analyticsId}/_start` `/internal/ml/data_frame/analytics/{analyticsId}/_stop` `/internal/ml/data_frame/analytics/{analyticsId}/_update` `/internal/ml/data_frame/analytics/{analyticsId}/messages` `/internal/ml/data_frame/analytics/jobs_exist` `/internal/ml/data_frame/analytics/map/{analyticsId}` `/internal/ml/data_frame/analytics/new_job_caps/{indexPattern}` `/internal/ml/data_frame/analytics/validate` `/internal/ml/data_visualizer/get_field_histograms/{indexPattern}` `/internal/ml/datafeeds` `/internal/ml/datafeeds/{datafeedId}` `/internal/ml/datafeeds/_stats` `/internal/ml/datafeeds/{datafeedId}/_stats` `/internal/ml/datafeeds/{datafeedId}` `/internal/ml/datafeeds/{datafeedId}/_update` `/internal/ml/datafeeds/{datafeedId}` `/internal/ml/datafeeds/{datafeedId}/_start` `/internal/ml/datafeeds/{datafeedId}/_stop` `/internal/ml/datafeeds/{datafeedId}/_preview` `/internal/ml/fields_service/field_cardinality` `/internal/ml/fields_service/time_field_range` `/internal/ml/filters` `/internal/ml/filters/{filterId}` `/internal/ml/filters` `/internal/ml/filters/{filterId}` `/internal/ml/filters/{filterId}` `/internal/ml/filters/_stats` `/internal/ml/indices/field_caps` `/internal/ml/job_audit_messages/messages/{jobId}` `/internal/ml/job_audit_messages/messages` `/internal/ml/job_audit_messages/clear_messages` `/internal/ml/jobs/force_start_datafeeds` `/internal/ml/jobs/stop_datafeeds` `/internal/ml/jobs/delete_jobs` `/internal/ml/jobs/close_jobs` `/internal/ml/jobs/reset_jobs` `/internal/ml/jobs/force_stop_and_close_job` `/internal/ml/jobs/jobs_summary` `/internal/ml/jobs/jobs_with_geo` `/internal/ml/jobs/jobs_with_time_range` `/internal/ml/jobs/job_for_cloning` `/internal/ml/jobs/jobs` `/internal/ml/jobs/groups` `/internal/ml/jobs/update_groups` `/internal/ml/jobs/blocking_jobs_tasks` `/internal/ml/jobs/jobs_exist` `/internal/ml/jobs/new_job_caps/{indexPattern}` `/internal/ml/jobs/new_job_line_chart` `/internal/ml/jobs/new_job_population_chart` `/internal/ml/jobs/all_jobs_and_group_ids` `/internal/ml/jobs/look_back_progress` `/internal/ml/jobs/categorization_field_examples` `/internal/ml/jobs/top_categories` `/internal/ml/jobs/datafeed_preview` `/internal/ml/jobs/revert_model_snapshot` `/internal/ml/jobs/bulk_create` `/internal/ml/validate/estimate_bucket_span` `/internal/ml/validate/calculate_model_memory_limit` `/internal/ml/validate/cardinality` `/internal/ml/validate/job` `/internal/ml/validate/datafeed_preview` `/internal/ml/json_schema` `/internal/ml/management/list/{listType}` `/internal/ml/model_management/nodes_overview` `/internal/ml/model_management/memory_usage` `/internal/ml/modules/recognize/{indexPatternTitle}` `/internal/ml/modules/get_module/{moduleId?}` `/internal/ml/modules/setup/{moduleId}` `/internal/ml/modules/jobs_exist/{moduleId}` `/internal/ml/notifications` `/internal/ml/notifications/count` `/internal/ml/results/anomalies_table_data` `/internal/ml/results/category_definition` `/internal/ml/results/max_anomaly_score` `/internal/ml/results/category_examples` `/internal/ml/results/partition_fields_values` `/internal/ml/results/anomaly_search` `/internal/ml/results/{jobId}/categorizer_stats` `/internal/ml/results/category_stopped_partitions` `/internal/ml/results/datafeed_results_chart` `/internal/ml/results/anomaly_charts` `/internal/ml/results/anomaly_records` `/internal/ml/saved_objects/status` `/internal/ml/saved_objects/initialize` `/internal/ml/saved_objects/sync_check` `/internal/ml/saved_objects/update_jobs_spaces` `/internal/ml/saved_objects/update_trained_models_spaces` `/internal/ml/saved_objects/remove_item_from_current_space` `/internal/ml/saved_objects/jobs_spaces` `/internal/ml/saved_objects/trained_models_spaces` `/internal/ml/saved_objects/can_delete_ml_space_aware_item/{jobType}` `/internal/ml/_has_privileges` `/internal/ml/ml_capabilities` `/internal/ml/ml_node_count` `/internal/ml/info` `/internal/ml/es_search` `/internal/ml/index_exists` `/internal/ml/trained_models/{modelId?}` `/internal/ml/trained_models/_stats` `/internal/ml/trained_models/{modelId}/_stats` `/internal/ml/trained_models/{modelId}/pipelines` `/internal/ml/trained_models/{modelId}` `/internal/ml/trained_models/{modelId}` `/internal/ml/trained_models/{modelId}/deployment/_start` `/internal/ml/trained_models/{modelId}/{deploymentId}/deployment/_update` `/internal/ml/trained_models/{modelId}/{deploymentId}/deployment/_stop` `/internal/ml/trained_models/pipeline_simulate` `/internal/ml/trained_models/infer/{modelId}/{deploymentId}` --- .../full_time_range_selector_service.ts | 2 +- .../ml_models/ml_model_stats_logic.test.ts | 2 +- .../api/ml_models/ml_model_stats_logic.ts | 5 +- .../api/ml_models/ml_models_logic.test.ts | 3 +- .../api/ml_models/ml_models_logic.ts | 10 +- .../logs/log_analysis/api/ml_cleanup.ts | 10 +- .../api/ml_get_jobs_summary_api.ts | 3 +- .../logs/log_analysis/api/ml_get_module.ts | 3 +- .../log_analysis/api/ml_setup_module_api.ts | 3 +- .../log_analysis_capabilities.tsx | 4 +- .../public/containers/ml/api/ml_cleanup.ts | 10 +- .../ml/api/ml_get_jobs_summary_api.ts | 3 +- .../public/containers/ml/api/ml_get_module.ts | 3 +- .../containers/ml/api/ml_setup_module_api.ts | 3 +- .../containers/ml/infra_ml_capabilities.tsx | 4 +- x-pack/plugins/ml/common/constants/app.ts | 3 +- .../anomaly_detection_jobs/summary_job.ts | 2 +- x-pack/plugins/ml/common/types/modules.ts | 8 + x-pack/plugins/ml/common/util/job_utils.ts | 17 + .../index_based/index_data_visualizer.tsx | 24 +- .../components/time_range_step/time_range.tsx | 3 +- .../services/anomaly_detector_service.ts | 39 +- .../services/ml_api_service/alerting.ts | 5 +- .../services/ml_api_service/annotations.ts | 14 +- .../ml_api_service/data_frame_analytics.ts | 50 +- .../services/ml_api_service/filters.ts | 17 +- .../services/ml_api_service/index.ts | 174 ++- .../services/ml_api_service/jobs.ts | 86 +- .../services/ml_api_service/json_schema.ts | 7 +- .../services/ml_api_service/management.ts | 7 +- .../services/ml_api_service/notifications.ts | 10 +- .../services/ml_api_service/results.ts | 36 +- .../services/ml_api_service/saved_objects.ts | 29 +- .../services/ml_api_service/trained_models.ts | 40 +- .../anomaly_charts_setup_flyout.tsx | 14 +- .../anomaly_swimlane_setup_flyout.tsx | 14 +- .../models/data_recognizer/data_recognizer.ts | 9 +- .../ml/server/models/data_recognizer/index.ts | 1 - x-pack/plugins/ml/server/routes/alerting.ts | 54 +- .../plugins/ml/server/routes/annotations.ts | 162 +- .../ml/server/routes/anomaly_detectors.ts | 1017 ++++++------ x-pack/plugins/ml/server/routes/calendars.ts | 248 +-- .../ml/server/routes/data_frame_analytics.ts | 1019 ++++++------ .../ml/server/routes/data_visualizer.ts | 70 +- x-pack/plugins/ml/server/routes/datafeeds.ts | 525 ++++--- .../ml/server/routes/fields_service.ts | 91 +- x-pack/plugins/ml/server/routes/filters.ts | 263 ++-- x-pack/plugins/ml/server/routes/indices.ts | 50 +- .../ml/server/routes/job_audit_messages.ts | 168 +- .../plugins/ml/server/routes/job_service.ts | 1369 +++++++++-------- .../ml/server/routes/job_validation.ts | 283 ++-- .../plugins/ml/server/routes/json_schema.ts | 54 +- x-pack/plugins/ml/server/routes/management.ts | 210 +-- .../ml/server/routes/model_management.ts | 101 +- x-pack/plugins/ml/server/routes/modules.ts | 389 ++--- .../plugins/ml/server/routes/notifications.ts | 99 +- .../ml/server/routes/results_service.ts | 517 ++++--- .../plugins/ml/server/routes/saved_objects.ts | 543 ++++--- x-pack/plugins/ml/server/routes/system.ts | 356 +++-- .../ml/server/routes/trained_models.ts | 695 +++++---- .../components/ml/api/anomalies_search.ts | 3 +- .../components/ml/api/anomalies_table_data.ts | 3 +- .../common/components/ml/api/get_jobs.ts | 3 +- .../components/ml/api/get_jobs_summary.ts | 3 +- .../components/ml/api/get_ml_capabilities.ts | 3 +- .../common/components/ml_popover/api.ts | 18 +- .../hooks/use_fetch_modules_query.ts | 2 +- .../hooks/use_fetch_recognizer_query.ts | 2 +- .../synthetics/common/constants/rest_api.ts | 10 +- .../apis/ml/annotations/create_annotations.ts | 14 +- .../apis/ml/annotations/delete_annotations.ts | 14 +- .../apis/ml/annotations/get_annotations.ts | 18 +- .../apis/ml/annotations/update_annotations.ts | 18 +- .../ml/anomaly_detectors/close_with_spaces.ts | 6 +- .../apis/ml/anomaly_detectors/create.ts | 6 +- .../anomaly_detectors/create_with_datafeed.ts | 6 +- .../anomaly_detectors/create_with_spaces.ts | 6 +- .../anomaly_detectors/delete_with_spaces.ts | 6 +- .../anomaly_detectors/forecast_with_spaces.ts | 6 +- .../apis/ml/anomaly_detectors/get.ts | 42 +- .../get_stats_with_spaces.ts | 6 +- .../ml/anomaly_detectors/get_with_spaces.ts | 6 +- .../ml/anomaly_detectors/open_with_spaces.ts | 6 +- .../apis/ml/calendars/create_calendars.ts | 14 +- .../apis/ml/calendars/delete_calendars.ts | 18 +- .../apis/ml/calendars/get_calendars.ts | 30 +- .../apis/ml/calendars/update_calendars.ts | 18 +- .../ml/data_frame_analytics/create_job.ts | 14 +- .../apis/ml/data_frame_analytics/delete.ts | 30 +- .../ml/data_frame_analytics/delete_spaces.ts | 6 +- .../apis/ml/data_frame_analytics/evaluate.ts | 14 +- .../apis/ml/data_frame_analytics/explain.ts | 14 +- .../apis/ml/data_frame_analytics/get.ts | 58 +- .../ml/data_frame_analytics/get_spaces.ts | 10 +- .../data_frame_analytics/jobs_exist_spaces.ts | 6 +- .../ml/data_frame_analytics/new_job_caps.ts | 6 +- .../apis/ml/data_frame_analytics/start.ts | 18 +- .../ml/data_frame_analytics/start_spaces.ts | 6 +- .../apis/ml/data_frame_analytics/stop.ts | 18 +- .../ml/data_frame_analytics/stop_spaces.ts | 6 +- .../apis/ml/data_frame_analytics/update.ts | 38 +- .../ml/data_frame_analytics/update_spaces.ts | 6 +- .../apis/ml/data_frame_analytics/validate.ts | 14 +- .../ml/datafeeds/get_stats_with_spaces.ts | 8 +- .../apis/ml/datafeeds/get_with_spaces.ts | 8 +- .../apis/ml/datafeeds/update.ts | 6 +- .../ml/fields_service/field_cardinality.ts | 6 +- .../ml/fields_service/time_field_range.ts | 6 +- .../apis/ml/filters/create_filters.ts | 6 +- .../apis/ml/filters/delete_filters.ts | 18 +- .../apis/ml/filters/get_filters.ts | 22 +- .../apis/ml/filters/get_filters_stats.ts | 14 +- .../apis/ml/filters/update_filters.ts | 18 +- .../apis/ml/indices/field_caps.ts | 6 +- .../ml/job_audit_messages/clear_messages.ts | 30 +- .../get_job_audit_messages.ts | 18 +- .../job_validation/bucket_span_estimator.ts | 14 +- .../calculate_model_memory_limit.ts | 6 +- .../apis/ml/job_validation/cardinality.ts | 18 +- .../datafeed_preview_validation.ts | 30 +- .../apis/ml/job_validation/validate.ts | 22 +- .../ml/jobs/categorization_field_examples.ts | 6 +- .../apis/ml/jobs/close_jobs.ts | 6 +- .../apis/ml/jobs/close_jobs_spaces.ts | 6 +- .../apis/ml/jobs/datafeed_preview.ts | 26 +- .../apis/ml/jobs/delete_jobs.ts | 6 +- .../apis/ml/jobs/delete_jobs_spaces.ts | 6 +- .../apis/ml/jobs/force_start_datafeeds.ts | 6 +- .../ml/jobs/force_start_datafeeds_spaces.ts | 6 +- .../apis/ml/jobs/get_groups.ts | 6 +- .../test/api_integration/apis/ml/jobs/jobs.ts | 7 +- .../apis/ml/jobs/jobs_exist.ts | 6 +- .../apis/ml/jobs/jobs_exist_spaces.ts | 6 +- .../apis/ml/jobs/jobs_summary.ts | 6 +- .../apis/ml/jobs/jobs_summary_spaces.ts | 6 +- .../api_integration/apis/ml/jobs/reset.ts | 6 +- .../apis/ml/jobs/stop_datafeeds.ts | 6 +- .../apis/ml/jobs/stop_datafeeds_spaces.ts | 6 +- .../apis/ml/management/get_list.ts | 6 +- .../apis/ml/modules/get_module.ts | 6 +- .../apis/ml/modules/jobs_exist.ts | 6 +- .../apis/ml/modules/recognize_module.ts | 6 +- .../apis/ml/modules/setup_module.ts | 6 +- .../ml/notifications/count_notifications.ts | 14 +- .../ml/notifications/get_notifications.ts | 22 +- .../ml/results/get_anomalies_table_data.ts | 14 +- .../apis/ml/results/get_anomaly_search.ts | 6 +- .../apis/ml/results/get_categorizer_stats.ts | 26 +- .../ml/results/get_category_definition.ts | 6 +- .../apis/ml/results/get_category_examples.ts | 6 +- .../ml/results/get_datafeed_results_chart.ts | 14 +- .../ml/results/get_partition_fields_values.ts | 6 +- .../apis/ml/results/get_stopped_partitions.ts | 26 +- .../apis/ml/results/max_anomaly_score.ts | 6 +- .../apis/ml/saved_objects/can_delete_job.ts | 6 +- .../saved_objects/can_delete_trained_model.ts | 6 +- .../apis/ml/saved_objects/get_jobs_spaces.ts | 6 +- .../saved_objects/get_trained_model_spaces.ts | 6 +- .../apis/ml/saved_objects/initialize_jobs.ts | 6 +- .../initialize_trained_models.ts | 6 +- .../remove_from_current_space.ts | 6 +- .../apis/ml/saved_objects/status.ts | 6 +- .../apis/ml/saved_objects/sync_jobs.ts | 8 +- .../ml/saved_objects/sync_trained_models.ts | 8 +- .../ml/saved_objects/update_jobs_spaces.ts | 6 +- .../update_trained_model_spaces.ts | 6 +- .../apis/ml/system/capabilities.ts | 6 +- .../apis/ml/system/index_exists.ts | 6 +- .../apis/ml/system/space_capabilities.ts | 6 +- .../apis/ml/trained_models/delete_model.ts | 22 +- .../ml/trained_models/get_model_pipelines.ts | 10 +- .../apis/ml/trained_models/get_model_stats.ts | 14 +- .../apis/ml/trained_models/get_models.ts | 22 +- .../apis/transform/delete_transforms.ts | 18 +- .../apis/transform/reauthorize_transforms.ts | 14 +- .../apis/transform/reset_transforms.ts | 12 +- .../apis/transform/schedule_now_transforms.ts | 12 +- .../apis/transform/start_transforms.ts | 12 +- .../apis/transform/stop_transforms.ts | 12 +- .../apis/transform/transforms.ts | 12 +- .../apis/transform/transforms_create.ts | 6 +- .../apis/transform/transforms_nodes.ts | 8 +- .../apis/transform/transforms_preview.ts | 8 +- .../apis/transform/transforms_stats.ts | 6 +- .../apis/transform/transforms_update.ts | 10 +- .../utils/machine_learning_setup.ts | 4 +- .../apps/transform/actions/reauthorizing.ts | 4 +- x-pack/test/functional/services/ml/api.ts | 50 +- .../test/functional/services/ml/common_api.ts | 14 +- .../functional/services/ml/test_resources.ts | 24 +- 190 files changed, 5817 insertions(+), 4637 deletions(-) diff --git a/x-pack/packages/ml/date_picker/src/services/full_time_range_selector_service.ts b/x-pack/packages/ml/date_picker/src/services/full_time_range_selector_service.ts index a1c54e609a6235..cfd363e8b53ce2 100644 --- a/x-pack/packages/ml/date_picker/src/services/full_time_range_selector_service.ts +++ b/x-pack/packages/ml/date_picker/src/services/full_time_range_selector_service.ts @@ -22,7 +22,7 @@ import type { GetTimeFieldRangeResponse } from './types'; */ export type SetFullTimeRangeApiPath = | '/internal/file_upload/time_field_range' - | '/api/ml/fields_service/time_field_range'; + | '/internal/ml/fields_service/time_field_range'; /** * Determines the full available time range of the given Data View and updates diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.test.ts index c36704a46604d4..4bcea4ac4e83ae 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.test.ts @@ -18,7 +18,7 @@ describe('MLModelsApiLogic', () => { it('calls the ml api', async () => { http.get.mockResolvedValue(mlModelStats); const result = await getMLModelsStats(); - expect(http.get).toHaveBeenCalledWith('/api/ml/trained_models/_stats'); + expect(http.get).toHaveBeenCalledWith('/internal/ml/trained_models/_stats', { version: '1' }); expect(result).toEqual(mlModelStats); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.ts index 7c0d1020cd265b..d8bc341fcb6c31 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_model_stats_logic.ts @@ -17,7 +17,10 @@ export interface GetMlModelsStatsResponse { } export const getMLModelsStats = async () => { - return await HttpLogic.values.http.get('/api/ml/trained_models/_stats'); + return await HttpLogic.values.http.get( + '/internal/ml/trained_models/_stats', + { version: '1' } + ); }; export const MLModelsStatsApiLogic = createApiLogic( diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.test.ts index 6196d6a162dae5..cffdc08dfd2efd 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.test.ts @@ -18,8 +18,9 @@ describe('MLModelsApiLogic', () => { it('calls the ml api', async () => { http.get.mockResolvedValue(mlModels); const result = await getMLModels(); - expect(http.get).toHaveBeenCalledWith('/api/ml/trained_models', { + expect(http.get).toHaveBeenCalledWith('/internal/ml/trained_models', { query: { size: 1000, with_pipelines: true }, + version: '1', }); expect(result).toEqual(mlModels); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.ts b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.ts index fe610ed0b710ac..9cec020b8d7826 100644 --- a/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/enterprise_search_content/api/ml_models/ml_models_logic.ts @@ -14,9 +14,13 @@ export type GetMlModelsArgs = number | undefined; export type GetMlModelsResponse = TrainedModelConfigResponse[]; export const getMLModels = async (size: GetMlModelsArgs = 1000) => { - return await HttpLogic.values.http.get('/api/ml/trained_models', { - query: { size, with_pipelines: true }, - }); + return await HttpLogic.values.http.get( + '/internal/ml/trained_models', + { + query: { size, with_pipelines: true }, + version: '1', + } + ); }; export const MLModelsApiLogic = createApiLogic(['ml_models_api_logic'], getMLModels, { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts index 2912cdf74a36e6..e0cdd44bafe148 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts @@ -24,8 +24,9 @@ export const callDeleteJobs = async ( const { spaceId, logViewId, jobTypes } = requestArgs; // NOTE: Deleting the jobs via this API will delete the datafeeds at the same time - const deleteJobsResponse = await fetch('/api/ml/jobs/delete_jobs', { + const deleteJobsResponse = await fetch('/internal/ml/jobs/delete_jobs', { method: 'POST', + version: '1', body: JSON.stringify( deleteJobsRequestPayloadRT.encode({ jobIds: jobTypes.map((jobType) => getJobId(spaceId, logViewId, jobType)), @@ -37,7 +38,9 @@ export const callDeleteJobs = async ( }; export const callGetJobDeletionTasks = async (fetch: HttpHandler) => { - const jobDeletionTasksResponse = await fetch('/api/ml/jobs/deleting_jobs_tasks'); + const jobDeletionTasksResponse = await fetch('/internal/ml/jobs/deleting_jobs_tasks', { + version: '1', + }); return decodeOrThrow(getJobDeletionTasksResponsePayloadRT)(jobDeletionTasksResponse); }; @@ -55,8 +58,9 @@ export const callStopDatafeeds = async ( const { spaceId, logViewId, jobTypes } = requestArgs; // Stop datafeed due to https://github.com/elastic/kibana/issues/44652 - const stopDatafeedResponse = await fetch('/api/ml/jobs/stop_datafeeds', { + const stopDatafeedResponse = await fetch('/internal/ml/jobs/stop_datafeeds', { method: 'POST', + version: '1', body: JSON.stringify( stopDatafeedsRequestPayloadRT.encode({ datafeedIds: jobTypes.map((jobType) => getDatafeedId(spaceId, logViewId, jobType)), diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts index b737427b239126..35c678f7b20c09 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts @@ -22,8 +22,9 @@ export const callJobsSummaryAPI = async ( fetch: HttpHandler ) => { const { spaceId, logViewId, jobTypes } = requestArgs; - const response = await fetch('/api/ml/jobs/jobs_summary', { + const response = await fetch('/internal/ml/jobs/jobs_summary', { method: 'POST', + version: '1', body: JSON.stringify( fetchJobStatusRequestPayloadRT.encode({ jobIds: jobTypes.map((jobType) => getJobId(spaceId, logViewId, jobType)), diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_module.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_module.ts index 11a423c9ba438a..8fb75722ae7d89 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_module.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_module.ts @@ -12,8 +12,9 @@ import { jobCustomSettingsRT } from '../../../../../common/log_analysis'; import { decodeOrThrow } from '../../../../../common/runtime_types'; export const callGetMlModuleAPI = async (moduleId: string, fetch: HttpHandler) => { - const response = await fetch(`/api/ml/modules/get_module/${moduleId}`, { + const response = await fetch(`/internal/ml/modules/get_module/${moduleId}`, { method: 'GET', + version: '1', }); return decodeOrThrow(getMlModuleResponsePayloadRT)(response); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_setup_module_api.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_setup_module_api.ts index 39c8668c535b2c..f19c754ada3807 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_setup_module_api.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_setup_module_api.ts @@ -38,8 +38,9 @@ export const callSetupMlModuleAPI = async (requestArgs: RequestArgs, fetch: Http useDedicatedIndex = false, } = requestArgs; - const response = await fetch(`/api/ml/modules/setup/${moduleId}`, { + const response = await fetch(`/internal/ml/modules/setup/${moduleId}`, { method: 'POST', + version: '1', body: JSON.stringify( setupMlModuleRequestPayloadRT.encode({ start, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx index db519b4c795eb8..d4a5ebe1f49667 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx @@ -24,7 +24,9 @@ export const useLogAnalysisCapabilities = () => { { cancelPreviousOn: 'resolution', createPromise: async () => { - const rawResponse = await services.http.fetch('/api/ml/ml_capabilities'); + const rawResponse = await services.http.fetch('/internal/ml/ml_capabilities', { + version: '1', + }); return decodeOrThrow(getMlCapabilitiesResponsePayloadRT)(rawResponse); }, diff --git a/x-pack/plugins/infra/public/containers/ml/api/ml_cleanup.ts b/x-pack/plugins/infra/public/containers/ml/api/ml_cleanup.ts index 915240c6c6cec6..e2d22cd45bc112 100644 --- a/x-pack/plugins/infra/public/containers/ml/api/ml_cleanup.ts +++ b/x-pack/plugins/infra/public/containers/ml/api/ml_cleanup.ts @@ -23,8 +23,9 @@ export const callDeleteJobs = async ( const { spaceId, sourceId, jobTypes } = requestArgs; // NOTE: Deleting the jobs via this API will delete the datafeeds at the same time - const deleteJobsResponse = await fetch('/api/ml/jobs/delete_jobs', { + const deleteJobsResponse = await fetch('/internal/ml/jobs/delete_jobs', { method: 'POST', + version: '1', body: JSON.stringify( deleteJobsRequestPayloadRT.encode({ jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), @@ -36,7 +37,9 @@ export const callDeleteJobs = async ( }; export const callGetJobDeletionTasks = async (fetch: HttpHandler) => { - const jobDeletionTasksResponse = await fetch('/api/ml/jobs/deleting_jobs_tasks'); + const jobDeletionTasksResponse = await fetch('/internal/ml/jobs/deleting_jobs_tasks', { + version: '1', + }); return decodeOrThrow(getJobDeletionTasksResponsePayloadRT)(jobDeletionTasksResponse); }; @@ -54,8 +57,9 @@ export const callStopDatafeeds = async ( const { spaceId, sourceId, jobTypes } = requestArgs; // Stop datafeed due to https://github.com/elastic/kibana/issues/44652 - const stopDatafeedResponse = await fetch('/api/ml/jobs/stop_datafeeds', { + const stopDatafeedResponse = await fetch('/internal/ml/jobs/stop_datafeeds', { method: 'POST', + version: '1', body: JSON.stringify( stopDatafeedsRequestPayloadRT.encode({ datafeedIds: jobTypes.map((jobType) => getDatafeedId(spaceId, sourceId, jobType)), diff --git a/x-pack/plugins/infra/public/containers/ml/api/ml_get_jobs_summary_api.ts b/x-pack/plugins/infra/public/containers/ml/api/ml_get_jobs_summary_api.ts index 58baccbcedbb93..9488c9c1301e09 100644 --- a/x-pack/plugins/infra/public/containers/ml/api/ml_get_jobs_summary_api.ts +++ b/x-pack/plugins/infra/public/containers/ml/api/ml_get_jobs_summary_api.ts @@ -22,8 +22,9 @@ export const callJobsSummaryAPI = async ( fetch: HttpHandler ) => { const { spaceId, sourceId, jobTypes } = requestArgs; - const response = await fetch('/api/ml/jobs/jobs_summary', { + const response = await fetch('/internal/ml/jobs/jobs_summary', { method: 'POST', + version: '1', body: JSON.stringify( fetchJobStatusRequestPayloadRT.encode({ jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), diff --git a/x-pack/plugins/infra/public/containers/ml/api/ml_get_module.ts b/x-pack/plugins/infra/public/containers/ml/api/ml_get_module.ts index 9d24693c720cab..afb1ee211a75a9 100644 --- a/x-pack/plugins/infra/public/containers/ml/api/ml_get_module.ts +++ b/x-pack/plugins/infra/public/containers/ml/api/ml_get_module.ts @@ -12,8 +12,9 @@ import { jobCustomSettingsRT } from '../../../../common/log_analysis'; import { decodeOrThrow } from '../../../../common/runtime_types'; export const callGetMlModuleAPI = async (moduleId: string, fetch: HttpHandler) => { - const response = await fetch(`/api/ml/modules/get_module/${moduleId}`, { + const response = await fetch(`/internal/ml/modules/get_module/${moduleId}`, { method: 'GET', + version: '1', }); return decodeOrThrow(getMlModuleResponsePayloadRT)(response); diff --git a/x-pack/plugins/infra/public/containers/ml/api/ml_setup_module_api.ts b/x-pack/plugins/infra/public/containers/ml/api/ml_setup_module_api.ts index e9392062c31182..4514b6c6082357 100644 --- a/x-pack/plugins/infra/public/containers/ml/api/ml_setup_module_api.ts +++ b/x-pack/plugins/infra/public/containers/ml/api/ml_setup_module_api.ts @@ -36,8 +36,9 @@ export const callSetupMlModuleAPI = async (requestArgs: RequestArgs, fetch: Http query, } = requestArgs; - const response = await fetch(`/api/ml/modules/setup/${moduleId}`, { + const response = await fetch(`/internal/ml/modules/setup/${moduleId}`, { method: 'POST', + version: '1', body: JSON.stringify( setupMlModuleRequestPayloadRT.encode({ start, diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx index 7b9fe25cc3fa12..210eb4de4725f9 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx @@ -27,7 +27,9 @@ export const useInfraMLCapabilities = () => { { cancelPreviousOn: 'resolution', createPromise: async () => { - const rawResponse = await services.http.fetch('/api/ml/ml_capabilities'); + const rawResponse = await services.http.fetch('/internal/ml/ml_capabilities', { + version: '1', + }); return pipe( getMlCapabilitiesResponsePayloadRT.decode(rawResponse), diff --git a/x-pack/plugins/ml/common/constants/app.ts b/x-pack/plugins/ml/common/constants/app.ts index 974984d457ae49..970505f4857390 100644 --- a/x-pack/plugins/ml/common/constants/app.ts +++ b/x-pack/plugins/ml/common/constants/app.ts @@ -13,4 +13,5 @@ export const PLUGIN_ICON_SOLUTION = 'logoKibana'; export const ML_APP_NAME = i18n.translate('xpack.ml.navMenu.mlAppNameText', { defaultMessage: 'Machine Learning', }); -export const ML_BASE_PATH = '/api/ml'; +export const ML_INTERNAL_BASE_PATH = '/internal/ml'; +export const ML_EXTERNAL_BASE_PATH = '/api/ml'; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/summary_job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/summary_job.ts index 504fdb8cf1dcd1..3fec712e78e9ec 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/summary_job.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/summary_job.ts @@ -90,7 +90,7 @@ export interface MlSummaryJob { /** * Used in older implementations of the job config, where the datafeed was placed inside the job for convenience. - * This will be populated if the job's id has been passed to the /api/ml/jobs/jobs_summary endpoint. + * This will be populated if the job's id has been passed to the /internal/ml/jobs/jobs_summary endpoint. */ fullJob?: CombinedJob; diff --git a/x-pack/plugins/ml/common/types/modules.ts b/x-pack/plugins/ml/common/types/modules.ts index 2a6cc9bbd57ce2..30ec4efd74302d 100644 --- a/x-pack/plugins/ml/common/types/modules.ts +++ b/x-pack/plugins/ml/common/types/modules.ts @@ -58,6 +58,14 @@ export interface Module { kibana: KibanaObjects; } +export interface RecognizeResult { + id: string; + title: string; + query: any; + description: string; + logo: Logo; +} + export interface FileBasedModule extends Omit { jobs: Array<{ file: string; id: string }>; datafeeds: Array<{ file: string; job_id: string; id: string }>; diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index d465a844b3ec73..2b3f3d82042d1a 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -916,3 +916,20 @@ export function isKnownEmptyQuery(query: QueryDslQueryContainer) { return false; } + +/** + * Extract unique influencers from the job or collection of jobs + * @param jobs + */ +export function extractInfluencers(jobs: Job | Job[]): string[] { + if (!Array.isArray(jobs)) { + jobs = [jobs]; + } + const influencers = new Set(); + for (const job of jobs) { + for (const influencer of job.analysis_config.influencers || []) { + influencers.add(influencer); + } + } + return Array.from(influencers); +} diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx index 50da8f132cb6be..10c7003e6e18ae 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx @@ -23,26 +23,18 @@ import { mlNodesAvailable, getMlNodeCount } from '../../ml_nodes_check/check_ml_ import { checkPermission } from '../../capabilities/check_capabilities'; import { MlPageHeader } from '../../components/page_header'; -interface RecognizerModule { - id: string; - title: string; - query: Record; - description: string; - logo: { - icon: string; - }; -} - export const IndexDataVisualizerPage: FC = () => { useTimefilter({ timeRangeSelector: false, autoRefreshSelector: false }); const { services: { - http, docLinks, dataVisualizer, data: { dataViews: { get: getDataView }, }, + mlServices: { + mlApiServices: { recognizeIndex }, + }, }, } = useMlKibana(); const mlLocator = useMlLocator()!; @@ -140,18 +132,14 @@ export const IndexDataVisualizerPage: FC = () => { const getAsyncRecognizedModuleCards = async (params: GetAdditionalLinksParams) => { const { dataViewId, dataViewTitle } = params; try { - const modules = await http.fetch( - `/api/ml/modules/recognize/${dataViewTitle}`, - { - method: 'GET', - } - ); + const modules = await recognizeIndex({ indexPatternTitle: dataViewTitle! }); + return modules?.map( (m): ResultLink => ({ id: m.id, title: m.title, description: m.description, - icon: m.logo.icon, + icon: m.logo?.icon ?? '', type: 'index', getUrl: async () => { return await mlLocator.getUrl({ diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx index 309b751a0da5d1..ef63ca2ed270f2 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx @@ -13,6 +13,7 @@ import moment from 'moment'; import { FullTimeRangeSelector, FROZEN_TIER_PREFERENCE } from '@kbn/ml-date-picker'; import { useTimefilter, type GetTimeFieldRangeResponse } from '@kbn/ml-date-picker'; import { useStorage } from '@kbn/ml-local-storage'; +import { ML_INTERNAL_BASE_PATH } from '../../../../../../../common/constants/app'; import { WizardNav } from '../wizard_nav'; import { StepProps, WIZARD_STEPS } from '../step_types'; import { JobCreatorContext } from '../job_creator_context'; @@ -135,7 +136,7 @@ export const TimeRangeStep: FC = ({ setCurrentStep, isCurrentStep }) disabled={false} callback={fullTimeRangeCallback} timefilter={timefilter} - apiPath="/api/ml/fields_service/time_field_range" + apiPath={`${ML_INTERNAL_BASE_PATH}/fields_service/time_field_range`} /> diff --git a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts index 1601a5d6cceeae..304ee7399940ce 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts @@ -7,25 +7,23 @@ import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; -import { Job, JobId } from '../../../common/types/anomaly_detection_jobs'; -import { basePath } from './ml_api_service'; +import type { Job, JobId } from '../../../common/types/anomaly_detection_jobs'; import { HttpService } from './http_service'; +import { type MlApiServices, mlApiServicesProvider } from './ml_api_service'; export class AnomalyDetectorService { - private readonly apiBasePath = basePath() + '/anomaly_detectors'; + private mlApiServices: MlApiServices; - constructor(private httpService: HttpService) {} + constructor(httpService: HttpService) { + this.mlApiServices = mlApiServicesProvider(httpService); + } /** * Fetches a single job object * @param jobId */ getJobById$(jobId: JobId): Observable { - return this.httpService - .http$<{ count: number; jobs: Job[] }>({ - path: `${this.apiBasePath}/${jobId}`, - }) - .pipe(map((response) => response.jobs[0])); + return this.getJobs$([jobId]).pipe(map((jobs) => jobs[0])); } /** @@ -33,27 +31,8 @@ export class AnomalyDetectorService { * @param jobIds */ getJobs$(jobIds: JobId[]): Observable { - return this.httpService - .http$<{ count: number; jobs: Job[] }>({ - path: `${this.apiBasePath}/${jobIds.join(',')}`, - }) + return this.mlApiServices + .getJobs$({ jobId: jobIds.join(',') }) .pipe(map((response) => response.jobs)); } - - /** - * Extract unique influencers from the job or collection of jobs - * @param jobs - */ - extractInfluencers(jobs: Job | Job[]): string[] { - if (!Array.isArray(jobs)) { - jobs = [jobs]; - } - const influencers = new Set(); - for (const job of jobs) { - for (const influencer of job.analysis_config.influencers || []) { - influencers.add(influencer); - } - } - return Array.from(influencers); - } } diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/alerting.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/alerting.ts index 57f0510314cdcc..1f94fbf3342896 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/alerting.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/alerting.ts @@ -8,7 +8,7 @@ import { useMemo } from 'react'; import { HttpService } from '../http_service'; import { useMlKibana } from '../../contexts/kibana'; -import { ML_BASE_PATH } from '../../../../common/constants/app'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import type { MlAnomalyDetectionAlertParams, PreviewResponse, @@ -23,9 +23,10 @@ export const alertingApiProvider = (httpService: HttpService) => { }): Promise { const body = JSON.stringify(params); return httpService.http({ - path: `${ML_BASE_PATH}/alerting/preview`, + path: `${ML_INTERNAL_BASE_PATH}/alerting/preview`, method: 'POST', body, + version: '1', }); }, }; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts index 093d85169264cf..1f15b98a6fa2ca 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts @@ -6,10 +6,10 @@ */ import { useMemo } from 'react'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { HttpService } from '../http_service'; import { useMlKibana } from '../../contexts/kibana'; import type { Annotation, GetAnnotationsResponse } from '../../../../common/types/annotations'; -import { basePath } from '.'; export const annotationsApiProvider = (httpService: HttpService) => ({ getAnnotations$(obj: { @@ -22,9 +22,10 @@ export const annotationsApiProvider = (httpService: HttpService) => ({ }) { const body = JSON.stringify(obj); return httpService.http$({ - path: `${basePath()}/annotations`, + path: `${ML_INTERNAL_BASE_PATH}/annotations`, method: 'POST', body, + version: '1', }); }, @@ -38,24 +39,27 @@ export const annotationsApiProvider = (httpService: HttpService) => ({ }) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/annotations`, + path: `${ML_INTERNAL_BASE_PATH}/annotations`, method: 'POST', body, + version: '1', }); }, indexAnnotation(obj: Annotation) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/annotations/index`, + path: `${ML_INTERNAL_BASE_PATH}/annotations/index`, method: 'PUT', body, + version: '1', }); }, deleteAnnotation(id: string) { return httpService.http({ - path: `${basePath()}/annotations/delete/${id}`, + path: `${ML_INTERNAL_BASE_PATH}/annotations/delete/${id}`, method: 'DELETE', + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts index b7ba26de984b02..d89018c5fd8d84 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -6,10 +6,10 @@ */ import { useMemo } from 'react'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { HttpService } from '../http_service'; import { useMlKibana } from '../../contexts/kibana'; -import { basePath } from '.'; import type { DataFrameAnalyticsStats } from '../../data_frame_analytics/pages/analytics_management/components/analytics_list/common'; import type { ValidateAnalyticsJobResponse } from '../../../../common/constants/validation'; import type { DataFrameAnalyticsConfig } from '../../data_frame_analytics/common'; @@ -58,22 +58,25 @@ export const dataFrameAnalyticsApiProvider = (httpService: HttpService) => ({ getDataFrameAnalytics(analyticsId?: string, excludeGenerated?: boolean, size?: number) { const analyticsIdString = analyticsId !== undefined ? `/${analyticsId}` : ''; return httpService.http({ - path: `${basePath()}/data_frame/analytics${analyticsIdString}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics${analyticsIdString}`, method: 'GET', ...(excludeGenerated ? { query: { excludeGenerated, size } } : {}), + version: '1', }); }, getDataFrameAnalyticsStats(analyticsId?: string) { if (analyticsId !== undefined) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}/_stats`, method: 'GET', + version: '1', }); } return httpService.http({ - path: `${basePath()}/data_frame/analytics/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/_stats`, method: 'GET', + version: '1', }); }, createDataFrameAnalytics( @@ -82,17 +85,19 @@ export const dataFrameAnalyticsApiProvider = (httpService: HttpService) => ({ ) { const body = JSON.stringify(analyticsConfig); return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}`, method: 'PUT', body, + version: '1', }); }, updateDataFrameAnalytics(analyticsId: string, updateConfig: UpdateDataFrameAnalyticsConfig) { const body = JSON.stringify(updateConfig); return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}/_update`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}/_update`, method: 'POST', body, + version: '1', }); }, getDataFrameAnalyticsMap( @@ -102,39 +107,44 @@ export const dataFrameAnalyticsApiProvider = (httpService: HttpService) => ({ ): Promise { const idString = id !== undefined ? `/${id}` : ''; return httpService.http({ - path: `${basePath()}/data_frame/analytics/map${idString}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/map${idString}`, method: 'GET', query: { treatAsRoot, type }, + version: '1', }); }, jobsExist(analyticsIds: string[], allSpaces: boolean = false) { const body = JSON.stringify({ analyticsIds, allSpaces }); return httpService.http({ - path: `${basePath()}/data_frame/analytics/jobs_exist`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/jobs_exist`, method: 'POST', body, + version: '1', }); }, evaluateDataFrameAnalytics(evaluateConfig: any) { const body = JSON.stringify(evaluateConfig); return httpService.http({ - path: `${basePath()}/data_frame/_evaluate`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/_evaluate`, method: 'POST', body, + version: '1', }); }, explainDataFrameAnalytics(jobConfig: DeepPartial) { const body = JSON.stringify(jobConfig); return httpService.http({ - path: `${basePath()}/data_frame/analytics/_explain`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/_explain`, method: 'POST', body, + version: '1', }); }, deleteDataFrameAnalytics(analyticsId: string) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}`, method: 'DELETE', + version: '1', }); }, deleteDataFrameAnalyticsAndDestIndex( @@ -143,44 +153,50 @@ export const dataFrameAnalyticsApiProvider = (httpService: HttpService) => ({ deleteDestIndexPattern: boolean ) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}`, query: { deleteDestIndex, deleteDestIndexPattern }, method: 'DELETE', + version: '1', }); }, startDataFrameAnalytics(analyticsId: string) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}/_start`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}/_start`, method: 'POST', + version: '1', }); }, stopDataFrameAnalytics(analyticsId: string, force: boolean = false) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}/_stop`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}/_stop`, method: 'POST', query: { force }, + version: '1', }); }, getAnalyticsAuditMessages(analyticsId: string) { return httpService.http({ - path: `${basePath()}/data_frame/analytics/${analyticsId}/messages`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/${analyticsId}/messages`, method: 'GET', + version: '1', }); }, validateDataFrameAnalytics(analyticsConfig: DeepPartial) { const body = JSON.stringify(analyticsConfig); return httpService.http({ - path: `${basePath()}/data_frame/analytics/validate`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/validate`, method: 'POST', body, + version: '1', }); }, newJobCapsAnalytics(indexPatternTitle: string, isRollup: boolean = false) { const query = isRollup === true ? { rollup: true } : {}; return httpService.http({ - path: `${basePath()}/data_frame/analytics/new_job_caps/${indexPatternTitle}`, + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/new_job_caps/${indexPatternTitle}`, method: 'GET', query, + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/filters.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/filters.ts index 882b785e388894..c4dbff3cac1f8c 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/filters.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/filters.ts @@ -8,25 +8,27 @@ // Service for querying filters, which hold lists of entities, // for example a list of known safe URL domains. import { useMemo } from 'react'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { HttpService } from '../http_service'; import { useMlKibana } from '../../contexts/kibana'; -import { basePath } from '.'; import type { Filter, FilterStats } from '../../../../common/types/filters'; export const filtersApiProvider = (httpService: HttpService) => ({ filters(obj?: { filterId?: string }) { const filterId = obj && obj.filterId ? `/${obj.filterId}` : ''; return httpService.http({ - path: `${basePath()}/filters${filterId}`, + path: `${ML_INTERNAL_BASE_PATH}/filters${filterId}`, method: 'GET', + version: '1', }); }, filtersStats() { return httpService.http({ - path: `${basePath()}/filters/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/filters/_stats`, method: 'GET', + version: '1', }); }, @@ -37,8 +39,9 @@ export const filtersApiProvider = (httpService: HttpService) => ({ items, }); return httpService.http({ - path: `${basePath()}/filters`, + path: `${ML_INTERNAL_BASE_PATH}/filters`, method: 'PUT', + version: '1', body, }); }, @@ -51,16 +54,18 @@ export const filtersApiProvider = (httpService: HttpService) => ({ }); return httpService.http({ - path: `${basePath()}/filters/${filterId}`, + path: `${ML_INTERNAL_BASE_PATH}/filters/${filterId}`, method: 'PUT', body, + version: '1', }); }, deleteFilter(filterId: string) { return httpService.http<{ acknowledged: boolean }>({ - path: `${basePath()}/filters/${filterId}`, + path: `${ML_INTERNAL_BASE_PATH}/filters/${filterId}`, method: 'DELETE', + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts index c242b0e58832dd..c7c3f275ab7c9c 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts @@ -8,6 +8,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { Observable } from 'rxjs'; import type { HttpStart } from '@kbn/core/public'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { jsonSchemaProvider } from './json_schema'; import { HttpService } from '../http_service'; @@ -41,7 +42,11 @@ import type { IndicesOptions, } from '../../../../common/types/anomaly_detection_jobs'; import type { FieldHistogramRequestConfig } from '../../datavisualizer/index_based/common/request'; -import type { DataRecognizerConfigResponse, Module } from '../../../../common/types/modules'; +import type { + DataRecognizerConfigResponse, + Module, + RecognizeResult, +} from '../../../../common/types/modules'; import { getHttp } from '../../util/dependency_cache'; import type { RuntimeMappings } from '../../../../common/types/fields'; import type { DatafeedValidationResponse } from '../../../../common/types/job_validation'; @@ -89,10 +94,6 @@ export interface GetModelSnapshotsResponse { model_snapshots: ModelSnapshot[]; } -export function basePath() { - return '/api/ml'; -} - /** * Temp solution to allow {@link ml} service to use http from * the dependency_cache. @@ -120,83 +121,102 @@ export function mlApiServicesProvider(httpService: HttpService) { getJobs(obj?: { jobId?: string }) { const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; return httpService.http<{ jobs: Job[]; count: number }>({ - path: `${basePath()}/anomaly_detectors${jobId}`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors${jobId}`, + version: '1', + }); + }, + + getJobs$(obj?: { jobId?: string }) { + const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; + return httpService.http$<{ count: number; jobs: Job[] }>({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors${jobId}`, + version: '1', }); }, getJobStats(obj: { jobId?: string }) { const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; return httpService.http<{ jobs: JobStats[]; count: number }>({ - path: `${basePath()}/anomaly_detectors${jobId}/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors${jobId}/_stats`, + version: '1', }); }, addJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify(job); return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}`, method: 'PUT', body, + version: '1', }); }, openJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_open`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_open`, method: 'POST', + version: '1', }); }, closeJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_close`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_close`, method: 'POST', + version: '1', }); }, forceCloseJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_close?force=true`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_close?force=true`, method: 'POST', + version: '1', }); }, deleteJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}`, method: 'DELETE', + version: '1', }); }, forceDeleteJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}?force=true`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}?force=true`, method: 'DELETE', + version: '1', }); }, updateJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify(job); return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_update`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_update`, method: 'POST', body, + version: '1', }); }, resetJob({ jobId }: { jobId: string }) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_reset`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_reset`, method: 'POST', + version: '1', }); }, estimateBucketSpan(obj: BucketSpanEstimatorData) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/validate/estimate_bucket_span`, + path: `${ML_INTERNAL_BASE_PATH}/validate/estimate_bucket_span`, method: 'POST', body, + version: '1', }); }, @@ -210,50 +230,56 @@ export function mlApiServicesProvider(httpService: HttpService) { }) { const body = JSON.stringify(payload); return httpService.http({ - path: `${basePath()}/validate/job`, + path: `${ML_INTERNAL_BASE_PATH}/validate/job`, method: 'POST', body, + version: '1', }); }, validateDatafeedPreview(payload: { job: CombinedJob; start?: number; end?: number }) { const body = JSON.stringify(payload); return httpService.http({ - path: `${basePath()}/validate/datafeed_preview`, + path: `${ML_INTERNAL_BASE_PATH}/validate/datafeed_preview`, method: 'POST', body, + version: '1', }); }, validateCardinality$(job: CombinedJob): Observable { const body = JSON.stringify(job); return httpService.http$({ - path: `${basePath()}/validate/cardinality`, + path: `${ML_INTERNAL_BASE_PATH}/validate/cardinality`, method: 'POST', body, + version: '1', }); }, getDatafeeds(obj: { datafeedId: string }) { const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; return httpService.http({ - path: `${basePath()}/datafeeds${datafeedId}`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds${datafeedId}`, + version: '1', }); }, getDatafeedStats(obj: { datafeedId: string }) { const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; return httpService.http({ - path: `${basePath()}/datafeeds${datafeedId}/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds${datafeedId}/_stats`, + version: '1', }); }, addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { const body = JSON.stringify(datafeedConfig); return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}`, method: 'PUT', body, + version: '1', }); }, @@ -266,23 +292,26 @@ export function mlApiServicesProvider(httpService: HttpService) { }) { const body = JSON.stringify(datafeedConfig); return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}/_update`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}/_update`, method: 'POST', body, + version: '1', }); }, deleteDatafeed({ datafeedId }: { datafeedId: string }) { return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}`, method: 'DELETE', + version: '1', }); }, forceDeleteDatafeed({ datafeedId }: { datafeedId: string }) { return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}?force=true`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}?force=true`, method: 'DELETE', + version: '1', }); }, @@ -301,37 +330,41 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}/_start`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}/_start`, method: 'POST', body, + version: '1', }); }, stopDatafeed({ datafeedId }: { datafeedId: string }) { return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}/_stop`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}/_stop`, method: 'POST', + version: '1', }); }, forceStopDatafeed({ datafeedId }: { datafeedId: string }) { return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}/_stop?force=true`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}/_stop?force=true`, method: 'POST', + version: '1', }); }, datafeedPreview({ datafeedId }: { datafeedId: string }) { return httpService.http({ - path: `${basePath()}/datafeeds/${datafeedId}/_preview`, + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/${datafeedId}/_preview`, method: 'GET', + version: '1', }); }, validateDetector({ detector }: { detector: Detector }) { const body = JSON.stringify(detector); return httpService.http({ - path: `${basePath()}/anomaly_detectors/_validate/detector`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/_validate/detector`, method: 'POST', body, }); @@ -343,9 +376,10 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/_forecast`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_forecast`, method: 'POST', body, + version: '1', }); }, @@ -372,25 +406,28 @@ export function mlApiServicesProvider(httpService: HttpService) { ...(overallScore ? { overall_score: overallScore } : {}), }); return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/results/overall_buckets`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/results/overall_buckets`, method: 'POST', body, + version: '1', }); }, hasPrivileges(obj: any) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/_has_privileges`, + path: `${ML_INTERNAL_BASE_PATH}/_has_privileges`, method: 'POST', body, + version: '1', }); }, checkMlCapabilities() { return httpService.http({ - path: `${basePath()}/ml_capabilities`, + path: `${ML_INTERNAL_BASE_PATH}/ml_capabilities`, method: 'GET', + version: '1', }); }, @@ -398,9 +435,10 @@ export function mlApiServicesProvider(httpService: HttpService) { const body = JSON.stringify({ indices }); return httpService.http>({ - path: `${basePath()}/index_exists`, + path: `${ML_INTERNAL_BASE_PATH}/index_exists`, method: 'POST', body, + version: '1', }); }, @@ -411,37 +449,42 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/indices/field_caps`, + path: `${ML_INTERNAL_BASE_PATH}/indices/field_caps`, method: 'POST', body, + version: '1', }); }, recognizeIndex({ indexPatternTitle }: { indexPatternTitle: string }) { - return httpService.http({ - path: `${basePath()}/modules/recognize/${indexPatternTitle}`, + return httpService.http({ + path: `${ML_INTERNAL_BASE_PATH}/modules/recognize/${indexPatternTitle}`, method: 'GET', + version: '1', }); }, listDataRecognizerModules() { return httpService.http({ - path: `${basePath()}/modules/get_module`, + path: `${ML_INTERNAL_BASE_PATH}/modules/get_module`, method: 'GET', + version: '1', }); }, getDataRecognizerModule({ moduleId }: { moduleId: string }) { return httpService.http({ - path: `${basePath()}/modules/get_module/${moduleId}`, + path: `${ML_INTERNAL_BASE_PATH}/modules/get_module/${moduleId}`, method: 'GET', + version: '1', }); }, dataRecognizerModuleJobsExist({ moduleId }: { moduleId: string }) { return httpService.http({ - path: `${basePath()}/modules/jobs_exist/${moduleId}`, + path: `${ML_INTERNAL_BASE_PATH}/modules/jobs_exist/${moduleId}`, method: 'GET', + version: '1', }); }, @@ -484,9 +527,10 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/modules/setup/${moduleId}`, + path: `${ML_INTERNAL_BASE_PATH}/modules/setup/${moduleId}`, method: 'POST', body, + version: '1', }); }, @@ -511,9 +555,10 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/data_visualizer/get_field_histograms/${indexPattern}`, + path: `${ML_INTERNAL_BASE_PATH}/data_visualizer/get_field_histograms/${indexPattern}`, method: 'POST', body, + version: '1', }); }, @@ -531,17 +576,19 @@ export function mlApiServicesProvider(httpService: HttpService) { calendarIdsPathComponent = `/${calendarIds.join(',')}`; } return httpService.http({ - path: `${basePath()}/calendars${calendarIdsPathComponent}`, + path: `${ML_INTERNAL_BASE_PATH}/calendars${calendarIdsPathComponent}`, method: 'GET', + version: '1', }); }, addCalendar(obj: Calendar) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/calendars`, + path: `${ML_INTERNAL_BASE_PATH}/calendars`, method: 'PUT', body, + version: '1', }); }, @@ -549,30 +596,34 @@ export function mlApiServicesProvider(httpService: HttpService) { const calendarId = obj && obj.calendarId ? `/${obj.calendarId}` : ''; const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/calendars${calendarId}`, + path: `${ML_INTERNAL_BASE_PATH}/calendars${calendarId}`, method: 'PUT', body, + version: '1', }); }, deleteCalendar({ calendarId }: { calendarId?: string }) { return httpService.http({ - path: `${basePath()}/calendars/${calendarId}`, + path: `${ML_INTERNAL_BASE_PATH}/calendars/${calendarId}`, method: 'DELETE', + version: '1', }); }, mlNodeCount() { return httpService.http({ - path: `${basePath()}/ml_node_count`, + path: `${ML_INTERNAL_BASE_PATH}/ml_node_count`, method: 'GET', + version: '1', }); }, mlInfo() { return httpService.http({ - path: `${basePath()}/info`, + path: `${ML_INTERNAL_BASE_PATH}/info`, method: 'GET', + version: '1', }); }, @@ -604,9 +655,10 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http$<{ modelMemoryLimit: string }>({ - path: `${basePath()}/validate/calculate_model_memory_limit`, + path: `${ML_INTERNAL_BASE_PATH}/validate/calculate_model_memory_limit`, method: 'POST', body, + version: '1', }); }, @@ -635,9 +687,10 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/fields_service/field_cardinality`, + path: `${ML_INTERNAL_BASE_PATH}/fields_service/field_cardinality`, method: 'POST', body, + version: '1', }); }, @@ -666,27 +719,30 @@ export function mlApiServicesProvider(httpService: HttpService) { }); return httpService.http({ - path: `${basePath()}/fields_service/time_field_range`, + path: `${ML_INTERNAL_BASE_PATH}/fields_service/time_field_range`, method: 'POST', body, + version: '1', }); }, esSearch(obj: any) { const body = JSON.stringify(obj); return httpService.http({ - path: `${basePath()}/es_search`, + path: `${ML_INTERNAL_BASE_PATH}/es_search`, method: 'POST', body, + version: '1', }); }, esSearch$(obj: any) { const body = JSON.stringify(obj); return httpService.http$({ - path: `${basePath()}/es_search`, + path: `${ML_INTERNAL_BASE_PATH}/es_search`, method: 'POST', body, + version: '1', }); }, @@ -695,14 +751,16 @@ export function mlApiServicesProvider(httpService: HttpService) { return httpService.http>({ path: `${tempBasePath}/index_management/indices`, method: 'GET', + version: '1', }); }, getModelSnapshots(jobId: string, snapshotId?: string) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/model_snapshots${ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/model_snapshots${ snapshotId !== undefined ? `/${snapshotId}` : '' }`, + version: '1', }); }, @@ -712,16 +770,18 @@ export function mlApiServicesProvider(httpService: HttpService) { body: { description?: string; retain?: boolean } ) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/model_snapshots/${snapshotId}/_update`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/model_snapshots/${snapshotId}/_update`, method: 'POST', body: JSON.stringify(body), + version: '1', }); }, deleteModelSnapshot(jobId: string, snapshotId: string) { return httpService.http({ - path: `${basePath()}/anomaly_detectors/${jobId}/model_snapshots/${snapshotId}`, + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/model_snapshots/${snapshotId}`, method: 'DELETE', + version: '1', }); }, diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/jobs.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/jobs.ts index 1ab3a659442b17..08353144c67394 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/jobs.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/jobs.ts @@ -36,22 +36,24 @@ import type { BulkCreateResults, ResetJobsResponse, } from '../../../../common/types/job_service'; -import { ML_BASE_PATH } from '../../../../common/constants/app'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; export const jobsApiProvider = (httpService: HttpService) => ({ jobsSummary(jobIds: string[]) { const body = JSON.stringify({ jobIds }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/jobs_summary`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_summary`, method: 'POST', body, + version: '1', }); }, jobIdsWithGeo() { return httpService.http({ - path: `${ML_BASE_PATH}/jobs/jobs_with_geo`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_with_geo`, method: 'GET', + version: '1', }); }, @@ -61,43 +63,48 @@ export const jobsApiProvider = (httpService: HttpService) => ({ jobs: MlJobWithTimeRange[]; jobsMap: Dictionary; }>({ - path: `${ML_BASE_PATH}/jobs/jobs_with_time_range`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_with_time_range`, method: 'POST', body, + version: '1', }); }, jobForCloning(jobId: string) { const body = JSON.stringify({ jobId }); return httpService.http<{ job?: Job; datafeed?: Datafeed } | undefined>({ - path: `${ML_BASE_PATH}/jobs/job_for_cloning`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/job_for_cloning`, method: 'POST', body, + version: '1', }); }, jobs(jobIds: string[]) { const body = JSON.stringify({ jobIds }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/jobs`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs`, method: 'POST', body, + version: '1', }); }, groups() { return httpService.http({ - path: `${ML_BASE_PATH}/jobs/groups`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/groups`, method: 'GET', + version: '1', }); }, updateGroups(updatedJobs: Array<{ jobId: string; groups: string[] }>) { const body = JSON.stringify({ jobs: updatedJobs }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/update_groups`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/update_groups`, method: 'POST', body, + version: '1', }); }, @@ -109,54 +116,60 @@ export const jobsApiProvider = (httpService: HttpService) => ({ }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/force_start_datafeeds`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/force_start_datafeeds`, method: 'POST', body, + version: '1', }); }, stopDatafeeds(datafeedIds: string[]) { const body = JSON.stringify({ datafeedIds }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/stop_datafeeds`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/stop_datafeeds`, method: 'POST', body, + version: '1', }); }, deleteJobs(jobIds: string[], deleteUserAnnotations?: boolean) { const body = JSON.stringify({ jobIds, deleteUserAnnotations }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/delete_jobs`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/delete_jobs`, method: 'POST', body, + version: '1', }); }, closeJobs(jobIds: string[]) { const body = JSON.stringify({ jobIds }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/close_jobs`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/close_jobs`, method: 'POST', body, + version: '1', }); }, resetJobs(jobIds: string[], deleteUserAnnotations?: boolean) { const body = JSON.stringify({ jobIds, deleteUserAnnotations }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/reset_jobs`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/reset_jobs`, method: 'POST', body, + version: '1', }); }, forceStopAndCloseJob(jobId: string) { const body = JSON.stringify({ jobId }); return httpService.http<{ success: boolean }>({ - path: `${ML_BASE_PATH}/jobs/force_stop_and_close_job`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/force_stop_and_close_job`, method: 'POST', body, + version: '1', }); }, @@ -178,52 +191,58 @@ export const jobsApiProvider = (httpService: HttpService) => ({ }; return httpService.http<{ messages: JobMessage[]; notificationIndices: string[] }>({ - path: `${ML_BASE_PATH}/job_audit_messages/messages${jobIdString}`, + path: `${ML_INTERNAL_BASE_PATH}/job_audit_messages/messages${jobIdString}`, method: 'GET', query, + version: '1', }); }, clearJobAuditMessages(jobId: string, notificationIndices: string[]) { const body = JSON.stringify({ jobId, notificationIndices }); return httpService.http<{ success: boolean; latest_cleared: number }>({ - path: `${ML_BASE_PATH}/job_audit_messages/clear_messages`, + path: `${ML_INTERNAL_BASE_PATH}/job_audit_messages/clear_messages`, method: 'PUT', body, + version: '1', }); }, blockingJobTasks() { return httpService.http>({ - path: `${ML_BASE_PATH}/jobs/blocking_jobs_tasks`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/blocking_jobs_tasks`, method: 'GET', + version: '1', }); }, jobsExist(jobIds: string[], allSpaces: boolean = false) { const body = JSON.stringify({ jobIds, allSpaces }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/jobs_exist`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_exist`, method: 'POST', body, + version: '1', }); }, jobsExist$(jobIds: string[], allSpaces: boolean = false): Observable { const body = JSON.stringify({ jobIds, allSpaces }); return httpService.http$({ - path: `${ML_BASE_PATH}/jobs/jobs_exist`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_exist`, method: 'POST', body, + version: '1', }); }, newJobCaps(indexPatternTitle: string, isRollup: boolean = false) { const query = isRollup === true ? { rollup: true } : {}; return httpService.http({ - path: `${ML_BASE_PATH}/jobs/new_job_caps/${indexPatternTitle}`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_caps/${indexPatternTitle}`, method: 'GET', query, + version: '1', }); }, @@ -254,9 +273,10 @@ export const jobsApiProvider = (httpService: HttpService) => ({ indicesOptions, }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/new_job_line_chart`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_line_chart`, method: 'POST', body, + version: '1', }); }, @@ -285,16 +305,18 @@ export const jobsApiProvider = (httpService: HttpService) => ({ indicesOptions, }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/new_job_population_chart`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_population_chart`, method: 'POST', body, + version: '1', }); }, getAllJobAndGroupIds() { return httpService.http({ - path: `${ML_BASE_PATH}/jobs/all_jobs_and_group_ids`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/all_jobs_and_group_ids`, method: 'GET', + version: '1', }); }, @@ -305,9 +327,10 @@ export const jobsApiProvider = (httpService: HttpService) => ({ end, }); return httpService.http<{ progress: number; isRunning: boolean; isJobClosed: boolean }>({ - path: `${ML_BASE_PATH}/jobs/look_back_progress`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/look_back_progress`, method: 'POST', body, + version: '1', }); }, @@ -341,9 +364,10 @@ export const jobsApiProvider = (httpService: HttpService) => ({ overallValidStatus: CATEGORY_EXAMPLES_VALIDATION_STATUS; validationChecks: FieldExampleCheck[]; }>({ - path: `${ML_BASE_PATH}/jobs/categorization_field_examples`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/categorization_field_examples`, method: 'POST', body, + version: '1', }); }, @@ -353,9 +377,10 @@ export const jobsApiProvider = (httpService: HttpService) => ({ total: number; categories: Array<{ count?: number; category: Category }>; }>({ - path: `${ML_BASE_PATH}/jobs/top_categories`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/top_categories`, method: 'POST', body, + version: '1', }); }, @@ -370,27 +395,30 @@ export const jobsApiProvider = (httpService: HttpService) => ({ return httpService.http<{ success: boolean; }>({ - path: `${ML_BASE_PATH}/jobs/revert_model_snapshot`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/revert_model_snapshot`, method: 'POST', body, + version: '1', }); }, datafeedPreview(datafeedId?: string, job?: Job, datafeed?: Datafeed) { const body = JSON.stringify({ datafeedId, job, datafeed }); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/datafeed_preview`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/datafeed_preview`, method: 'POST', body, + version: '1', }); }, bulkCreateJobs(jobs: { job: Job; datafeed: Datafeed } | Array<{ job: Job; datafeed: Datafeed }>) { const body = JSON.stringify(jobs); return httpService.http({ - path: `${ML_BASE_PATH}/jobs/bulk_create`, + path: `${ML_INTERNAL_BASE_PATH}/jobs/bulk_create`, method: 'POST', body, + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/json_schema.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/json_schema.ts index aa630cd51d5cd7..bb4a9759e3e709 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/json_schema.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/json_schema.ts @@ -7,9 +7,9 @@ import { omitBy } from 'lodash'; import { isDefined } from '@kbn/ml-is-defined'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { type SupportedPath } from '../../../../common/api_schemas/json_schema_schema'; import { HttpService } from '../http_service'; -import { basePath } from '.'; export interface GetSchemaDefinitionParams { path: SupportedPath; @@ -17,14 +17,13 @@ export interface GetSchemaDefinitionParams { } export function jsonSchemaProvider(httpService: HttpService) { - const apiBasePath = basePath(); - return { getSchemaDefinition(params: GetSchemaDefinitionParams) { return httpService.http({ - path: `${apiBasePath}/json_schema`, + path: `${ML_INTERNAL_BASE_PATH}/json_schema`, method: 'GET', query: omitBy(params, (v) => !isDefined(v)), + version: '1', }); }, }; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/management.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/management.ts index 71df618cfa7be4..73740151257fa5 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/management.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/management.ts @@ -6,8 +6,8 @@ */ import { useMemo } from 'react'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { HttpService } from '../http_service'; -import { basePath } from '.'; import { useMlKibana } from '../../contexts/kibana'; import type { TrainedModelStat } from '../../../../common/types/trained_models'; import type { ManagementListResponse } from '../../../../common/types/management'; @@ -47,8 +47,6 @@ export interface InferenceStatsResponse { * @param httpService */ export function managementApiProvider(httpService: HttpService) { - const apiBasePath = basePath(); - return { /** * Fetches lists of anomaly detection jobs, data frame analytics jobs or trained models @@ -58,8 +56,9 @@ export function managementApiProvider(httpService: HttpService) { */ getList(mlSavedObjectType: MlSavedObjectType) { return httpService.http({ - path: `${apiBasePath}/management/list/${mlSavedObjectType}`, + path: `${ML_INTERNAL_BASE_PATH}/management/list/${mlSavedObjectType}`, method: 'GET', + version: '1', }); }, }; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/notifications.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/notifications.ts index fd6f7bd708cd4c..c67ba9a63e3cb9 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/notifications.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/notifications.ts @@ -7,11 +7,11 @@ import { omitBy } from 'lodash'; import { isDefined } from '@kbn/ml-is-defined'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import type { NotificationsQueryParams, NotificationsSearchResponse, } from '../../../../common/types/notifications'; -import { basePath } from '.'; import type { HttpService } from '../http_service'; import type { NotificationsCountQueryParams, @@ -19,22 +19,22 @@ import type { } from '../../../../common/types/notifications'; export function notificationsProvider(httpService: HttpService) { - const apiBasePath = basePath(); - return { findMessages(params: NotificationsQueryParams) { return httpService.http({ - path: `${apiBasePath}/notifications`, + path: `${ML_INTERNAL_BASE_PATH}/notifications`, method: 'GET', query: omitBy(params, (v) => !isDefined(v)), + version: '1', }); }, countMessages$(params: NotificationsCountQueryParams) { return httpService.http$({ - path: `${apiBasePath}/notifications/count`, + path: `${ML_INTERNAL_BASE_PATH}/notifications/count`, method: 'GET', query: omitBy(params, (v) => !isDefined(v)), + version: '1', }); }, }; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts index ee74bedb795ac2..87ca7cde2287ea 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts @@ -17,6 +17,7 @@ import { ML_JOB_ID, ML_PARTITION_FIELD_VALUE, } from '@kbn/ml-anomaly-utils'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import type { GetStoppedPartitionResult, GetDatafeedResultsChartDataResult, @@ -31,8 +32,6 @@ import type { HttpService } from '../http_service'; import type { CriteriaField } from '../results_service'; import type { PartitionFieldsDefinition } from '../results_service/result_service_rx'; -import { basePath } from '.'; - export interface CategoryDefinition { categoryId: number; terms: string; @@ -71,9 +70,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ }); return httpService.http$({ - path: `${basePath()}/results/anomalies_table_data`, + path: `${ML_INTERNAL_BASE_PATH}/results/anomalies_table_data`, method: 'POST', body, + version: '1', }); }, @@ -84,18 +84,20 @@ export const resultsApiProvider = (httpService: HttpService) => ({ latestMs, }); return httpService.http({ - path: `${basePath()}/results/max_anomaly_score`, + path: `${ML_INTERNAL_BASE_PATH}/results/max_anomaly_score`, method: 'POST', body, + version: '1', }); }, getCategoryDefinition(jobId: string, categoryId: string) { const body = JSON.stringify({ jobId, categoryId }); return httpService.http({ - path: `${basePath()}/results/category_definition`, + path: `${ML_INTERNAL_BASE_PATH}/results/category_definition`, method: 'POST', body, + version: '1', }); }, @@ -106,9 +108,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ maxExamples, }); return httpService.http({ - path: `${basePath()}/results/category_examples`, + path: `${ML_INTERNAL_BASE_PATH}/results/category_examples`, method: 'POST', body, + version: '1', }); }, @@ -129,27 +132,30 @@ export const resultsApiProvider = (httpService: HttpService) => ({ fieldsConfig, }); return httpService.http$({ - path: `${basePath()}/results/partition_fields_values`, + path: `${ML_INTERNAL_BASE_PATH}/results/partition_fields_values`, method: 'POST', body, + version: '1', }); }, anomalySearch(query: ESSearchRequest, jobIds: string[]) { const body = JSON.stringify({ query, jobIds }); return httpService.http>({ - path: `${basePath()}/results/anomaly_search`, + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_search`, method: 'POST', body, + version: '1', }); }, anomalySearch$(query: ESSearchRequest, jobIds: string[]) { const body = JSON.stringify({ query, jobIds }); return httpService.http$>({ - path: `${basePath()}/results/anomaly_search`, + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_search`, method: 'POST', body, + version: '1', }); }, @@ -162,9 +168,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ fieldToBucket, }); return httpService.http({ - path: `${basePath()}/results/category_stopped_partitions`, + path: `${ML_INTERNAL_BASE_PATH}/results/category_stopped_partitions`, method: 'POST', body, + version: '1', }); }, @@ -175,9 +182,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ end, }); return httpService.http({ - path: `${basePath()}/results/datafeed_results_chart`, + path: `${ML_INTERNAL_BASE_PATH}/results/datafeed_results_chart`, method: 'POST', body, + version: '1', }); }, @@ -204,9 +212,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ timeBounds, }); return httpService.http$({ - path: `${basePath()}/results/anomaly_charts`, + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_charts`, method: 'POST', body, + version: '1', }); }, @@ -229,9 +238,10 @@ export const resultsApiProvider = (httpService: HttpService) => ({ functionDescription, }); return httpService.http$<{ success: boolean; records: MlAnomalyRecordDoc[] }>({ - path: `${basePath()}/results/anomaly_records`, + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_records`, method: 'POST', body, + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/saved_objects.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/saved_objects.ts index 26db1cc7d0f72a..f87040a30e76e6 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/saved_objects.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/saved_objects.ts @@ -8,11 +8,11 @@ // Service for managing job saved objects import { useMemo } from 'react'; +import { ML_INTERNAL_BASE_PATH, ML_EXTERNAL_BASE_PATH } from '../../../../common/constants/app'; import { useMlKibana } from '../../contexts/kibana'; import { HttpService } from '../http_service'; -import { basePath } from '.'; import type { JobType, MlSavedObjectType, @@ -28,8 +28,9 @@ import type { export const savedObjectsApiProvider = (httpService: HttpService) => ({ jobsSpaces() { return httpService.http({ - path: `${basePath()}/saved_objects/jobs_spaces`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/jobs_spaces`, method: 'GET', + version: '1', }); }, updateJobsSpaces( @@ -40,61 +41,69 @@ export const savedObjectsApiProvider = (httpService: HttpService) => ({ ) { const body = JSON.stringify({ jobType, jobIds, spacesToAdd, spacesToRemove }); return httpService.http({ - path: `${basePath()}/saved_objects/update_jobs_spaces`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/update_jobs_spaces`, method: 'POST', body, + version: '1', }); }, removeItemFromCurrentSpace(mlSavedObjectType: MlSavedObjectType, ids: string[]) { const body = JSON.stringify({ mlSavedObjectType, ids }); return httpService.http({ - path: `${basePath()}/saved_objects/remove_item_from_current_space`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/remove_item_from_current_space`, method: 'POST', body, + version: '1', }); }, syncSavedObjects(simulate: boolean = false) { return httpService.http({ - path: `${basePath()}/saved_objects/sync`, + path: `${ML_EXTERNAL_BASE_PATH}/saved_objects/sync`, method: 'GET', query: { simulate }, + version: '2023-05-15', }); }, initSavedObjects(simulate: boolean = false) { return httpService.http({ - path: `${basePath()}/saved_objects/initialize`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/initialize`, method: 'GET', query: { simulate }, + version: '1', }); }, syncCheck(mlSavedObjectType?: MlSavedObjectType) { const body = JSON.stringify({ mlSavedObjectType }); return httpService.http({ - path: `${basePath()}/saved_objects/sync_check`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/sync_check`, method: 'POST', body, + version: '1', }); }, canDeleteMLSpaceAwareItems(mlSavedObjectType: MlSavedObjectType, ids: string[]) { const body = JSON.stringify({ ids }); return httpService.http({ - path: `${basePath()}/saved_objects/can_delete_ml_space_aware_item/${mlSavedObjectType}`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/can_delete_ml_space_aware_item/${mlSavedObjectType}`, method: 'POST', body, + version: '1', }); }, trainedModelsSpaces() { return httpService.http({ - path: `${basePath()}/saved_objects/trained_models_spaces`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/trained_models_spaces`, method: 'GET', + version: '1', }); }, updateModelsSpaces(modelIds: string[], spacesToAdd: string[], spacesToRemove: string[]) { const body = JSON.stringify({ modelIds, spacesToAdd, spacesToRemove }); return httpService.http({ - path: `${basePath()}/saved_objects/update_trained_models_spaces`, + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/update_trained_models_spaces`, method: 'POST', body, + version: '1', }); }, }); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/trained_models.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/trained_models.ts index 5c47b16b26aae2..30abf6f4dd2ead 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/trained_models.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/trained_models.ts @@ -10,9 +10,9 @@ import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { useMemo } from 'react'; import type { HttpFetchQuery } from '@kbn/core/public'; import type { ErrorType } from '@kbn/ml-error-utils'; +import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; import type { MlSavedObjectType } from '../../../../common/types/saved_objects'; import { HttpService } from '../http_service'; -import { basePath } from '.'; import { useMlKibana } from '../../contexts/kibana'; import type { TrainedModelConfigResponse, @@ -55,8 +55,6 @@ export interface InferenceStatsResponse { * @param httpService */ export function trainedModelsApiProvider(httpService: HttpService) { - const apiBasePath = basePath(); - return { /** * Fetches configuration information for a trained inference model. @@ -69,9 +67,10 @@ export function trainedModelsApiProvider(httpService: HttpService) { const model = Array.isArray(modelId) ? modelId.join(',') : modelId; return httpService.http({ - path: `${apiBasePath}/trained_models${model ? `/${model}` : ''}`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models${model ? `/${model}` : ''}`, method: 'GET', ...(params ? { query: params as HttpFetchQuery } : {}), + version: '1', }); }, @@ -86,8 +85,9 @@ export function trainedModelsApiProvider(httpService: HttpService) { const model = Array.isArray(modelId) ? modelId.join(',') : modelId; return httpService.http({ - path: `${apiBasePath}/trained_models${model ? `/${model}` : ''}/_stats`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models${model ? `/${model}` : ''}/_stats`, method: 'GET', + version: '1', }); }, @@ -103,8 +103,9 @@ export function trainedModelsApiProvider(httpService: HttpService) { } return httpService.http({ - path: `${apiBasePath}/trained_models/${model}/pipelines`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${model}/pipelines`, method: 'GET', + version: '1', }); }, @@ -115,15 +116,17 @@ export function trainedModelsApiProvider(httpService: HttpService) { */ deleteTrainedModel(modelId: string) { return httpService.http<{ acknowledge: boolean }>({ - path: `${apiBasePath}/trained_models/${modelId}`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${modelId}`, method: 'DELETE', + version: '1', }); }, getTrainedModelsNodesOverview() { return httpService.http({ - path: `${apiBasePath}/model_management/nodes_overview`, + path: `${ML_INTERNAL_BASE_PATH}/model_management/nodes_overview`, method: 'GET', + version: '1', }); }, @@ -137,9 +140,10 @@ export function trainedModelsApiProvider(httpService: HttpService) { } ) { return httpService.http<{ acknowledge: boolean }>({ - path: `${apiBasePath}/trained_models/${modelId}/deployment/_start`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${modelId}/deployment/_start`, method: 'POST', query: queryParams, + version: '1', }); }, @@ -151,11 +155,12 @@ export function trainedModelsApiProvider(httpService: HttpService) { const force = options?.force; return httpService.http>({ - path: `${apiBasePath}/trained_models/${modelId}/${deploymentsIds.join( + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${modelId}/${deploymentsIds.join( ',' )}/deployment/_stop`, method: 'POST', query: { force }, + version: '1', }); }, @@ -165,9 +170,10 @@ export function trainedModelsApiProvider(httpService: HttpService) { params: { number_of_allocations: number } ) { return httpService.http<{ acknowledge: boolean }>({ - path: `${apiBasePath}/trained_models/${modelId}/${deploymentId}/deployment/_update`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${modelId}/${deploymentId}/deployment/_update`, method: 'POST', body: JSON.stringify(params), + version: '1', }); }, @@ -179,10 +185,11 @@ export function trainedModelsApiProvider(httpService: HttpService) { ) { const body = JSON.stringify(payload); return httpService.http({ - path: `${apiBasePath}/trained_models/infer/${modelId}/${deploymentsId}`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/infer/${modelId}/${deploymentsId}`, method: 'POST', body, ...(timeout ? { query: { timeout } as HttpFetchQuery } : {}), + version: '1', }); }, @@ -195,25 +202,28 @@ export function trainedModelsApiProvider(httpService: HttpService) { docs, }); return httpService.http({ - path: `${apiBasePath}/trained_models/pipeline_simulate`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/pipeline_simulate`, method: 'POST', body, + version: '1', }); }, memoryUsage(type?: MlSavedObjectType, node?: string, showClosedJobs = false) { return httpService.http({ - path: `${apiBasePath}/model_management/memory_usage`, + path: `${ML_INTERNAL_BASE_PATH}/model_management/memory_usage`, method: 'GET', query: { type, node, showClosedJobs }, + version: '1', }); }, putTrainedModelConfig(modelId: string, config: object) { return httpService.http({ - path: `${apiBasePath}/trained_models/${modelId}`, + path: `${ML_INTERNAL_BASE_PATH}/trained_models/${modelId}`, method: 'PUT', body: JSON.stringify(config), + version: '1', }); }, }; diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_setup_flyout.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_setup_flyout.tsx index c65d46d88402ef..a4417faa8e100d 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_setup_flyout.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_setup_flyout.tsx @@ -6,16 +6,16 @@ */ import React from 'react'; -import { CoreStart } from '@kbn/core/public'; -import { lastValueFrom } from 'rxjs'; +import type { CoreStart } from '@kbn/core/public'; import { toMountPoint, wrapWithTheme } from '@kbn/kibana-react-plugin/public'; +import { extractInfluencers } from '../../../common/util/job_utils'; import { VIEW_BY_JOB_LABEL } from '../../application/explorer/explorer_constants'; -import { AnomalyDetectorService } from '../../application/services/anomaly_detector_service'; import { getDefaultExplorerChartsPanelTitle } from './anomaly_charts_embeddable'; import { HttpService } from '../../application/services/http_service'; -import { AnomalyChartsEmbeddableInput } from '..'; +import type { AnomalyChartsEmbeddableInput } from '..'; import { resolveJobSelection } from '../common/resolve_job_selection'; import { AnomalyChartsInitializer } from './anomaly_charts_initializer'; +import { mlApiServicesProvider } from '../../application/services/ml_api_service'; export async function resolveEmbeddableAnomalyChartsUserInput( coreStart: CoreStart, @@ -23,14 +23,14 @@ export async function resolveEmbeddableAnomalyChartsUserInput( ): Promise> { const { http, overlays } = coreStart; - const anomalyDetectorService = new AnomalyDetectorService(new HttpService(http)); + const { getJobs } = mlApiServicesProvider(new HttpService(http)); return new Promise(async (resolve, reject) => { try { const { jobIds } = await resolveJobSelection(coreStart, input?.jobIds); const title = input?.title ?? getDefaultExplorerChartsPanelTitle(jobIds); - const jobs = await lastValueFrom(anomalyDetectorService.getJobs$(jobIds)); - const influencers = anomalyDetectorService.extractInfluencers(jobs); + const { jobs } = await getJobs({ jobId: jobIds.join(',') }); + const influencers = extractInfluencers(jobs); influencers.push(VIEW_BY_JOB_LABEL); const { theme$ } = coreStart.theme; const modalSession = overlays.openModal( diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_setup_flyout.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_setup_flyout.tsx index 98326071b3515c..12073abb5d95fa 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_setup_flyout.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_setup_flyout.tsx @@ -6,16 +6,16 @@ */ import React from 'react'; -import { CoreStart } from '@kbn/core/public'; -import { lastValueFrom } from 'rxjs'; +import type { CoreStart } from '@kbn/core/public'; import { toMountPoint, wrapWithTheme } from '@kbn/kibana-react-plugin/public'; +import { extractInfluencers } from '../../../common/util/job_utils'; import { VIEW_BY_JOB_LABEL } from '../../application/explorer/explorer_constants'; import { AnomalySwimlaneInitializer } from './anomaly_swimlane_initializer'; -import { AnomalyDetectorService } from '../../application/services/anomaly_detector_service'; import { getDefaultSwimlanePanelTitle } from './anomaly_swimlane_embeddable'; import { HttpService } from '../../application/services/http_service'; -import { AnomalySwimlaneEmbeddableInput } from '..'; +import type { AnomalySwimlaneEmbeddableInput } from '..'; import { resolveJobSelection } from '../common/resolve_job_selection'; +import { mlApiServicesProvider } from '../../application/services/ml_api_service'; export async function resolveAnomalySwimlaneUserInput( coreStart: CoreStart, @@ -23,14 +23,14 @@ export async function resolveAnomalySwimlaneUserInput( ): Promise> { const { http, overlays } = coreStart; - const anomalyDetectorService = new AnomalyDetectorService(new HttpService(http)); + const { getJobs } = mlApiServicesProvider(new HttpService(http)); return new Promise(async (resolve, reject) => { try { const { jobIds } = await resolveJobSelection(coreStart, input?.jobIds); const title = input?.title ?? getDefaultSwimlanePanelTitle(jobIds); - const jobs = await lastValueFrom(anomalyDetectorService.getJobs$(jobIds)); - const influencers = anomalyDetectorService.extractInfluencers(jobs); + const { jobs } = await getJobs({ jobId: jobIds.join(',') }); + const influencers = extractInfluencers(jobs); influencers.push(VIEW_BY_JOB_LABEL); const { theme$ } = coreStart.theme; const modalSession = overlays.openModal( diff --git a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 43baf2b5bd0613..e9284a368f69d6 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -40,6 +40,7 @@ import type { DataRecognizerConfigResponse, GeneralDatafeedsOverride, JobSpecificOverride, + RecognizeResult, } from '../../../common/types/modules'; import { isGeneralJobOverride } from '../../../common/types/modules'; import { @@ -80,14 +81,6 @@ interface Config { isSavedObject: boolean; } -export interface RecognizeResult { - id: string; - title: string; - query: any; - description: string; - logo: Logo; -} - interface ObjectExistResult { id: string; type: string; diff --git a/x-pack/plugins/ml/server/models/data_recognizer/index.ts b/x-pack/plugins/ml/server/models/data_recognizer/index.ts index 55595c3a12bde1..56b1a4f51282fe 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/index.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/index.ts @@ -5,5 +5,4 @@ * 2.0. */ -export type { RecognizeResult } from './data_recognizer'; export { DataRecognizer, dataRecognizerFactory } from './data_recognizer'; diff --git a/x-pack/plugins/ml/server/routes/alerting.ts b/x-pack/plugins/ml/server/routes/alerting.ts index 59091e1c8dfb0e..f0decf485df580 100644 --- a/x-pack/plugins/ml/server/routes/alerting.ts +++ b/x-pack/plugins/ml/server/routes/alerting.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { RouteInitialization } from '../types'; import { wrapError } from '../client/error_wrapper'; import { mlAnomalyDetectionAlertPreviewRequest } from './schemas/alerting_schema'; @@ -17,37 +18,44 @@ export function alertingRoutes( /** * @apiGroup Alerting * - * @api {post} /api/ml/alerting/preview Preview alerting condition + * @api {post} /internal/ml/alerting/preview Preview alerting condition * @apiName PreviewAlert * @apiDescription Returns a preview of the alerting condition * * @apiSchema (body) mlAnomalyDetectionAlertPreviewRequest */ - router.post( - { - path: '/api/ml/alerting/preview', - validate: { - body: mlAnomalyDetectionAlertPreviewRequest, - }, + router.versioned + .post({ + access: 'internal', + path: `${ML_INTERNAL_BASE_PATH}/alerting/preview`, options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response, client, context }) => { - try { - const alertingService = sharedServicesProviders.alertingServiceProvider( - (await context.core).savedObjects.client, - request - ); + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: mlAnomalyDetectionAlertPreviewRequest, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response, client, context }) => { + try { + const alertingService = sharedServicesProviders.alertingServiceProvider( + (await context.core).savedObjects.client, + request + ); - const result = await alertingService.preview(request.body); + const result = await alertingService.preview(request.body); - return response.ok({ - body: result, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: result, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/annotations.ts b/x-pack/plugins/ml/server/routes/annotations.ts index eb173688dc2445..dc073928d0513f 100644 --- a/x-pack/plugins/ml/server/routes/annotations.ts +++ b/x-pack/plugins/ml/server/routes/annotations.ts @@ -9,6 +9,7 @@ import Boom from '@hapi/boom'; import { i18n } from '@kbn/i18n'; import { SecurityPluginSetup } from '@kbn/security-plugin/server'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { isAnnotationsFeatureAvailable } from '../lib/check_annotations'; import { annotationServiceProvider } from '../models/annotation_service'; import { wrapError } from '../client/error_wrapper'; @@ -40,7 +41,7 @@ export function annotationRoutes( /** * @apiGroup Annotations * - * @api {post} /api/ml/annotations Gets annotations + * @api {post} /internal/ml/annotations Gets annotations * @apiName GetAnnotations * @apiDescription Gets annotations. * @@ -49,109 +50,124 @@ export function annotationRoutes( * @apiSuccess {Boolean} success * @apiSuccess {Object} annotations */ - router.post( - { - path: '/api/ml/annotations', - validate: { - body: getAnnotationsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/annotations`, + access: 'internal', options: { tags: ['access:ml:canGetAnnotations'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { getAnnotations } = annotationServiceProvider(client); - const resp = await getAnnotations(request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { body: getAnnotationsSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { getAnnotations } = annotationServiceProvider(client); + const resp = await getAnnotations(request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Annotations * - * @api {put} /api/ml/annotations/index Index annotation + * @api {put} /internal/ml/annotations/index Index annotation * @apiName IndexAnnotations * @apiDescription Index the annotation. * * @apiSchema (body) indexAnnotationSchema */ - router.put( - { - path: '/api/ml/annotations/index', - validate: { - body: indexAnnotationSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/annotations/index`, + access: 'internal', options: { tags: ['access:ml:canCreateAnnotation'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable(client); - if (annotationsFeatureAvailable === false) { - throw getAnnotationsFeatureUnavailableErrorMessage(); - } + }) + .addVersion( + { + version: '1', + validate: { + request: { body: indexAnnotationSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable(client); + if (annotationsFeatureAvailable === false) { + throw getAnnotationsFeatureUnavailableErrorMessage(); + } - const { indexAnnotation } = annotationServiceProvider(client); + const { indexAnnotation } = annotationServiceProvider(client); - const currentUser = - securityPlugin !== undefined ? securityPlugin.authc.getCurrentUser(request) : {}; - // @ts-expect-error username doesn't exist on {} - const username = currentUser?.username ?? ANNOTATION_USER_UNKNOWN; - const resp = await indexAnnotation(request.body, username); + const currentUser = + securityPlugin !== undefined ? securityPlugin.authc.getCurrentUser(request) : {}; + // @ts-expect-error username doesn't exist on {} + const username = currentUser?.username ?? ANNOTATION_USER_UNKNOWN; + const resp = await indexAnnotation(request.body, username); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Annotations * - * @api {delete} /api/ml/annotations/delete/:annotationId Deletes annotation + * @api {delete} /internal/ml/annotations/delete/:annotationId Deletes annotation * @apiName DeleteAnnotation * @apiDescription Deletes specified annotation * * @apiSchema (params) deleteAnnotationSchema */ - router.delete( - { - path: '/api/ml/annotations/delete/{annotationId}', - validate: { - params: deleteAnnotationSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/annotations/delete/{annotationId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteAnnotation'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable(client); - if (annotationsFeatureAvailable === false) { - throw getAnnotationsFeatureUnavailableErrorMessage(); - } + }) + .addVersion( + { + version: '1', + validate: { + request: { params: deleteAnnotationSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable(client); + if (annotationsFeatureAvailable === false) { + throw getAnnotationsFeatureUnavailableErrorMessage(); + } - const annotationId = request.params.annotationId; - const { deleteAnnotation } = annotationServiceProvider(client); - const resp = await deleteAnnotation(annotationId); + const annotationId = request.params.annotationId; + const { deleteAnnotation } = annotationServiceProvider(client); + const resp = await deleteAnnotation(annotationId); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts index 8c02fce672c338..82031e5ca64c17 100644 --- a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts @@ -7,6 +7,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/types'; import { schema } from '@kbn/config-schema'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { @@ -34,131 +35,155 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors Get anomaly detectors data + * @api {get} /internal/ml/anomaly_detectors Get anomaly detectors data * @apiName GetAnomalyDetectors * @apiDescription Returns the list of anomaly detection jobs. * * @apiSuccess {Number} count * @apiSuccess {Object[]} jobs */ - router.get( - { - path: '/api/ml/anomaly_detectors', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.getJobs(); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.getJobs(); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/:jobId Get anomaly detection data by id + * @api {get} /internal/ml/anomaly_detectors/:jobId Get anomaly detection data by id * @apiName GetAnomalyDetectorsById * @apiDescription Returns the anomaly detection job. * * @apiSchema (params) jobIdSchema */ - router.get( - { - path: '/api/ml/anomaly_detectors/{jobId}', - validate: { - params: jobIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobId } = request.params; - const body = await mlClient.getJobs({ job_id: jobId }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobId } = request.params; + const body = await mlClient.getJobs({ job_id: jobId }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/_stats Get anomaly detection stats + * @api {get} /internal/ml/anomaly_detectors/_stats Get anomaly detection stats * @apiName GetAnomalyDetectorsStats * @apiDescription Returns anomaly detection jobs statistics. * * @apiSuccess {Number} count * @apiSuccess {Object[]} jobs */ - router.get( - { - path: '/api/ml/anomaly_detectors/_stats', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.getJobStats(); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.getJobStats(); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/:jobId/_stats Get stats for requested anomaly detection job + * @api {get} /internal/ml/anomaly_detectors/:jobId/_stats Get stats for requested anomaly detection job * @apiName GetAnomalyDetectorsStatsById * @apiDescription Returns anomaly detection job statistics. * * @apiSchema (params) jobIdSchema */ - router.get( - { - path: '/api/ml/anomaly_detectors/{jobId}/_stats', - validate: { - params: jobIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobId } = request.params; - const body = await mlClient.getJobStats({ job_id: jobId }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobId } = request.params; + const body = await mlClient.getJobStats({ job_id: jobId }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {put} /api/ml/anomaly_detectors/:jobId Create an anomaly detection job + * @api {put} /internal/ml/anomaly_detectors/:jobId Create an anomaly detection job * @apiName CreateAnomalyDetectors * @apiDescription Creates an anomaly detection job. * @@ -167,302 +192,358 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { * * @apiSuccess {Object} job the configuration of the job that has been created. */ - router.put( - { - path: '/api/ml/anomaly_detectors/{jobId}', - validate: { - params: jobIdSchema, - body: schema.object(anomalyDetectionJobSchema), - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobId } = request.params; - const body = await mlClient.putJob( - { - job_id: jobId, - // @ts-expect-error job type custom_rules is incorrect - body: request.body, + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + body: schema.object(anomalyDetectionJobSchema), }, - getAuthorizationHeader(request) - ); + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobId } = request.params; + const body = await mlClient.putJob( + { + job_id: jobId, + // @ts-expect-error job type custom_rules is incorrect + body: request.body, + }, + getAuthorizationHeader(request) + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/_update Update an anomaly detection job + * @api {post} /internal/ml/anomaly_detectors/:jobId/_update Update an anomaly detection job * @apiName UpdateAnomalyDetectors * @apiDescription Updates certain properties of an anomaly detection job. * * @apiSchema (params) jobIdSchema * @apiSchema (body) anomalyDetectionUpdateJobSchema */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/_update', - validate: { - params: jobIdSchema, - body: anomalyDetectionUpdateJobSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_update`, + access: 'internal', options: { tags: ['access:ml:canUpdateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobId } = request.params; - const body = await mlClient.updateJob({ - job_id: jobId, - // @ts-expect-error MlDetector is not compatible - body: request.body, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + body: anomalyDetectionUpdateJobSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobId } = request.params; + const body = await mlClient.updateJob({ + job_id: jobId, + // @ts-expect-error MlDetector is not compatible + body: request.body, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/_open Open specified job + * @api {post} /internal/ml/anomaly_detectors/:jobId/_open Open specified job * @apiName OpenAnomalyDetectorsJob * @apiDescription Opens an anomaly detection job. * * @apiSchema (params) jobIdSchema */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/_open', - validate: { - params: jobIdSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_open`, + access: 'internal', options: { tags: ['access:ml:canOpenJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobId } = request.params; - const body = await mlClient.openJob({ job_id: jobId }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobId } = request.params; + const body = await mlClient.openJob({ job_id: jobId }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/_close Close specified job + * @api {post} /internal/ml/anomaly_detectors/:jobId/_close Close specified job * @apiName CloseAnomalyDetectorsJob * @apiDescription Closes an anomaly detection job. * * @apiSchema (params) jobIdSchema * @apiSchema (query) forceQuerySchema */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/_close', - validate: { - params: jobIdSchema, - query: forceQuerySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_close`, + access: 'internal', options: { tags: ['access:ml:canCloseJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const options: estypes.MlCloseJobRequest = { - job_id: request.params.jobId, - }; - const force = request.query.force; - if (force !== undefined) { - options.force = force; - } - const body = await mlClient.closeJob(options); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + query: forceQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const options: estypes.MlCloseJobRequest = { + job_id: request.params.jobId, + }; + const force = request.query.force; + if (force !== undefined) { + options.force = force; + } + const body = await mlClient.closeJob(options); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/_reset Reset specified job + * @api {post} /internal/ml/anomaly_detectors/:jobId/_reset Reset specified job * @apiName ResetAnomalyDetectorsJob * @apiDescription Resets an anomaly detection job. * * @apiSchema (params) jobIdSchema * @apiSchema (query) jobResetQuerySchema */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/_reset', - validate: { - params: jobIdSchema, - query: jobResetQuerySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_reset`, + access: 'internal', options: { tags: ['access:ml:canCloseJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const options: { job_id: string; wait_for_completion?: boolean } = { - // TODO change this to correct resetJob request type - job_id: request.params.jobId, - ...(request.query.wait_for_completion !== undefined - ? { wait_for_completion: request.query.wait_for_completion } - : {}), - }; - const body = await mlClient.resetJob(options); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + query: jobResetQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const options: { job_id: string; wait_for_completion?: boolean } = { + // TODO change this to correct resetJob request type + job_id: request.params.jobId, + ...(request.query.wait_for_completion !== undefined + ? { wait_for_completion: request.query.wait_for_completion } + : {}), + }; + const body = await mlClient.resetJob(options); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {delete} /api/ml/anomaly_detectors/:jobId Delete specified job + * @api {delete} /internal/ml/anomaly_detectors/:jobId Delete specified job * @apiName DeleteAnomalyDetectorsJob * @apiDescription Deletes specified anomaly detection job. * * @apiSchema (params) jobIdSchema * @apiSchema (query) forceQuerySchema */ - router.delete( - { - path: '/api/ml/anomaly_detectors/{jobId}', - validate: { - params: jobIdSchema, - query: forceQuerySchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const options: estypes.MlDeleteJobRequest = { - job_id: request.params.jobId, - wait_for_completion: false, - }; - const force = request.query.force; - if (force !== undefined) { - options.force = force; - } - const body = await mlClient.deleteJob(options); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + query: forceQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const options: estypes.MlDeleteJobRequest = { + job_id: request.params.jobId, + wait_for_completion: false, + }; + const force = request.query.force; + if (force !== undefined) { + options.force = force; + } + const body = await mlClient.deleteJob(options); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/_validate/detector Validate detector + * @api {post} /internal/ml/anomaly_detectors/_validate/detector Validate detector * @apiName ValidateAnomalyDetector * @apiDescription Validates specified detector. */ - router.post( - { - path: '/api/ml/anomaly_detectors/_validate/detector', - validate: { - body: schema.any(), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/_validate/detector`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.validateDetector({ body: request.body }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.any(), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.validateDetector({ body: request.body }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/_forecast Create forecast for specified job + * @api {post} /internal/ml/anomaly_detectors/:jobId/_forecast Create forecast for specified job * @apiName ForecastAnomalyDetector * @apiDescription Creates a forecast for the specified anomaly detection job, predicting the future behavior of a time series by using its historical behavior. * * @apiSchema (params) jobIdSchema * @apiSchema (body) forecastAnomalyDetector */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/_forecast', - validate: { - params: jobIdSchema, - body: forecastAnomalyDetector, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/_forecast`, + access: 'internal', options: { tags: ['access:ml:canForecastJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const jobId = request.params.jobId; - const duration = request.body.duration; - const body = await mlClient.forecast({ - job_id: jobId, - body: { - duration, - }, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + body: forecastAnomalyDetector, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const jobId = request.params.jobId; + const duration = request.body.duration; + const body = await mlClient.forecast({ + job_id: jobId, + body: { + duration, + }, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/results/records Retrieves anomaly records for a job. + * @api {post} /internal/ml/anomaly_detectors/:jobId/results/records Retrieves anomaly records for a job. * @apiName GetRecords * @apiDescription Retrieves anomaly records for a job. * @@ -472,36 +553,43 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Number} count * @apiSuccess {Object[]} records */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/results/records', - validate: { - params: jobIdSchema, - body: getRecordsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/results/records`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getRecords({ - job_id: request.params.jobId, - body: request.body, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + body: getRecordsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getRecords({ + job_id: request.params.jobId, + body: request.body, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/results/buckets Obtain bucket scores for the specified job ID + * @api {post} /internal/ml/anomaly_detectors/:jobId/results/buckets Obtain bucket scores for the specified job ID * @apiName GetBuckets * @apiDescription The get buckets API presents a chronological view of the records, grouped by bucket. * @@ -511,37 +599,44 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Number} count * @apiSuccess {Object[]} buckets */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/results/buckets/{timestamp?}', - validate: { - params: getBucketParamsSchema, - body: getBucketsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/results/buckets/{timestamp?}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getBuckets({ - job_id: request.params.jobId, - timestamp: request.params.timestamp, - body: request.body, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: getBucketParamsSchema, + body: getBucketsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getBuckets({ + job_id: request.params.jobId, + timestamp: request.params.timestamp, + body: request.body, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/results/overall_buckets Obtain overall bucket scores for the specified job ID + * @api {post} /internal/ml/anomaly_detectors/:jobId/results/overall_buckets Obtain overall bucket scores for the specified job ID * @apiName GetOverallBuckets * @apiDescription Retrieves overall bucket results that summarize the bucket results of multiple anomaly detection jobs. * @@ -551,205 +646,247 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Number} count * @apiSuccess {Object[]} overall_buckets */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/results/overall_buckets', - validate: { - params: jobIdSchema, - body: getOverallBucketsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/results/overall_buckets`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getOverallBuckets({ - job_id: request.params.jobId, - top_n: request.body.topN, - bucket_span: request.body.bucketSpan, - start: request.body.start !== undefined ? String(request.body.start) : undefined, - end: request.body.end !== undefined ? String(request.body.end) : undefined, - overall_score: request.body.overall_score ?? 0, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + body: getOverallBucketsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getOverallBuckets({ + job_id: request.params.jobId, + top_n: request.body.topN, + bucket_span: request.body.bucketSpan, + start: request.body.start !== undefined ? String(request.body.start) : undefined, + end: request.body.end !== undefined ? String(request.body.end) : undefined, + overall_score: request.body.overall_score ?? 0, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/:jobId/results/categories/:categoryId Get results category data by job ID and category ID + * @api {get} /internal/ml/anomaly_detectors/:jobId/results/categories/:categoryId Get results category data by job ID and category ID * @apiName GetCategories * @apiDescription Returns the categories results for the specified job ID and category ID. * * @apiSchema (params) getCategoriesSchema */ - router.get( - { - path: '/api/ml/anomaly_detectors/{jobId}/results/categories/{categoryId}', - validate: { - params: getCategoriesSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/results/categories/{categoryId}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getCategories({ - job_id: request.params.jobId, - category_id: request.params.categoryId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: getCategoriesSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getCategories({ + job_id: request.params.jobId, + category_id: request.params.categoryId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/:jobId/model_snapshots Get model snapshots by job ID + * @api {get} /internal/ml/anomaly_detectors/:jobId/model_snapshots Get model snapshots by job ID * @apiName GetModelSnapshots * @apiDescription Returns the model snapshots for the specified job ID * * @apiSchema (params) getModelSnapshotsSchema */ - router.get( - { - path: '/api/ml/anomaly_detectors/{jobId}/model_snapshots', - validate: { - params: getModelSnapshotsSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/model_snapshots`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getModelSnapshots({ - job_id: request.params.jobId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: getModelSnapshotsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getModelSnapshots({ + job_id: request.params.jobId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {get} /api/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId Get model snapshots by job ID and snapshot ID + * @api {get} /internal/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId Get model snapshots by job ID and snapshot ID * @apiName GetModelSnapshotsById * @apiDescription Returns the model snapshots for the specified job ID and snapshot ID * * @apiSchema (params) getModelSnapshotsSchema */ - router.get( - { - path: '/api/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}', - validate: { - params: getModelSnapshotsSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getModelSnapshots({ - job_id: request.params.jobId, - snapshot_id: request.params.snapshotId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: getModelSnapshotsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getModelSnapshots({ + job_id: request.params.jobId, + snapshot_id: request.params.snapshotId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {post} /api/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId/_update Update model snapshot by snapshot ID + * @api {post} /internal/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId/_update Update model snapshot by snapshot ID * @apiName UpdateModelSnapshotsById * @apiDescription Updates the model snapshot for the specified snapshot ID * * @apiSchema (params) updateModelSnapshotsSchema * @apiSchema (body) updateModelSnapshotBodySchema */ - router.post( - { - path: '/api/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}/_update', - validate: { - params: updateModelSnapshotsSchema, - body: updateModelSnapshotBodySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}/_update`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.updateModelSnapshot({ - job_id: request.params.jobId, - snapshot_id: request.params.snapshotId, - body: request.body, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: updateModelSnapshotsSchema, + body: updateModelSnapshotBodySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.updateModelSnapshot({ + job_id: request.params.jobId, + snapshot_id: request.params.snapshotId, + body: request.body, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup AnomalyDetectors * - * @api {delete} /api/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId Delete model snapshots by snapshot ID + * @api {delete} /internal/ml/anomaly_detectors/:jobId/model_snapshots/:snapshotId Delete model snapshots by snapshot ID * @apiName GetModelSnapshotsById * @apiDescription Deletes the model snapshot for the specified snapshot ID * * @apiSchema (params) updateModelSnapshotsSchema */ - router.delete( - { - path: '/api/ml/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}', - validate: { - params: updateModelSnapshotsSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/{jobId}/model_snapshots/{snapshotId}`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.deleteModelSnapshot({ - job_id: request.params.jobId, - snapshot_id: request.params.snapshotId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: updateModelSnapshotsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.deleteModelSnapshot({ + job_id: request.params.jobId, + snapshot_id: request.params.snapshotId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/calendars.ts b/x-pack/plugins/ml/server/routes/calendars.ts index 256ea249096d5b..0ce02fd54f949f 100644 --- a/x-pack/plugins/ml/server/routes/calendars.ts +++ b/x-pack/plugins/ml/server/routes/calendars.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { calendarSchema, calendarIdSchema, calendarIdsSchema } from './schemas/calendars_schema'; @@ -45,171 +46,204 @@ export function calendars({ router, routeGuard }: RouteInitialization) { /** * @apiGroup Calendars * - * @api {get} /api/ml/calendars Gets calendars + * @api {get} /internal/ml/calendars Gets calendars * @apiName GetCalendars * @apiDescription Gets calendars - size limit has been explicitly set to 1000 */ - router.get( - { - path: '/api/ml/calendars', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/calendars`, + access: 'internal', options: { tags: ['access:ml:canGetCalendars'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const resp = await getAllCalendars(mlClient); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const resp = await getAllCalendars(mlClient); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Calendars * - * @api {get} /api/ml/calendars/:calendarIds Gets a calendar + * @api {get} /internal/ml/calendars/:calendarIds Gets a calendar * @apiName GetCalendarById * @apiDescription Gets calendar by id * * @apiSchema (params) calendarIdsSchema */ - router.get( - { - path: '/api/ml/calendars/{calendarIds}', - validate: { - params: calendarIdsSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/calendars/{calendarIds}`, + access: 'internal', options: { tags: ['access:ml:canGetCalendars'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - let returnValue; - try { - const calendarIds = request.params.calendarIds.split(','); - - if (calendarIds.length === 1) { - returnValue = await getCalendar(mlClient, calendarIds[0]); - } else { - returnValue = await getCalendarsByIds(mlClient, calendarIds); - } - - return response.ok({ - body: returnValue, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: calendarIdsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + let returnValue; + try { + const calendarIds = request.params.calendarIds.split(','); + + if (calendarIds.length === 1) { + returnValue = await getCalendar(mlClient, calendarIds[0]); + } else { + returnValue = await getCalendarsByIds(mlClient, calendarIds); + } + + return response.ok({ + body: returnValue, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Calendars * - * @api {put} /api/ml/calendars Creates a calendar + * @api {put} /internal/ml/calendars Creates a calendar * @apiName PutCalendars * @apiDescription Creates a calendar * * @apiSchema (body) calendarSchema */ - router.put( - { - path: '/api/ml/calendars', - validate: { - body: calendarSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/calendars`, + access: 'internal', options: { tags: ['access:ml:canCreateCalendar'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = request.body; - // @ts-expect-error event interface incorrect - const resp = await newCalendar(mlClient, body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: calendarSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = request.body; + // @ts-expect-error event interface incorrect + const resp = await newCalendar(mlClient, body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Calendars * - * @api {put} /api/ml/calendars/:calendarId Updates a calendar + * @api {put} /internal/ml/calendars/:calendarId Updates a calendar * @apiName UpdateCalendarById * @apiDescription Updates a calendar * * @apiSchema (params) calendarIdSchema * @apiSchema (body) calendarSchema */ - router.put( - { - path: '/api/ml/calendars/{calendarId}', - validate: { - params: calendarIdSchema, - body: calendarSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/calendars/{calendarId}`, + access: 'internal', options: { tags: ['access:ml:canCreateCalendar'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { calendarId } = request.params; - const body = request.body; - // @ts-expect-error event interface incorrect - const resp = await updateCalendar(mlClient, calendarId, body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: calendarIdSchema, + body: calendarSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { calendarId } = request.params; + const body = request.body; + // @ts-expect-error event interface incorrect + const resp = await updateCalendar(mlClient, calendarId, body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Calendars * - * @api {delete} /api/ml/calendars/:calendarId Deletes a calendar + * @api {delete} /internal/ml/calendars/:calendarId Deletes a calendar * @apiName DeleteCalendarById * @apiDescription Deletes a calendar * * @apiSchema (params) calendarIdSchema */ - router.delete( - { - path: '/api/ml/calendars/{calendarId}', - validate: { - params: calendarIdSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/calendars/{calendarId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteCalendar'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { calendarId } = request.params; - const resp = await deleteCalendar(mlClient, calendarId); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: calendarIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { calendarId } = request.params; + const resp = await deleteCalendar(mlClient, calendarId); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts index 1fd79cbe963e6d..3132d3fc085ada 100644 --- a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts @@ -7,6 +7,7 @@ import type { IScopedClusterClient } from '@kbn/core/server'; import type { DataViewsService } from '@kbn/data-views-plugin/common'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { analyticsAuditMessagesProvider } from '../models/data_frame_analytics/analytics_audit_messages'; import type { RouteInitialization } from '../types'; @@ -113,141 +114,167 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics Get analytics data + * @api {get} /internal/ml/data_frame/analytics Get analytics data * @apiName GetDataFrameAnalytics * @apiDescription Returns the list of data frame analytics jobs. * * @apiSuccess {Number} count * @apiSuccess {Object[]} data_frame_analytics */ - router.get( - { - path: '/api/ml/data_frame/analytics', - validate: { - query: analyticsQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { size } = request.query; - const body = await mlClient.getDataFrameAnalytics({ - size: size ?? 1000, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + query: analyticsQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { size } = request.query; + const body = await mlClient.getDataFrameAnalytics({ + size: size ?? 1000, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/:analyticsId Get analytics data by id + * @api {get} /internal/ml/data_frame/analytics/:analyticsId Get analytics data by id * @apiName GetDataFrameAnalyticsById * @apiDescription Returns the data frame analytics job. * * @apiSchema (params) analyticsIdSchema */ - router.get( - { - path: '/api/ml/data_frame/analytics/{analyticsId}', - validate: { - params: analyticsIdSchema, - query: analyticsQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { analyticsId } = request.params; - const { excludeGenerated } = request.query; - - const body = await mlClient.getDataFrameAnalytics({ - id: analyticsId, - ...(excludeGenerated ? { exclude_generated: true } : {}), - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + query: analyticsQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { analyticsId } = request.params; + const { excludeGenerated } = request.query; + + const body = await mlClient.getDataFrameAnalytics({ + id: analyticsId, + ...(excludeGenerated ? { exclude_generated: true } : {}), + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/_stats Get analytics stats + * @api {get} /internal/ml/data_frame/analytics/_stats Get analytics stats * @apiName GetDataFrameAnalyticsStats * @apiDescription Returns data frame analytics jobs statistics. */ - router.get( - { - path: '/api/ml/data_frame/analytics/_stats', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.getDataFrameAnalyticsStats({ size: 1000 }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.getDataFrameAnalyticsStats({ size: 1000 }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/:analyticsId/_stats Get stats for requested analytics job + * @api {get} /internal/ml/data_frame/analytics/:analyticsId/_stats Get stats for requested analytics job * @apiName GetDataFrameAnalyticsStatsById * @apiDescription Returns data frame analytics job statistics. * * @apiSchema (params) analyticsIdSchema */ - router.get( - { - path: '/api/ml/data_frame/analytics/{analyticsId}/_stats', - validate: { - params: analyticsIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { analyticsId } = request.params; - const body = await mlClient.getDataFrameAnalyticsStats({ - id: analyticsId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { analyticsId } = request.params; + const body = await mlClient.getDataFrameAnalyticsStats({ + id: analyticsId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {put} /api/ml/data_frame/analytics/:analyticsId Instantiate a data frame analytics job + * @api {put} /internal/ml/data_frame/analytics/:analyticsId Instantiate a data frame analytics job * @apiName UpdateDataFrameAnalytics * @apiDescription This API creates a data frame analytics job that performs an analysis * on the source index and stores the outcome in a destination index. @@ -255,529 +282,621 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout * @apiSchema (params) analyticsIdSchema * @apiSchema (body) dataAnalyticsJobConfigSchema */ - router.put( - { - path: '/api/ml/data_frame/analytics/{analyticsId}', - validate: { - params: analyticsIdSchema, - body: dataAnalyticsJobConfigSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}`, + access: 'internal', options: { tags: ['access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { analyticsId } = request.params; - const body = await mlClient.putDataFrameAnalytics( - { - id: analyticsId, - // @ts-expect-error @elastic-elasticsearch Data frame types incomplete - body: request.body, - }, - getAuthorizationHeader(request) - ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + body: dataAnalyticsJobConfigSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { analyticsId } = request.params; + const body = await mlClient.putDataFrameAnalytics( + { + id: analyticsId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + body: request.body, + }, + getAuthorizationHeader(request) + ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/_evaluate Evaluate the data frame analytics for an annotated index + * @api {post} /internal/ml/data_frame/_evaluate Evaluate the data frame analytics for an annotated index * @apiName EvaluateDataFrameAnalytics * @apiDescription Evaluates the data frame analytics for an annotated index. * * @apiSchema (body) dataAnalyticsEvaluateSchema */ - router.post( - { - path: '/api/ml/data_frame/_evaluate', - validate: { - body: dataAnalyticsEvaluateSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/_evaluate`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.evaluateDataFrame( - { - // @ts-expect-error @elastic-elasticsearch Data frame types incomplete - body: request.body, - }, - getAuthorizationHeader(request) - ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: dataAnalyticsEvaluateSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.evaluateDataFrame( + { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + body: request.body, + }, + getAuthorizationHeader(request) + ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/_explain Explain a data frame analytics config + * @api {post} /internal/ml/data_frame/_explain Explain a data frame analytics config * @apiName ExplainDataFrameAnalytics * @apiDescription This API provides explanations for a data frame analytics config * that either exists already or one that has not been created yet. * * @apiSchema (body) dataAnalyticsExplainSchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/_explain', - validate: { - body: dataAnalyticsExplainSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/_explain`, + access: 'internal', options: { tags: ['access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.explainDataFrameAnalytics( - { - body: request.body, - }, - getAuthorizationHeader(request) - ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: dataAnalyticsExplainSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.explainDataFrameAnalytics( + { + body: request.body, + }, + getAuthorizationHeader(request) + ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {delete} /api/ml/data_frame/analytics/:analyticsId Delete specified analytics job + * @api {delete} /internal/ml/data_frame/analytics/:analyticsId Delete specified analytics job * @apiName DeleteDataFrameAnalytics * @apiDescription Deletes specified data frame analytics job. * * @apiSchema (params) analyticsIdSchema */ - router.delete( - { - path: '/api/ml/data_frame/analytics/{analyticsId}', - validate: { - params: analyticsIdSchema, - query: deleteDataFrameAnalyticsJobSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ mlClient, client, request, response, getDataViewsService }) => { - try { - const { analyticsId } = request.params; - const { deleteDestIndex, deleteDestIndexPattern } = request.query; - let destinationIndex: string | undefined; - const analyticsJobDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { success: false }; - const destIndexDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { success: false }; - const destIndexPatternDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { - success: false, - }; - + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + query: deleteDataFrameAnalyticsJobSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ mlClient, client, request, response, getDataViewsService }) => { try { - // Check if analyticsId is valid and get destination index - const body = await mlClient.getDataFrameAnalytics({ - id: analyticsId, - }); - if (Array.isArray(body.data_frame_analytics) && body.data_frame_analytics.length > 0) { - destinationIndex = body.data_frame_analytics[0].dest.index; + const { analyticsId } = request.params; + const { deleteDestIndex, deleteDestIndexPattern } = request.query; + let destinationIndex: string | undefined; + const analyticsJobDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { success: false }; + const destIndexDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { success: false }; + const destIndexPatternDeleted: DeleteDataFrameAnalyticsWithIndexStatus = { + success: false, + }; + + try { + // Check if analyticsId is valid and get destination index + const body = await mlClient.getDataFrameAnalytics({ + id: analyticsId, + }); + if ( + Array.isArray(body.data_frame_analytics) && + body.data_frame_analytics.length > 0 + ) { + destinationIndex = body.data_frame_analytics[0].dest.index; + } + } catch (e) { + // exist early if the job doesn't exist + return response.customError(wrapError(e)); } - } catch (e) { - // exist early if the job doesn't exist - return response.customError(wrapError(e)); - } - if (deleteDestIndex || deleteDestIndexPattern) { - // If user checks box to delete the destinationIndex associated with the job - if (destinationIndex && deleteDestIndex) { - // Verify if user has privilege to delete the destination index - const userCanDeleteDestIndex = await userCanDeleteIndex(client, destinationIndex); - // If user does have privilege to delete the index, then delete the index - if (userCanDeleteDestIndex) { - try { - await client.asCurrentUser.indices.delete({ - index: destinationIndex, - }); - destIndexDeleted.success = true; - } catch ({ body }) { - destIndexDeleted.error = body; + if (deleteDestIndex || deleteDestIndexPattern) { + // If user checks box to delete the destinationIndex associated with the job + if (destinationIndex && deleteDestIndex) { + // Verify if user has privilege to delete the destination index + const userCanDeleteDestIndex = await userCanDeleteIndex(client, destinationIndex); + // If user does have privilege to delete the index, then delete the index + if (userCanDeleteDestIndex) { + try { + await client.asCurrentUser.indices.delete({ + index: destinationIndex, + }); + destIndexDeleted.success = true; + } catch ({ body }) { + destIndexDeleted.error = body; + } + } else { + return response.forbidden(); } - } else { - return response.forbidden(); } - } - // Delete the index pattern if there's an index pattern that matches the name of dest index - if (destinationIndex && deleteDestIndexPattern) { - try { - const dataViewsService = await getDataViewsService(); - const dataViewId = await getDataViewId(dataViewsService, destinationIndex); - if (dataViewId) { - await deleteDestDataViewById(dataViewsService, dataViewId); + // Delete the index pattern if there's an index pattern that matches the name of dest index + if (destinationIndex && deleteDestIndexPattern) { + try { + const dataViewsService = await getDataViewsService(); + const dataViewId = await getDataViewId(dataViewsService, destinationIndex); + if (dataViewId) { + await deleteDestDataViewById(dataViewsService, dataViewId); + } + destIndexPatternDeleted.success = true; + } catch (deleteDestIndexPatternError) { + destIndexPatternDeleted.error = deleteDestIndexPatternError; } - destIndexPatternDeleted.success = true; - } catch (deleteDestIndexPatternError) { - destIndexPatternDeleted.error = deleteDestIndexPatternError; } } - } - // Grab the target index from the data frame analytics job id - // Delete the data frame analytics - - try { - await mlClient.deleteDataFrameAnalytics({ - id: analyticsId, + // Grab the target index from the data frame analytics job id + // Delete the data frame analytics + + try { + await mlClient.deleteDataFrameAnalytics({ + id: analyticsId, + }); + analyticsJobDeleted.success = true; + } catch ({ body }) { + analyticsJobDeleted.error = body; + } + const results = { + analyticsJobDeleted, + destIndexDeleted, + destIndexPatternDeleted, + }; + return response.ok({ + body: results, }); - analyticsJobDeleted.success = true; - } catch ({ body }) { - analyticsJobDeleted.error = body; + } catch (e) { + return response.customError(wrapError(e)); } - const results = { - analyticsJobDeleted, - destIndexDeleted, - destIndexPatternDeleted, - }; - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); } - } - ) - ); + ) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/analytics/:analyticsId/_start Start specified analytics job + * @api {post} /internal/ml/data_frame/analytics/:analyticsId/_start Start specified analytics job * @apiName StartDataFrameAnalyticsJob * @apiDescription Starts a data frame analytics job. * * @apiSchema (params) analyticsIdSchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/{analyticsId}/_start', - validate: { - params: analyticsIdSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}/_start`, + access: 'internal', options: { tags: ['access:ml:canStartStopDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { analyticsId } = request.params; - const body = await mlClient.startDataFrameAnalytics({ - id: analyticsId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { analyticsId } = request.params; + const body = await mlClient.startDataFrameAnalytics({ + id: analyticsId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/analytics/:analyticsId/_stop Stop specified analytics job + * @api {post} /internal/ml/data_frame/analytics/:analyticsId/_stop Stop specified analytics job * @apiName StopsDataFrameAnalyticsJob * @apiDescription Stops a data frame analytics job. * * @apiSchema (params) analyticsIdSchema * @apiSchema (query) stopsDataFrameAnalyticsJobQuerySchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/{analyticsId}/_stop', - validate: { - params: analyticsIdSchema, - query: stopsDataFrameAnalyticsJobQuerySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}/_stop`, + access: 'internal', options: { tags: ['access:ml:canStartStopDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.stopDataFrameAnalytics({ - id: request.params.analyticsId, - force: request.query.force, - }); - - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + query: stopsDataFrameAnalyticsJobQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.stopDataFrameAnalytics({ + id: request.params.analyticsId, + force: request.query.force, + }); + + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/analytics/:analyticsId/_update Update specified analytics job + * @api {post} /internal/ml/data_frame/analytics/:analyticsId/_update Update specified analytics job * @apiName UpdateDataFrameAnalyticsJob * @apiDescription Updates a data frame analytics job. * * @apiSchema (params) analyticsIdSchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/{analyticsId}/_update', - validate: { - params: analyticsIdSchema, - body: dataAnalyticsJobUpdateSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}/_update`, + access: 'internal', options: { tags: ['access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { analyticsId } = request.params; - const body = await mlClient.updateDataFrameAnalytics( - { - id: analyticsId, - body: request.body, - }, - getAuthorizationHeader(request) - ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + body: dataAnalyticsJobUpdateSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { analyticsId } = request.params; + const body = await mlClient.updateDataFrameAnalytics( + { + id: analyticsId, + body: request.body, + }, + getAuthorizationHeader(request) + ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/:analyticsId/messages Get analytics job messages + * @api {get} /internal/ml/data_frame/analytics/:analyticsId/messages Get analytics job messages * @apiName GetDataFrameAnalyticsMessages * @apiDescription Returns the list of audit messages for data frame analytics jobs. * * @apiSchema (params) analyticsIdSchema */ - router.get( - { - path: '/api/ml/data_frame/analytics/{analyticsId}/messages', - validate: { - params: analyticsIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/{analyticsId}/messages`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { analyticsId } = request.params; - const { getAnalyticsAuditMessages } = analyticsAuditMessagesProvider(client); - - const results = await getAnalyticsAuditMessages(analyticsId); - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { analyticsId } = request.params; + const { getAnalyticsAuditMessages } = analyticsAuditMessagesProvider(client); + + const results = await getAnalyticsAuditMessages(analyticsId); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/analytics/jobs_exist Check whether jobs exist in current or any space + * @api {post} /internal/ml/data_frame/analytics/jobs_exist Check whether jobs exist in current or any space * @apiName JobsExist * @apiDescription Checks if each of the jobs in the specified list of IDs exists. * If allSpaces is true, the check will look across all spaces. * * @apiSchema (params) jobsExistSchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/jobs_exist', - validate: { - body: jobsExistSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/jobs_exist`, + access: 'internal', options: { tags: ['access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { analyticsIds, allSpaces } = request.body; - const results: { [id: string]: { exists: boolean } } = {}; - for (const id of analyticsIds) { - try { - const body = allSpaces - ? await client.asInternalUser.ml.getDataFrameAnalytics({ - id, - }) - : await mlClient.getDataFrameAnalytics({ - id, - }); - results[id] = { exists: body.data_frame_analytics.length > 0 }; - } catch (error) { - if (error.statusCode !== 404) { - throw error; + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: jobsExistSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { analyticsIds, allSpaces } = request.body; + const results: { [id: string]: { exists: boolean } } = {}; + for (const id of analyticsIds) { + try { + const body = allSpaces + ? await client.asInternalUser.ml.getDataFrameAnalytics({ + id, + }) + : await mlClient.getDataFrameAnalytics({ + id, + }); + results[id] = { exists: body.data_frame_analytics.length > 0 }; + } catch (error) { + if (error.statusCode !== 404) { + throw error; + } + results[id] = { exists: false }; } - results[id] = { exists: false }; } - } - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/map/:analyticsId Get objects leading up to analytics job + * @api {get} /internal/ml/data_frame/analytics/map/:analyticsId Get objects leading up to analytics job * @apiName GetDataFrameAnalyticsIdMap * @apiDescription Returns map of objects leading up to analytics job. * * @apiParam {String} analyticsId Analytics ID. */ - router.get( - { - path: '/api/ml/data_frame/analytics/map/{analyticsId}', - validate: { - params: analyticsIdSchema, - query: analyticsMapQuerySchema, - }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, client, request, response }) => { - try { - const { analyticsId } = request.params; - const treatAsRoot = request.query?.treatAsRoot; - const type = request.query?.type; - - let results; - if (treatAsRoot === 'true' || treatAsRoot === true) { - // @ts-expect-error never used as analyticsId - results = await getExtendedMap(mlClient, client, { - analyticsId: type !== JOB_MAP_NODE_TYPES.INDEX ? analyticsId : undefined, - index: type === JOB_MAP_NODE_TYPES.INDEX ? analyticsId : undefined, - }); - } else { - // @ts-expect-error never used as analyticsId - results = await getAnalyticsMap(mlClient, client, { - analyticsId: type !== JOB_MAP_NODE_TYPES.TRAINED_MODEL ? analyticsId : undefined, - modelId: type === JOB_MAP_NODE_TYPES.TRAINED_MODEL ? analyticsId : undefined, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/map/{analyticsId}`, + access: 'internal', + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsIdSchema, + query: analyticsMapQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, client, request, response }) => { + try { + const { analyticsId } = request.params; + const treatAsRoot = request.query?.treatAsRoot; + const type = request.query?.type; + + let results; + if (treatAsRoot === 'true' || treatAsRoot === true) { + // @ts-expect-error never used as analyticsId + results = await getExtendedMap(mlClient, client, { + analyticsId: type !== JOB_MAP_NODE_TYPES.INDEX ? analyticsId : undefined, + index: type === JOB_MAP_NODE_TYPES.INDEX ? analyticsId : undefined, + }); + } else { + // @ts-expect-error never used as analyticsId + results = await getAnalyticsMap(mlClient, client, { + analyticsId: type !== JOB_MAP_NODE_TYPES.TRAINED_MODEL ? analyticsId : undefined, + modelId: type === JOB_MAP_NODE_TYPES.TRAINED_MODEL ? analyticsId : undefined, + }); + } + + return response.ok({ + body: results, }); + } catch (e) { + return response.customError(wrapError(e)); } - - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {get} /api/ml/data_frame/analytics/new_job_caps/:indexPattern Get fields for a pattern of indices used for analytics + * @api {get} /internal/ml/data_frame/analytics/new_job_caps/:indexPattern Get fields for a pattern of indices used for analytics * @apiName AnalyticsNewJobCaps * @apiDescription Retrieve the index fields for analytics */ - router.get( - { - path: '/api/ml/data_frame/analytics/new_job_caps/{indexPattern}', - validate: { - params: analyticsNewJobCapsParamsSchema, - query: analyticsNewJobCapsQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/new_job_caps/{indexPattern}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response, getDataViewsService }) => { - try { - const { indexPattern } = request.params; - const isRollup = request.query?.rollup === 'true'; - const dataViewsService = await getDataViewsService(); - const fieldService = fieldServiceProvider(indexPattern, isRollup, client, dataViewsService); - const { fields, aggs } = await fieldService.getData(true); - convertForStringify(aggs, fields); - - return response.ok({ - body: { - [indexPattern]: { - aggs, - fields, - }, - }, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: analyticsNewJobCapsParamsSchema, + query: analyticsNewJobCapsQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response, getDataViewsService }) => { + try { + const { indexPattern } = request.params; + const isRollup = request.query?.rollup === 'true'; + const dataViewsService = await getDataViewsService(); + const fieldService = fieldServiceProvider( + indexPattern, + isRollup, + client, + dataViewsService + ); + const { fields, aggs } = await fieldService.getData(true); + convertForStringify(aggs, fields); + + return response.ok({ + body: { + [indexPattern]: { + aggs, + fields, + }, + }, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFrameAnalytics * - * @api {post} /api/ml/data_frame/validate Validate the data frame analytics job config + * @api {post} /internal/ml/data_frame/validate Validate the data frame analytics job config * @apiName ValidateDataFrameAnalytics * @apiDescription Validates the data frame analytics job config. * * @apiSchema (body) dataAnalyticsJobConfigSchema */ - router.post( - { - path: '/api/ml/data_frame/analytics/validate', - validate: { - body: dataAnalyticsJobConfigSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_frame/analytics/validate`, + access: 'internal', options: { tags: ['access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - const jobConfig = request.body; - try { - // @ts-expect-error DFA schemas are incorrect - const results = await validateAnalyticsJob(client, jobConfig); - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: dataAnalyticsJobConfigSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + const jobConfig = request.body; + try { + // @ts-expect-error DFA schemas are incorrect + const results = await validateAnalyticsJob(client, jobConfig); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/data_visualizer.ts b/x-pack/plugins/ml/server/routes/data_visualizer.ts index 4ecdc73f534c7b..0bb350e15d9372 100644 --- a/x-pack/plugins/ml/server/routes/data_visualizer.ts +++ b/x-pack/plugins/ml/server/routes/data_visualizer.ts @@ -7,6 +7,7 @@ import { IScopedClusterClient } from '@kbn/core/server'; import { FieldsForHistograms } from '@kbn/ml-agg-utils'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { DataVisualizer } from '../models/data_visualizer'; import { @@ -35,7 +36,7 @@ export function dataVisualizerRoutes({ router, routeGuard }: RouteInitialization /** * @apiGroup DataVisualizer * - * @api {post} /api/ml/data_visualizer/get_field_histograms/:indexPattern Get histograms for fields + * @api {post} /internal/ml/data_visualizer/get_field_histograms/:indexPattern Get histograms for fields * @apiName GetHistogramsForFields * @apiDescription Returns the histograms on a list fields in the specified index pattern. * @@ -44,39 +45,46 @@ export function dataVisualizerRoutes({ router, routeGuard }: RouteInitialization * * @apiSuccess {Object} fieldName histograms by field, keyed on the name of the field. */ - router.post( - { - path: '/api/ml/data_visualizer/get_field_histograms/{indexPattern}', - validate: { - params: indexPatternSchema, - body: dataVisualizerFieldHistogramsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/data_visualizer/get_field_histograms/{indexPattern}`, + access: 'internal', options: { tags: ['access:ml:canGetFieldInfo'], }, - }, - routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { - params: { indexPattern }, - body: { query, fields, samplerShardSize, runtimeMappings }, - } = request; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: indexPatternSchema, + body: dataVisualizerFieldHistogramsSchema, + }, + }, + }, + routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { + params: { indexPattern }, + body: { query, fields, samplerShardSize, runtimeMappings }, + } = request; - const results = await getHistogramsForFields( - client, - indexPattern, - query, - fields, - samplerShardSize, - runtimeMappings - ); + const results = await getHistogramsForFields( + client, + indexPattern, + query, + fields, + samplerShardSize, + runtimeMappings + ); - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/datafeeds.ts b/x-pack/plugins/ml/server/routes/datafeeds.ts index 2a45d8e8dc9b07..0720292b5b7cf6 100644 --- a/x-pack/plugins/ml/server/routes/datafeeds.ts +++ b/x-pack/plugins/ml/server/routes/datafeeds.ts @@ -6,6 +6,7 @@ */ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { @@ -23,365 +24,431 @@ export function dataFeedRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup DatafeedService * - * @api {get} /api/ml/datafeeds Get all datafeeds + * @api {get} /internal/ml/datafeeds Get all datafeeds * @apiName GetDatafeeds * @apiDescription Retrieves configuration information for datafeeds */ - router.get( - { - path: '/api/ml/datafeeds', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds`, + access: 'internal', options: { tags: ['access:ml:canGetDatafeeds'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.getDatafeeds(); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.getDatafeeds(); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {get} /api/ml/datafeeds/:datafeedId Get datafeed for given datafeed id + * @api {get} /internal/ml/datafeeds/:datafeedId Get datafeed for given datafeed id * @apiName GetDatafeed * @apiDescription Retrieves configuration information for datafeed * * @apiSchema (params) datafeedIdSchema */ - router.get( - { - path: '/api/ml/datafeeds/{datafeedId}', - validate: { - params: datafeedIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}`, + access: 'internal', options: { tags: ['access:ml:canGetDatafeeds'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const body = await mlClient.getDatafeeds({ datafeed_id: datafeedId }); - - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const body = await mlClient.getDatafeeds({ datafeed_id: datafeedId }); + + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {get} /api/ml/datafeeds/_stats Get stats for all datafeeds + * @api {get} /internal/ml/datafeeds/_stats Get stats for all datafeeds * @apiName GetDatafeedsStats * @apiDescription Retrieves usage information for datafeeds */ - router.get( - { - path: '/api/ml/datafeeds/_stats', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetDatafeeds'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.getDatafeedStats(); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.getDatafeedStats(); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {get} /api/ml/datafeeds/:datafeedId/_stats Get datafeed stats for given datafeed id + * @api {get} /internal/ml/datafeeds/:datafeedId/_stats Get datafeed stats for given datafeed id * @apiName GetDatafeedStats * @apiDescription Retrieves usage information for datafeed * * @apiSchema (params) datafeedIdSchema */ - router.get( - { - path: '/api/ml/datafeeds/{datafeedId}/_stats', - validate: { - params: datafeedIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetDatafeeds'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const body = await mlClient.getDatafeedStats({ - datafeed_id: datafeedId, - }); - - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const body = await mlClient.getDatafeedStats({ + datafeed_id: datafeedId, + }); + + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {put} /api/ml/datafeeds/:datafeedId Creates datafeed + * @api {put} /internal/ml/datafeeds/:datafeedId Creates datafeed * @apiName CreateDatafeed * @apiDescription Instantiates a datafeed * * @apiSchema (params) datafeedIdSchema * @apiSchema (body) datafeedConfigSchema */ - router.put( - { - path: '/api/ml/datafeeds/{datafeedId}', - validate: { - params: datafeedIdSchema, - body: datafeedConfigSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}`, + access: 'internal', options: { tags: ['access:ml:canCreateDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const body = await mlClient.putDatafeed( - { - datafeed_id: datafeedId, - // @ts-expect-error type mismatch for `time_span` (string | number versus estypes.Duration) - body: request.body, + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + body: datafeedConfigSchema, }, - getAuthorizationHeader(request) - ); + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const body = await mlClient.putDatafeed( + { + datafeed_id: datafeedId, + // @ts-expect-error type mismatch for `time_span` (string | number versus estypes.Duration) + body: request.body, + }, + getAuthorizationHeader(request) + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {post} /api/ml/datafeeds/:datafeedId/_update Updates datafeed for given datafeed id + * @api {post} /internal/ml/datafeeds/:datafeedId/_update Updates datafeed for given datafeed id * @apiName UpdateDatafeed * @apiDescription Updates certain properties of a datafeed * * @apiSchema (params) datafeedIdSchema * @apiSchema (body) datafeedConfigSchema */ - router.post( - { - path: '/api/ml/datafeeds/{datafeedId}/_update', - validate: { - params: datafeedIdSchema, - body: datafeedConfigSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}/_update`, + access: 'internal', options: { tags: ['access:ml:canUpdateDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const body = await mlClient.updateDatafeed( - { - datafeed_id: datafeedId, - // @ts-expect-error type mismatch for `time_span` (string | number versus estypes.Duration) - body: request.body, + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + body: datafeedConfigSchema, }, - getAuthorizationHeader(request) - ); + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const body = await mlClient.updateDatafeed( + { + datafeed_id: datafeedId, + // @ts-expect-error type mismatch for `time_span` (string | number versus estypes.Duration) + body: request.body, + }, + getAuthorizationHeader(request) + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {delete} /api/ml/datafeeds/:datafeedId Deletes datafeed + * @api {delete} /internal/ml/datafeeds/:datafeedId Deletes datafeed * @apiName DeleteDatafeed * @apiDescription Deletes an existing datafeed * * @apiSchema (params) datafeedIdSchema * @apiSchema (query) deleteDatafeedQuerySchema */ - router.delete( - { - path: '/api/ml/datafeeds/{datafeedId}', - validate: { - params: datafeedIdSchema, - query: deleteDatafeedQuerySchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const options: estypes.MlDeleteDatafeedRequest = { - datafeed_id: request.params.datafeedId, - }; - const force = request.query.force; - if (force !== undefined) { - options.force = force; - } + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + query: deleteDatafeedQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const options: estypes.MlDeleteDatafeedRequest = { + datafeed_id: request.params.datafeedId, + }; + const force = request.query.force; + if (force !== undefined) { + options.force = force; + } - const body = await mlClient.deleteDatafeed(options); + const body = await mlClient.deleteDatafeed(options); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {post} /api/ml/datafeeds/:datafeedId/_start Starts datafeed for given datafeed id(s) + * @api {post} /internal/ml/datafeeds/:datafeedId/_start Starts datafeed for given datafeed id(s) * @apiName StartDatafeed * @apiDescription Starts one or more datafeeds * * @apiSchema (params) datafeedIdSchema * @apiSchema (body) startDatafeedSchema */ - router.post( - { - path: '/api/ml/datafeeds/{datafeedId}/_start', - validate: { - params: datafeedIdSchema, - body: startDatafeedSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}/_start`, + access: 'internal', options: { tags: ['access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const { start, end } = request.body; - - const body = await mlClient.startDatafeed({ - datafeed_id: datafeedId, - body: { - start: start !== undefined ? String(start) : undefined, - end: end !== undefined ? String(end) : undefined, + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + body: startDatafeedSchema, }, - }); + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const { start, end } = request.body; - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + const body = await mlClient.startDatafeed({ + datafeed_id: datafeedId, + body: { + start: start !== undefined ? String(start) : undefined, + end: end !== undefined ? String(end) : undefined, + }, + }); + + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {post} /api/ml/datafeeds/:datafeedId/_stop Stops datafeed for given datafeed id(s) + * @api {post} /internal/ml/datafeeds/:datafeedId/_stop Stops datafeed for given datafeed id(s) * @apiName StopDatafeed * @apiDescription Stops one or more datafeeds * * @apiSchema (params) datafeedIdSchema */ - router.post( - { - path: '/api/ml/datafeeds/{datafeedId}/_stop', - validate: { - params: datafeedIdSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}/_stop`, + access: 'internal', options: { tags: ['access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; - const body = await mlClient.stopDatafeed({ - datafeed_id: datafeedId, - }); + const body = await mlClient.stopDatafeed({ + datafeed_id: datafeedId, + }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DatafeedService * - * @api {get} /api/ml/datafeeds/:datafeedId/_preview Preview datafeed for given datafeed id + * @api {get} /internal/ml/datafeeds/:datafeedId/_preview Preview datafeed for given datafeed id * @apiName PreviewDatafeed * @apiDescription Previews a datafeed * * @apiSchema (params) datafeedIdSchema */ - router.get( - { - path: '/api/ml/datafeeds/{datafeedId}/_preview', - validate: { - params: datafeedIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/datafeeds/{datafeedId}/_preview`, + access: 'internal', options: { tags: ['access:ml:canPreviewDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const datafeedId = request.params.datafeedId; - const body = await mlClient.previewDatafeed( - { - datafeed_id: datafeedId, + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: datafeedIdSchema, }, - { ...getAuthorizationHeader(request), maxRetries: 0 } - ); + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const datafeedId = request.params.datafeedId; + const body = await mlClient.previewDatafeed( + { + datafeed_id: datafeedId, + }, + { ...getAuthorizationHeader(request), maxRetries: 0 } + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/fields_service.ts b/x-pack/plugins/ml/server/routes/fields_service.ts index 16a7b6c1455aee..43c4673da7635f 100644 --- a/x-pack/plugins/ml/server/routes/fields_service.ts +++ b/x-pack/plugins/ml/server/routes/fields_service.ts @@ -6,6 +6,7 @@ */ import { IScopedClusterClient } from '@kbn/core/server'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { @@ -33,7 +34,7 @@ export function fieldsService({ router, routeGuard }: RouteInitialization) { /** * @apiGroup FieldsService * - * @api {post} /api/ml/fields_service/field_cardinality Get cardinality of fields + * @api {post} /internal/ml/fields_service/field_cardinality Get cardinality of fields * @apiName GetCardinalityOfFields * @apiDescription Returns the cardinality of one or more fields. Returns an Object whose keys are the names of the fields, with values equal to the cardinality of the field * @@ -41,33 +42,40 @@ export function fieldsService({ router, routeGuard }: RouteInitialization) { * * @apiSuccess {number} fieldName cardinality of the field. */ - router.post( - { - path: '/api/ml/fields_service/field_cardinality', - validate: { - body: getCardinalityOfFieldsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/fields_service/field_cardinality`, + access: 'internal', options: { tags: ['access:ml:canGetFieldInfo'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const resp = await getCardinalityOfFields(client, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: getCardinalityOfFieldsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const resp = await getCardinalityOfFields(client, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup FieldsService * - * @api {post} /api/ml/fields_service/time_field_range Get time field range + * @api {post} /internal/ml/fields_service/time_field_range Get time field range * @apiName GetTimeFieldRange * @apiDescription Returns the time range for the given index and query using the specified time range. * @@ -76,26 +84,33 @@ export function fieldsService({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Object} start start of time range with epoch and string properties. * @apiSuccess {Object} end end of time range with epoch and string properties. */ - router.post( - { - path: '/api/ml/fields_service/time_field_range', - validate: { - body: getTimeFieldRangeSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/fields_service/time_field_range`, + access: 'internal', options: { tags: ['access:ml:canGetFieldInfo'], }, - }, - routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { - try { - const resp = await getTimeFieldRange(client, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: getTimeFieldRangeSchema, + }, + }, + }, + routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { + try { + const resp = await getTimeFieldRange(client, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/filters.ts b/x-pack/plugins/ml/server/routes/filters.ts index b4c7d5bf5b109a..72bebe59529fd7 100644 --- a/x-pack/plugins/ml/server/routes/filters.ts +++ b/x-pack/plugins/ml/server/routes/filters.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { createFilterSchema, filterIdSchema, updateFilterSchema } from './schemas/filters_schema'; @@ -47,38 +48,43 @@ export function filtersRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup Filters * - * @api {get} /api/ml/filters Get filters + * @api {get} /internal/ml/filters Get filters * @apiName GetFilters * @apiDescription Retrieves the list of filters which are used for custom rules in anomaly detection. Sets the size limit explicitly to return a maximum of 1000. * * @apiSuccess {Boolean} success * @apiSuccess {Object[]} filters list of filters */ - router.get( - { - path: '/api/ml/filters', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/filters`, + access: 'internal', options: { tags: ['access:ml:canGetFilters'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const resp = await getAllFilters(mlClient); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const resp = await getAllFilters(mlClient); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Filters * - * @api {get} /api/ml/filters/:filterId Gets filter by ID + * @api {get} /internal/ml/filters/:filterId Gets filter by ID * @apiName GetFilterById * @apiDescription Retrieves the filter with the specified ID. * @@ -87,32 +93,37 @@ export function filtersRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Boolean} success * @apiSuccess {Object} filter the filter with the specified ID */ - router.get( - { - path: '/api/ml/filters/{filterId}', - validate: { - params: filterIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/filters/{filterId}`, + access: 'internal', options: { tags: ['access:ml:canGetFilters'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getFilter(mlClient, request.params.filterId); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { params: filterIdSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getFilter(mlClient, request.params.filterId); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Filters * - * @api {put} /api/ml/filters Creates a filter + * @api {put} /internal/ml/filters Creates a filter * @apiName CreateFilter * @apiDescription Instantiates a filter, for use by custom rules in anomaly detection. * @@ -121,34 +132,39 @@ export function filtersRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Boolean} success * @apiSuccess {Object} filter created filter */ - router.put( - { - path: '/api/ml/filters', - validate: { - body: createFilterSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/filters`, + access: 'internal', options: { tags: ['access:ml:canCreateFilter'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = request.body; - const resp = await newFilter(mlClient, body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { body: createFilterSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = request.body; + const resp = await newFilter(mlClient, body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Filters * - * @api {put} /api/ml/filters/:filterId Updates a filter + * @api {put} /internal/ml/filters/:filterId Updates a filter * @apiName UpdateFilter * @apiDescription Updates the description of a filter, adds items or removes items. * @@ -158,69 +174,83 @@ export function filtersRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Boolean} success * @apiSuccess {Object} filter updated filter */ - router.put( - { - path: '/api/ml/filters/{filterId}', - validate: { - params: filterIdSchema, - body: updateFilterSchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/filters/{filterId}`, + access: 'internal', options: { tags: ['access:ml:canCreateFilter'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { filterId } = request.params; - const body = request.body; - const resp = await updateFilter(mlClient, filterId, body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: filterIdSchema, + body: updateFilterSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { filterId } = request.params; + const body = request.body; + const resp = await updateFilter(mlClient, filterId, body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Filters * - * @api {delete} /api/ml/filters/:filterId Delete filter + * @api {delete} /internal/ml/filters/:filterId Delete filter * @apiName DeleteFilter * @apiDescription Deletes the filter with the specified ID. * * @apiSchema (params) filterIdSchema */ - router.delete( - { - path: '/api/ml/filters/{filterId}', - validate: { - params: filterIdSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/filters/{filterId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteFilter'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { filterId } = request.params; - const resp = await deleteFilter(mlClient, filterId); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: filterIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { filterId } = request.params; + const resp = await deleteFilter(mlClient, filterId); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup Filters * - * @api {get} /api/ml/filters/_stats Gets filters stats + * @api {get} /internal/ml/filters/_stats Gets filters stats * @apiName GetFiltersStats * @apiDescription Retrieves the list of filters which are used for custom rules in anomaly detection, * with stats on the list of jobs and detectors which are using each filter. @@ -228,24 +258,29 @@ export function filtersRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Boolean} success * @apiSuccess {Object[]} filters list of filters with stats on usage */ - router.get( - { - path: '/api/ml/filters/_stats', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/filters/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetFilters'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const resp = await getAllFilterStats(mlClient); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const resp = await getAllFilterStats(mlClient); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/indices.ts b/x-pack/plugins/ml/server/routes/indices.ts index 433ec659a36dac..9880f35ec0d7af 100644 --- a/x-pack/plugins/ml/server/routes/indices.ts +++ b/x-pack/plugins/ml/server/routes/indices.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { indicesSchema } from './schemas/indices_schema'; @@ -16,34 +17,41 @@ export function indicesRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup Indices * - * @api {post} /api/ml/indices/field_caps Field caps + * @api {post} /internal/ml/indices/field_caps Field caps * @apiName FieldCaps * @apiDescription Retrieves the capabilities of fields among multiple indices. * * @apiSchema (body) indicesSchema */ - router.post( - { - path: '/api/ml/indices/field_caps', - validate: { - body: indicesSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/indices/field_caps`, + access: 'internal', options: { tags: ['access:ml:canGetFieldInfo'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { - body: { index, fields: requestFields }, - } = request; - const fields = - requestFields !== undefined && Array.isArray(requestFields) ? requestFields : '*'; - const body = await client.asCurrentUser.fieldCaps({ index, fields }, { maxRetries: 0 }); - return response.ok({ body }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: indicesSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { + body: { index, fields: requestFields }, + } = request; + const fields = + requestFields !== undefined && Array.isArray(requestFields) ? requestFields : '*'; + const body = await client.asCurrentUser.fieldCaps({ index, fields }, { maxRetries: 0 }); + return response.ok({ body }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/job_audit_messages.ts b/x-pack/plugins/ml/server/routes/job_audit_messages.ts index 360e2bef4c99e2..f0eddade78db5d 100644 --- a/x-pack/plugins/ml/server/routes/job_audit_messages.ts +++ b/x-pack/plugins/ml/server/routes/job_audit_messages.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { jobAuditMessagesProvider } from '../models/job_audit_messages'; @@ -21,116 +22,137 @@ export function jobAuditMessagesRoutes({ router, routeGuard }: RouteInitializati /** * @apiGroup JobAuditMessages * - * @api {get} /api/ml/job_audit_messages/messages/:jobId Get audit messages + * @api {get} /internal/ml/job_audit_messages/messages/:jobId Get audit messages * @apiName GetJobAuditMessages * @apiDescription Returns audit messages for specified job ID * * @apiSchema (params) jobAuditMessagesJobIdSchema * @apiSchema (query) jobAuditMessagesQuerySchema */ - router.get( - { - path: '/api/ml/job_audit_messages/messages/{jobId}', - validate: { - params: jobAuditMessagesJobIdSchema, - query: jobAuditMessagesQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/job_audit_messages/messages/{jobId}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ client, mlClient, request, response, mlSavedObjectService }) => { - try { - const { getJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); - const { jobId } = request.params; - const { from, start, end } = request.query; - const resp = await getJobAuditMessages(mlSavedObjectService, { - jobId, - from, - start, - end, - }); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: jobAuditMessagesJobIdSchema, + query: jobAuditMessagesQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlClient, request, response, mlSavedObjectService }) => { + try { + const { getJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); + const { jobId } = request.params; + const { from, start, end } = request.query; + const resp = await getJobAuditMessages(mlSavedObjectService, { + jobId, + from, + start, + end, + }); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup JobAuditMessages * - * @api {get} /api/ml/job_audit_messages/messages Get all audit messages + * @api {get} /internal/ml/job_audit_messages/messages Get all audit messages * @apiName GetAllJobAuditMessages * @apiDescription Returns all audit messages * * @apiSchema (query) jobAuditMessagesQuerySchema */ - router.get( - { - path: '/api/ml/job_audit_messages/messages', - validate: { - query: jobAuditMessagesQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/job_audit_messages/messages`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ client, mlClient, request, response, mlSavedObjectService }) => { - try { - const { getJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); - const { from } = request.query; - const resp = await getJobAuditMessages(mlSavedObjectService, { from }); + }) + .addVersion( + { + version: '1', + validate: { + request: { + query: jobAuditMessagesQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlClient, request, response, mlSavedObjectService }) => { + try { + const { getJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); + const { from } = request.query; + const resp = await getJobAuditMessages(mlSavedObjectService, { from }); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup JobAuditMessages * - * @api {put} /api/ml/job_audit_messages/clear_messages Clear messages + * @api {put} /internal/ml/job_audit_messages/clear_messages Clear messages * @apiName ClearJobAuditMessages * @apiDescription Clear the job audit messages. * * @apiSchema (body) clearJobAuditMessagesSchema */ - router.put( - { - path: '/api/ml/job_audit_messages/clear_messages', - validate: { - body: clearJobAuditMessagesBodySchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/job_audit_messages/clear_messages`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ client, mlClient, request, response, mlSavedObjectService }) => { - try { - const { clearJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); - const { jobId, notificationIndices } = request.body; - const resp = await clearJobAuditMessages(jobId, notificationIndices); + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: clearJobAuditMessagesBodySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlClient, request, response, mlSavedObjectService }) => { + try { + const { clearJobAuditMessages } = jobAuditMessagesProvider(client, mlClient); + const { jobId, notificationIndices } = request.body; + const resp = await clearJobAuditMessages(jobId, notificationIndices); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); } diff --git a/x-pack/plugins/ml/server/routes/job_service.ts b/x-pack/plugins/ml/server/routes/job_service.ts index 6a465b2e8ad1d2..cb8bbebd95d31b 100644 --- a/x-pack/plugins/ml/server/routes/job_service.ts +++ b/x-pack/plugins/ml/server/routes/job_service.ts @@ -7,6 +7,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { schema } from '@kbn/config-schema'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import type { RouteInitialization } from '../types'; import { @@ -42,75 +43,89 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/force_start_datafeeds Start datafeeds + * @api {post} /internal/ml/jobs/force_start_datafeeds Start datafeeds * @apiName ForceStartDatafeeds * @apiDescription Starts one or more datafeeds * * @apiSchema (body) forceStartDatafeedSchema */ - router.post( - { - path: '/api/ml/jobs/force_start_datafeeds', - validate: { - body: forceStartDatafeedSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/force_start_datafeeds`, + access: 'internal', options: { tags: ['access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { forceStartDatafeeds } = jobServiceProvider(client, mlClient); - const { datafeedIds, start, end } = request.body; - const resp = await forceStartDatafeeds(datafeedIds, start, end); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: forceStartDatafeedSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { forceStartDatafeeds } = jobServiceProvider(client, mlClient); + const { datafeedIds, start, end } = request.body; + const resp = await forceStartDatafeeds(datafeedIds, start, end); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/stop_datafeeds Stop datafeeds + * @api {post} /internal/ml/jobs/stop_datafeeds Stop datafeeds * @apiName StopDatafeeds * @apiDescription Stops one or more datafeeds * * @apiSchema (body) datafeedIdsSchema */ - router.post( - { - path: '/api/ml/jobs/stop_datafeeds', - validate: { - body: datafeedIdsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/stop_datafeeds`, + access: 'internal', options: { tags: ['access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { stopDatafeeds } = jobServiceProvider(client, mlClient); - const { datafeedIds } = request.body; - const resp = await stopDatafeeds(datafeedIds); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: datafeedIdsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { stopDatafeeds } = jobServiceProvider(client, mlClient); + const { datafeedIds } = request.body; + const resp = await stopDatafeeds(datafeedIds); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/delete_jobs Delete jobs + * @api {post} /internal/ml/jobs/delete_jobs Delete jobs * @apiName DeleteJobs * @apiDescription Deletes an existing anomaly detection job * @@ -118,7 +133,7 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { */ router.post( { - path: '/api/ml/jobs/delete_jobs', + path: `${ML_INTERNAL_BASE_PATH}/jobs/delete_jobs`, validate: { body: deleteJobsSchema, }, @@ -144,109 +159,130 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/close_jobs Close jobs + * @api {post} /internal/ml/jobs/close_jobs Close jobs * @apiName CloseJobs * @apiDescription Closes one or more anomaly detection jobs * * @apiSchema (body) jobIdsSchema */ - router.post( - { - path: '/api/ml/jobs/close_jobs', - validate: { - body: jobIdsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/close_jobs`, + access: 'internal', options: { tags: ['access:ml:canCloseJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { closeJobs } = jobServiceProvider(client, mlClient); - const { jobIds } = request.body; - const resp = await closeJobs(jobIds); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: jobIdsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { closeJobs } = jobServiceProvider(client, mlClient); + const { jobIds } = request.body; + const resp = await closeJobs(jobIds); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/reset_jobs Reset multiple jobs + * @api {post} /internal/ml/jobs/reset_jobs Reset multiple jobs * @apiName ResetJobs * @apiDescription Resets one or more anomaly detection jobs * * @apiSchema (body) jobIdsSchema */ - router.post( - { - path: '/api/ml/jobs/reset_jobs', - validate: { - body: deleteJobsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/reset_jobs`, + access: 'internal', options: { tags: ['access:ml:canResetJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { resetJobs } = jobServiceProvider(client, mlClient); - const { jobIds, deleteUserAnnotations } = request.body; - const resp = await resetJobs(jobIds, deleteUserAnnotations); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: deleteJobsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { resetJobs } = jobServiceProvider(client, mlClient); + const { jobIds, deleteUserAnnotations } = request.body; + const resp = await resetJobs(jobIds, deleteUserAnnotations); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/force_stop_and_close_job Force stop and close job + * @api {post} /internal/ml/jobs/force_stop_and_close_job Force stop and close job * @apiName ForceStopAndCloseJob * @apiDescription Force stops the datafeed and then force closes the anomaly detection job specified by job ID * * @apiSchema (body) jobIdSchema */ - router.post( - { - path: '/api/ml/jobs/force_stop_and_close_job', - validate: { - body: jobIdSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/force_stop_and_close_job`, + access: 'internal', options: { tags: ['access:ml:canCloseJob', 'access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { forceStopAndCloseJob } = jobServiceProvider(client, mlClient); - const { jobId } = request.body; - const resp = await forceStopAndCloseJob(jobId); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: jobIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { forceStopAndCloseJob } = jobServiceProvider(client, mlClient); + const { jobId } = request.body; + const resp = await forceStopAndCloseJob(jobId); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/jobs_summary Jobs summary + * @api {post} /internal/ml/jobs/jobs_summary Jobs summary * @apiName JobsSummary * @apiDescription Returns a list of anomaly detection jobs, with summary level information for every job. * For any supplied job IDs, full job information will be returned, which include the analysis configuration, @@ -257,735 +293,858 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) { * @apiSuccess {Array} jobsList list of jobs. For any supplied job IDs, the job object will contain a fullJob property * which includes the full configuration and stats for the job. */ - router.post( - { - path: '/api/ml/jobs/jobs_summary', - validate: { - body: optionalJobIdsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_summary`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response, context }) => { - try { - const alerting = await context.alerting; - const { jobsSummary } = jobServiceProvider(client, mlClient, alerting?.getRulesClient()); - const { jobIds } = request.body; - const resp = await jobsSummary(jobIds); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { body: optionalJobIdsSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response, context }) => { + try { + const alerting = await context.alerting; + const { jobsSummary } = jobServiceProvider(client, mlClient, alerting?.getRulesClient()); + const { jobIds } = request.body; + const resp = await jobsSummary(jobIds); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/jobs_with_geo Jobs summary + * @api {post} /internal/ml/jobs/jobs_with_geo Jobs summary * @apiName JobsSummary * @apiDescription Returns a list of anomaly detection jobs with analysis config with fields supported by maps. * * @apiSuccess {Array} jobIds list of job ids. */ - router.get( - { - path: '/api/ml/jobs/jobs_with_geo', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_with_geo`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response, context }) => { - try { - const alerting = await context.alerting; - const { getJobIdsWithGeo } = jobServiceProvider( - client, - mlClient, - alerting?.getRulesClient() - ); + }) + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response, context }) => { + try { + const alerting = await context.alerting; + const { getJobIdsWithGeo } = jobServiceProvider( + client, + mlClient, + alerting?.getRulesClient() + ); - const resp = await getJobIdsWithGeo(); + const resp = await getJobIdsWithGeo(); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/jobs_with_time_range Jobs with time range + * @api {post} /internal/ml/jobs/jobs_with_time_range Jobs with time range * @apiName JobsWithTimeRange * @apiDescription Creates a list of jobs with data about the job's time range * * @apiSchema (body) jobsWithTimerangeSchema */ - router.post( - { - path: '/api/ml/jobs/jobs_with_time_range', - validate: { - body: jobsWithTimerangeSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_with_time_range`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { - try { - const { jobsWithTimerange } = jobServiceProvider(client, mlClient); - const resp = await jobsWithTimerange(); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: jobsWithTimerangeSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { + try { + const { jobsWithTimerange } = jobServiceProvider(client, mlClient); + const resp = await jobsWithTimerange(); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/job_for_cloning Get job for cloning + * @api {post} /internal/ml/jobs/job_for_cloning Get job for cloning * @apiName GetJobForCloning * @apiDescription Get the job configuration with auto generated fields excluded for cloning * * @apiSchema (body) jobIdSchema */ - router.post( - { - path: '/api/ml/jobs/job_for_cloning', - validate: { - body: jobIdSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/job_for_cloning`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { getJobForCloning } = jobServiceProvider(client, mlClient); - const { jobId } = request.body; - - const resp = await getJobForCloning(jobId); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: jobIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { getJobForCloning } = jobServiceProvider(client, mlClient); + const { jobId } = request.body; + + const resp = await getJobForCloning(jobId); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/jobs Create jobs list + * @api {post} /internal/ml/jobs/jobs Create jobs list * @apiName CreateFullJobsList * @apiDescription Creates a list of jobs * * @apiSchema (body) optionalJobIdsSchema */ - router.post( - { - path: '/api/ml/jobs/jobs', - validate: { - body: optionalJobIdsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response, context }) => { - try { - const alerting = await context.alerting; - const { createFullJobsList } = jobServiceProvider( - client, - mlClient, - alerting?.getRulesClient() - ); - const { jobIds } = request.body; - const resp = await createFullJobsList(jobIds); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: optionalJobIdsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response, context }) => { + try { + const alerting = await context.alerting; + const { createFullJobsList } = jobServiceProvider( + client, + mlClient, + alerting?.getRulesClient() + ); + const { jobIds } = request.body; + const resp = await createFullJobsList(jobIds); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {get} /api/ml/jobs/groups Get job groups + * @api {get} /internal/ml/jobs/groups Get job groups * @apiName GetAllGroups * @apiDescription Returns array of group objects with job ids listed for each group */ - router.get( - { - path: '/api/ml/jobs/groups', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/groups`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { - try { - const { getAllGroups } = jobServiceProvider(client, mlClient); - const resp = await getAllGroups(); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { + try { + const { getAllGroups } = jobServiceProvider(client, mlClient); + const resp = await getAllGroups(); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/update_groups Update job groups + * @api {post} /internal/ml/jobs/update_groups Update job groups * @apiName UpdateGroups * @apiDescription Updates 'groups' property of an anomaly detection job * * @apiSchema (body) updateGroupsSchema */ - router.post( - { - path: '/api/ml/jobs/update_groups', - validate: { - body: updateGroupsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/update_groups`, + access: 'internal', options: { tags: ['access:ml:canUpdateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { updateGroups } = jobServiceProvider(client, mlClient); - const { jobs } = request.body; - const resp = await updateGroups(jobs); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: updateGroupsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { updateGroups } = jobServiceProvider(client, mlClient); + const { jobs } = request.body; + const resp = await updateGroups(jobs); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {get} /api/ml/jobs/blocking_jobs_tasks Get blocking job tasks + * @api {get} /internal/ml/jobs/blocking_jobs_tasks Get blocking job tasks * @apiName BlockingJobTasks * @apiDescription Gets the ids of deleting, resetting or reverting anomaly detection jobs */ - router.get( - { - path: '/api/ml/jobs/blocking_jobs_tasks', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/blocking_jobs_tasks`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { - try { - const { blockingJobTasks } = jobServiceProvider(client, mlClient); - const resp = await blockingJobTasks(); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { + try { + const { blockingJobTasks } = jobServiceProvider(client, mlClient); + const resp = await blockingJobTasks(); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/jobs_exist Check whether jobs exists in current or any space + * @api {post} /internal/ml/jobs/jobs_exist Check whether jobs exists in current or any space * @apiName JobsExist * @apiDescription Checks if each of the jobs in the specified list of IDs exist. * If allSpaces is true, the check will look across all spaces. * * @apiSchema (body) jobsExistSchema */ - router.post( - { - path: '/api/ml/jobs/jobs_exist', - validate: { - body: jobsExistSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/jobs_exist`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { jobsExist } = jobServiceProvider(client, mlClient); - const { jobIds, allSpaces } = request.body; - const resp = await jobsExist(jobIds, allSpaces); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: jobsExistSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { jobsExist } = jobServiceProvider(client, mlClient); + const { jobIds, allSpaces } = request.body; + const resp = await jobsExist(jobIds, allSpaces); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {get} /api/ml/jobs/new_job_caps/:indexPattern Get new job capabilities + * @api {get} /internal/ml/jobs/new_job_caps/:indexPattern Get new job capabilities * @apiName NewJobCaps * @apiDescription Retrieve the capabilities of fields for indices */ - router.get( - { - path: '/api/ml/jobs/new_job_caps/{indexPattern}', - validate: { - params: schema.object({ indexPattern: schema.string() }), - query: schema.maybe(schema.object({ rollup: schema.maybe(schema.string()) })), - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_caps/{indexPattern}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ client, mlClient, request, response, getDataViewsService }) => { - try { - const { indexPattern } = request.params; - const isRollup = request.query?.rollup === 'true'; - const { newJobCaps } = jobServiceProvider(client, mlClient); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: schema.object({ indexPattern: schema.string() }), + query: schema.maybe(schema.object({ rollup: schema.maybe(schema.string()) })), + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlClient, request, response, getDataViewsService }) => { + try { + const { indexPattern } = request.params; + const isRollup = request.query?.rollup === 'true'; + const { newJobCaps } = jobServiceProvider(client, mlClient); - const dataViewsService = await getDataViewsService(); - const resp = await newJobCaps(indexPattern, isRollup, dataViewsService); + const dataViewsService = await getDataViewsService(); + const resp = await newJobCaps(indexPattern, isRollup, dataViewsService); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/new_job_line_chart Get job line chart data + * @api {post} /internal/ml/jobs/new_job_line_chart Get job line chart data * @apiName NewJobLineChart * @apiDescription Returns line chart data for anomaly detection job * * @apiSchema (body) chartSchema */ - router.post( - { - path: '/api/ml/jobs/new_job_line_chart', - validate: { - body: schema.object(basicChartSchema), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_line_chart`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - splitFieldValue, - runtimeMappings, - indicesOptions, - } = request.body; - - const { newJobLineChart } = jobServiceProvider(client, mlClient); - const resp = await newJobLineChart( - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - splitFieldValue, - runtimeMappings, - indicesOptions - ); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.object(basicChartSchema), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + splitFieldValue, + runtimeMappings, + indicesOptions, + } = request.body; + + const { newJobLineChart } = jobServiceProvider(client, mlClient); + const resp = await newJobLineChart( + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + splitFieldValue, + runtimeMappings, + indicesOptions + ); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/new_job_population_chart Get population job chart data + * @api {post} /internal/ml/jobs/new_job_population_chart Get population job chart data * @apiName NewJobPopulationChart * @apiDescription Returns population job chart data * * @apiSchema (body) chartSchema */ - router.post( - { - path: '/api/ml/jobs/new_job_population_chart', - validate: { - body: schema.object(populationChartSchema), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/new_job_population_chart`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - runtimeMappings, - indicesOptions, - } = request.body; - - const { newJobPopulationChart } = jobServiceProvider(client, mlClient); - const resp = await newJobPopulationChart( - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - runtimeMappings, - indicesOptions - ); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.object(populationChartSchema), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + runtimeMappings, + indicesOptions, + } = request.body; + + const { newJobPopulationChart } = jobServiceProvider(client, mlClient); + const resp = await newJobPopulationChart( + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + runtimeMappings, + indicesOptions + ); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {get} /api/ml/jobs/all_jobs_and_group_ids Get all job and group IDs + * @api {get} /internal/ml/jobs/all_jobs_and_group_ids Get all job and group IDs * @apiName GetAllJobAndGroupIds * @apiDescription Returns a list of all job IDs and all group IDs */ - router.get( - { - path: '/api/ml/jobs/all_jobs_and_group_ids', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/all_jobs_and_group_ids`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { - try { - const { getAllJobAndGroupIds } = jobServiceProvider(client, mlClient); - const resp = await getAllJobAndGroupIds(); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { + try { + const { getAllJobAndGroupIds } = jobServiceProvider(client, mlClient); + const resp = await getAllJobAndGroupIds(); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/look_back_progress Get lookback progress + * @api {post} /internal/ml/jobs/look_back_progress Get lookback progress * @apiName GetLookBackProgress * @apiDescription Returns current progress of anomaly detection job * * @apiSchema (body) lookBackProgressSchema */ - router.post( - { - path: '/api/ml/jobs/look_back_progress', - validate: { - body: schema.object(lookBackProgressSchema), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/look_back_progress`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { getLookBackProgress } = jobServiceProvider(client, mlClient); - const { jobId, start, end } = request.body; - const resp = await getLookBackProgress(jobId, start, end); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.object(lookBackProgressSchema), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { getLookBackProgress } = jobServiceProvider(client, mlClient); + const { jobId, start, end } = request.body; + const resp = await getLookBackProgress(jobId, start, end); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/categorization_field_examples Get categorization field examples + * @api {post} /internal/ml/jobs/categorization_field_examples Get categorization field examples * @apiName ValidateCategoryExamples * @apiDescription Validates category examples * * @apiSchema (body) categorizationFieldExamplesSchema */ - router.post( - { - path: '/api/ml/jobs/categorization_field_examples', - validate: { - body: schema.object(categorizationFieldExamplesSchema), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/categorization_field_examples`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { validateCategoryExamples } = categorizationExamplesProvider(client); - const { - indexPatternTitle, - timeField, - query, - size, - field, - start, - end, - analyzer, - runtimeMappings, - indicesOptions, - } = request.body; - - const resp = await validateCategoryExamples( - indexPatternTitle, - query, - size, - field, - timeField, - start, - end, - analyzer, - runtimeMappings, - indicesOptions - ); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.object(categorizationFieldExamplesSchema), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { validateCategoryExamples } = categorizationExamplesProvider(client); + const { + indexPatternTitle, + timeField, + query, + size, + field, + start, + end, + analyzer, + runtimeMappings, + indicesOptions, + } = request.body; + + const resp = await validateCategoryExamples( + indexPatternTitle, + query, + size, + field, + timeField, + start, + end, + analyzer, + runtimeMappings, + indicesOptions + ); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/top_categories Get top categories + * @api {post} /internal/ml/jobs/top_categories Get top categories * @apiName TopCategories * @apiDescription Returns list of top categories * * @apiSchema (body) topCategoriesSchema */ - router.post( - { - path: '/api/ml/jobs/top_categories', - validate: { - body: schema.object(topCategoriesSchema), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/top_categories`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { topCategories } = jobServiceProvider(client, mlClient); - const { jobId, count } = request.body; - const resp = await topCategories(jobId, count); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.object(topCategoriesSchema), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { topCategories } = jobServiceProvider(client, mlClient); + const { jobId, count } = request.body; + const resp = await topCategories(jobId, count); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/datafeed_preview Get datafeed preview + * @api {post} /internal/ml/jobs/datafeed_preview Get datafeed preview * @apiName DatafeedPreview * @apiDescription Returns a preview of the datafeed search * * @apiSchema (body) datafeedPreviewSchema */ - router.post( - { - path: '/api/ml/jobs/datafeed_preview', - validate: { - body: datafeedPreviewSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/datafeed_preview`, + access: 'internal', options: { tags: ['access:ml:canPreviewDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { datafeedId, job, datafeed } = request.body; - - const payload = - datafeedId !== undefined - ? { - datafeed_id: datafeedId, - } - : ({ - body: { - job_config: job, - datafeed_config: datafeed, - }, - } as estypes.MlPreviewDatafeedRequest); - - const body = await mlClient.previewDatafeed(payload, { - ...getAuthorizationHeader(request), - maxRetries: 0, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: datafeedPreviewSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { datafeedId, job, datafeed } = request.body; + + const payload = + datafeedId !== undefined + ? { + datafeed_id: datafeedId, + } + : ({ + body: { + job_config: job, + datafeed_config: datafeed, + }, + } as estypes.MlPreviewDatafeedRequest); + + const body = await mlClient.previewDatafeed(payload, { + ...getAuthorizationHeader(request), + maxRetries: 0, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/revert_model_snapshot Revert model snapshot + * @api {post} /internal/ml/jobs/revert_model_snapshot Revert model snapshot * @apiName RevertModelSnapshot * @apiDescription Reverts a job to a specified snapshot. Also allows the job to replayed to a specified date and to auto create calendars to skip analysis of specified date ranges * * @apiSchema (body) revertModelSnapshotSchema */ - router.post( - { - path: '/api/ml/jobs/revert_model_snapshot', - validate: { - body: revertModelSnapshotSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/revert_model_snapshot`, + access: 'internal', options: { tags: ['access:ml:canCreateJob', 'access:ml:canStartStopDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { revertModelSnapshot } = jobServiceProvider(client, mlClient); - const { jobId, snapshotId, replay, end, deleteInterveningResults, calendarEvents } = - request.body; - const resp = await revertModelSnapshot( - jobId, - snapshotId, - replay, - end, - deleteInterveningResults, - calendarEvents - ); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: revertModelSnapshotSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { revertModelSnapshot } = jobServiceProvider(client, mlClient); + const { jobId, snapshotId, replay, end, deleteInterveningResults, calendarEvents } = + request.body; + const resp = await revertModelSnapshot( + jobId, + snapshotId, + replay, + end, + deleteInterveningResults, + calendarEvents + ); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobService * - * @api {post} /api/ml/jobs/bulk_create Bulk create jobs and datafeeds + * @api {post} /internal/ml/jobs/bulk_create Bulk create jobs and datafeeds * @apiName BulkCreateJobs * @apiDescription Bulk create jobs and datafeeds. * * @apiSchema (body) bulkCreateSchema */ - router.post( - { - path: '/api/ml/jobs/bulk_create', - validate: { - body: bulkCreateSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/jobs/bulk_create`, + access: 'internal', options: { tags: ['access:ml:canPreviewDatafeed'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const bulkJobs = request.body; - - const { bulkCreate } = jobServiceProvider(client, mlClient); - const jobs = (Array.isArray(bulkJobs) ? bulkJobs : [bulkJobs]) as Array<{ - job: Job; - datafeed: Datafeed; - }>; - const body = await bulkCreate(jobs, getAuthorizationHeader(request)); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: bulkCreateSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const bulkJobs = request.body; + + const { bulkCreate } = jobServiceProvider(client, mlClient); + const jobs = (Array.isArray(bulkJobs) ? bulkJobs : [bulkJobs]) as Array<{ + job: Job; + datafeed: Datafeed; + }>; + const body = await bulkCreate(jobs, getAuthorizationHeader(request)); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/job_validation.ts b/x-pack/plugins/ml/server/routes/job_validation.ts index ca4d6e7b6b7154..3a43cd439ae8c5 100644 --- a/x-pack/plugins/ml/server/routes/job_validation.ts +++ b/x-pack/plugins/ml/server/routes/job_validation.ts @@ -8,6 +8,7 @@ import Boom from '@hapi/boom'; import { IScopedClusterClient } from '@kbn/core/server'; import { TypeOf } from '@kbn/config-schema'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import type { AnalysisConfig, Datafeed } from '../../common/types/anomaly_detection_jobs'; import { wrapError } from '../client/error_wrapper'; import type { RouteInitialization } from '../types'; @@ -65,52 +66,58 @@ export function jobValidationRoutes({ router, mlLicense, routeGuard }: RouteInit /** * @apiGroup JobValidation * - * @api {post} /api/ml/validate/estimate_bucket_span Estimate bucket span + * @api {post} /internal/ml/validate/estimate_bucket_span Estimate bucket span * @apiName EstimateBucketSpan * @apiDescription Estimates minimum viable bucket span based on the characteristics of a pre-viewed subset of the data * * @apiSchema (body) estimateBucketSpanSchema */ - router.post( - { - path: '/api/ml/validate/estimate_bucket_span', - validate: { - body: estimateBucketSpanSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/validate/estimate_bucket_span`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - let errorResp; - const resp = await estimateBucketSpanFactory(client)(request.body) - // this catch gets triggered when the estimation code runs without error - // but isn't able to come up with a bucket span estimation. - // this doesn't return a HTTP error but an object with an error message a HTTP error would be - // too severe for this case. - .catch((error: any) => { - errorResp = { - error: true, - message: error, - }; - }); - - return response.ok({ - body: errorResp !== undefined ? errorResp : resp, - }); - } catch (e) { - // this catch gets triggered when an actual error gets thrown when running - // the estimation code, for example when the request payload is malformed - throw Boom.badRequest(e); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { body: estimateBucketSpanSchema }, + }, + }, + + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + let errorResp; + const resp = await estimateBucketSpanFactory(client)(request.body) + // this catch gets triggered when the estimation code runs without error + // but isn't able to come up with a bucket span estimation. + // this doesn't return a HTTP error but an object with an error message a HTTP error would be + // too severe for this case. + .catch((error: any) => { + errorResp = { + error: true, + message: error, + }; + }); + + return response.ok({ + body: errorResp !== undefined ? errorResp : resp, + }); + } catch (e) { + // this catch gets triggered when an actual error gets thrown when running + // the estimation code, for example when the request payload is malformed + throw Boom.badRequest(e); + } + }) + ); /** * @apiGroup JobValidation * - * @api {post} /api/ml/validate/calculate_model_memory_limit Calculates model memory limit + * @api {post} /internal/ml/validate/calculate_model_memory_limit Calculates model memory limit * @apiName CalculateModelMemoryLimit * @apiDescription Calls _estimate_model_memory endpoint to retrieve model memory estimation. * @@ -118,139 +125,167 @@ export function jobValidationRoutes({ router, mlLicense, routeGuard }: RouteInit * * @apiSuccess {String} modelMemoryLimit */ - router.post( - { - path: '/api/ml/validate/calculate_model_memory_limit', - validate: { - body: modelMemoryLimitSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/validate/calculate_model_memory_limit`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const resp = await calculateModelMemoryLimit(client, mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: modelMemoryLimitSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const resp = await calculateModelMemoryLimit(client, mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobValidation * - * @api {post} /api/ml/validate/cardinality Validate cardinality + * @api {post} /internal/ml/validate/cardinality Validate cardinality * @apiName ValidateCardinality * @apiDescription Validates cardinality for the given job configuration * * @apiSchema (body) validateCardinalitySchema */ - router.post( - { - path: '/api/ml/validate/cardinality', - validate: { - body: validateCardinalitySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/validate/cardinality`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - // @ts-expect-error datafeed config is incorrect - const resp = await validateCardinality(client, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: validateCardinalitySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + // @ts-expect-error datafeed config is incorrect + const resp = await validateCardinality(client, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup JobValidation * - * @api {post} /api/ml/validate/job Validates job + * @api {post} /internal/ml/validate/job Validates job * @apiName ValidateJob * @apiDescription Validates the given job configuration * * @apiSchema (body) validateJobSchema */ - router.post( - { - path: '/api/ml/validate/job', - validate: { - body: validateJobSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/validate/job`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const resp = await validateJob( - client, - mlClient, - request.body, - getAuthorizationHeader(request), - mlLicense.isSecurityEnabled() === false - ); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: validateJobSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const resp = await validateJob( + client, + mlClient, + request.body, + getAuthorizationHeader(request), + mlLicense.isSecurityEnabled() === false + ); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup DataFeedPreviewValidation * - * @api {post} /api/ml/validate/datafeed_preview Validates datafeed preview + * @api {post} /internal/ml/validate/datafeed_preview Validates datafeed preview * @apiName ValidateDataFeedPreview * @apiDescription Validates that the datafeed preview runs successfully and produces results * * @apiSchema (body) validateDatafeedPreviewSchema */ - router.post( - { - path: '/api/ml/validate/datafeed_preview', - validate: { - body: validateDatafeedPreviewSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/validate/datafeed_preview`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { - body: { job, start, end }, - } = request; + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: validateDatafeedPreviewSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { + body: { job, start, end }, + } = request; - const resp = await validateDatafeedPreview( - mlClient, - getAuthorizationHeader(request), - job as CombinedJob, - start, - end - ); + const resp = await validateDatafeedPreview( + mlClient, + getAuthorizationHeader(request), + job as CombinedJob, + start, + end + ); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/json_schema.ts b/x-pack/plugins/ml/server/routes/json_schema.ts index c1c7c65b485190..01aba014fe29ab 100644 --- a/x-pack/plugins/ml/server/routes/json_schema.ts +++ b/x-pack/plugins/ml/server/routes/json_schema.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { getJsonSchemaQuerySchema } from '../../common/api_schemas/json_schema_schema'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; @@ -14,35 +15,42 @@ export function jsonSchemaRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup JsonSchema * - * @api {get} /api/ml/json_schema Get requested JSON schema + * @api {get} /internal/ml/json_schema Get requested JSON schema * @apiName GetJsonSchema * @apiDescription Retrieves the JSON schema */ - router.get( - { - path: '/api/ml/json_schema', - validate: { - query: getJsonSchemaQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/json_schema`, + access: 'internal', options: { tags: ['access:ml:canAccessML'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ request, response }) => { - try { - const jsonSchemaService = new JsonSchemaService(); + }) + .addVersion( + { + version: '1', + validate: { + request: { + query: getJsonSchemaQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ request, response }) => { + try { + const jsonSchemaService = new JsonSchemaService(); - const result = await jsonSchemaService.extractSchema( - request.query.path, - request.query.method - ); + const result = await jsonSchemaService.extractSchema( + request.query.path, + request.query.method + ); - return response.ok({ - body: result, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: result, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/management.ts b/x-pack/plugins/ml/server/routes/management.ts index a11ac899a3d4ec..0179085869d36b 100644 --- a/x-pack/plugins/ml/server/routes/management.ts +++ b/x-pack/plugins/ml/server/routes/management.ts @@ -7,6 +7,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { BUILT_IN_MODEL_TYPE, BUILT_IN_MODEL_TAG } from '@kbn/ml-trained-models-utils'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import type { RouteInitialization } from '../types'; import { listTypeSchema } from './schemas/management_schema'; @@ -26,19 +27,17 @@ export function managementRoutes({ router, routeGuard }: RouteInitialization) { /** * @apiGroup Management * - * @api {get} /api/ml/management/list/:listType Management list + * @api {get} /internal/ml/management/list/:listType Management list * @apiName ManagementList * @apiDescription Returns a list of anomaly detection jobs, data frame analytics jobs or trained models * * @apiSchema (params) listTypeSchema * */ - router.get( - { - path: '/api/ml/management/list/{listType}', - validate: { - params: listTypeSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/management/list/{listType}`, + access: 'internal', options: { tags: [ 'access:ml:canCreateJob', @@ -46,108 +45,117 @@ export function managementRoutes({ router, routeGuard }: RouteInitialization) { 'access:ml:canCreateTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ client, mlClient, request, response, mlSavedObjectService }) => { - try { - const { listType } = request.params; - const { jobsSpaces, trainedModelsSpaces } = checksFactory(client, mlSavedObjectService); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: listTypeSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlClient, request, response, mlSavedObjectService }) => { + try { + const { listType } = request.params; + const { jobsSpaces, trainedModelsSpaces } = checksFactory(client, mlSavedObjectService); - switch (listType) { - case 'anomaly-detector': - const { jobsSummary } = jobServiceProvider(client, mlClient); - const [jobs, adJobStatus] = await Promise.all([jobsSummary(), jobsSpaces()]); + switch (listType) { + case 'anomaly-detector': + const { jobsSummary } = jobServiceProvider(client, mlClient); + const [jobs, adJobStatus] = await Promise.all([jobsSummary(), jobsSpaces()]); - const adJobsWithSpaces: AnomalyDetectionManagementItems[] = jobs.map((job) => { - return { - id: job.id, - description: job.description, - jobState: job.jobState, - datafeedState: job.datafeedState, - spaces: adJobStatus['anomaly-detector'][job.id] ?? [], - }; - }); + const adJobsWithSpaces: AnomalyDetectionManagementItems[] = jobs.map((job) => { + return { + id: job.id, + description: job.description, + jobState: job.jobState, + datafeedState: job.datafeedState, + spaces: adJobStatus['anomaly-detector'][job.id] ?? [], + }; + }); - return response.ok({ - body: adJobsWithSpaces, - }); - case 'data-frame-analytics': - const [ - { data_frame_analytics: dfaJobs }, - { data_frame_analytics: dfaJobsStats }, - dfaJobStatus, - ] = await Promise.all([ - mlClient.getDataFrameAnalytics({ - size: 10000, - }), - mlClient.getDataFrameAnalyticsStats({ - size: 10000, - }), - jobsSpaces(), - ]); + return response.ok({ + body: adJobsWithSpaces, + }); + case 'data-frame-analytics': + const [ + { data_frame_analytics: dfaJobs }, + { data_frame_analytics: dfaJobsStats }, + dfaJobStatus, + ] = await Promise.all([ + mlClient.getDataFrameAnalytics({ + size: 10000, + }), + mlClient.getDataFrameAnalyticsStats({ + size: 10000, + }), + jobsSpaces(), + ]); - const dfaStatsMapped = dfaJobsStats.reduce((acc, cur) => { - acc[cur.id] = cur; - return acc; - }, {} as Record); + const dfaStatsMapped = dfaJobsStats.reduce((acc, cur) => { + acc[cur.id] = cur; + return acc; + }, {} as Record); - const dfaJobsWithSpaces: AnalyticsManagementItems[] = dfaJobs.map((j) => { - const id = j.id; - return { - id, - description: j.description ?? '', - source_index: j.source.index as string[], // esclient types are wrong - dest_index: j.dest.index, - job_type: Object.keys(j.analysis)[0] ?? '', - state: dfaStatsMapped[id]?.state ?? '', - spaces: dfaJobStatus['data-frame-analytics'][id] ?? [], - }; - }); - return response.ok({ - body: dfaJobsWithSpaces, - }); + const dfaJobsWithSpaces: AnalyticsManagementItems[] = dfaJobs.map((j) => { + const id = j.id; + return { + id, + description: j.description ?? '', + source_index: j.source.index as string[], // esclient types are wrong + dest_index: j.dest.index, + job_type: Object.keys(j.analysis)[0] ?? '', + state: dfaStatsMapped[id]?.state ?? '', + spaces: dfaJobStatus['data-frame-analytics'][id] ?? [], + }; + }); + return response.ok({ + body: dfaJobsWithSpaces, + }); - case 'trained-model': - const [ - { trained_model_configs: models }, - { trained_model_stats: modelsStats }, - modelSpaces, - ] = await Promise.all([ - mlClient.getTrainedModels(), - mlClient.getTrainedModelsStats(), - trainedModelsSpaces(), - ]); + case 'trained-model': + const [ + { trained_model_configs: models }, + { trained_model_stats: modelsStats }, + modelSpaces, + ] = await Promise.all([ + mlClient.getTrainedModels(), + mlClient.getTrainedModelsStats(), + trainedModelsSpaces(), + ]); - const modelStatsMapped = modelsStats.reduce((acc, cur) => { - acc[cur.model_id] = cur; - return acc; - }, {} as Record); + const modelStatsMapped = modelsStats.reduce((acc, cur) => { + acc[cur.model_id] = cur; + return acc; + }, {} as Record); - const modelsWithSpaces: TrainedModelsManagementItems[] = models.map((m) => { - const id = m.model_id; - return { - id, - description: m.description ?? '', - state: modelStatsMapped[id].deployment_stats?.state ?? '', - type: [ - m.model_type, - ...Object.keys(m.inference_config), - ...(m.tags.includes(BUILT_IN_MODEL_TAG) ? [BUILT_IN_MODEL_TYPE] : []), - ], - spaces: modelSpaces.trainedModels[id] ?? [], - }; - }); - return response.ok({ - body: modelsWithSpaces, - }); - default: - // this should never be hit because of the route's schema checks. - throw Error('Specified listType not supported'); + const modelsWithSpaces: TrainedModelsManagementItems[] = models.map((m) => { + const id = m.model_id; + return { + id, + description: m.description ?? '', + state: modelStatsMapped[id].deployment_stats?.state ?? '', + type: [ + m.model_type, + ...Object.keys(m.inference_config), + ...(m.tags.includes(BUILT_IN_MODEL_TAG) ? [BUILT_IN_MODEL_TYPE] : []), + ], + spaces: modelSpaces.trainedModels[id] ?? [], + }; + }); + return response.ok({ + body: modelsWithSpaces, + }); + default: + // this should never be hit because of the route's schema checks. + throw Error('Specified listType not supported'); + } + } catch (e) { + return response.customError(wrapError(e)); } - } catch (e) { - return response.customError(wrapError(e)); } - } - ) - ); + ) + ); } diff --git a/x-pack/plugins/ml/server/routes/model_management.ts b/x-pack/plugins/ml/server/routes/model_management.ts index a72e515a6dd9d9..853ee6582a7f78 100644 --- a/x-pack/plugins/ml/server/routes/model_management.ts +++ b/x-pack/plugins/ml/server/routes/model_management.ts @@ -13,6 +13,7 @@ */ import { schema } from '@kbn/config-schema'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { RouteInitialization } from '../types'; import { wrapError } from '../client/error_wrapper'; @@ -23,14 +24,14 @@ export function modelManagementRoutes({ router, routeGuard }: RouteInitializatio /** * @apiGroup ModelManagement * - * @api {get} /api/ml/model_management/nodes_overview Get node overview about the models allocation + * @api {get} /internal/ml/model_management/nodes_overview Get node overview about the models allocation * @apiName GetModelManagementNodesOverview * @apiDescription Retrieves the list of ML nodes with memory breakdown and allocated models info */ - router.get( - { - path: '/api/ml/model_management/nodes_overview', - validate: {}, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/model_management/nodes_overview`, + access: 'internal', options: { tags: [ 'access:ml:canViewMlNodes', @@ -39,37 +40,36 @@ export function modelManagementRoutes({ router, routeGuard }: RouteInitializatio 'access:ml:canGetTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { - try { - const memoryUsageService = new MemoryUsageService(mlClient); - const result = await memoryUsageService.getNodesOverview(); - return response.ok({ - body: result, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: {}, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response }) => { + try { + const memoryUsageService = new MemoryUsageService(mlClient); + const result = await memoryUsageService.getNodesOverview(); + return response.ok({ + body: result, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ModelManagement * - * @api {get} /api/ml/model_management/memory_usage Memory usage for jobs and trained models + * @api {get} /internal/ml/model_management/memory_usage Memory usage for jobs and trained models * @apiName GetModelManagementMemoryUsage * @apiDescription Returns the memory usage for jobs and trained models */ - router.get( - { - path: '/api/ml/model_management/memory_usage', - validate: { - query: schema.object({ - type: schema.maybe(itemTypeLiterals), - node: schema.maybe(schema.string()), - showClosedJobs: schema.maybe(schema.boolean()), - }), - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/model_management/memory_usage`, + access: 'internal', options: { tags: [ 'access:ml:canViewMlNodes', @@ -78,21 +78,34 @@ export function modelManagementRoutes({ router, routeGuard }: RouteInitializatio 'access:ml:canGetTrainedModels', ], }, - }, - - routeGuard.fullLicenseAPIGuard(async ({ mlClient, response, request }) => { - try { - const memoryUsageService = new MemoryUsageService(mlClient); - return response.ok({ - body: await memoryUsageService.getMemorySizes( - request.query.type, - request.query.node, - request.query.showClosedJobs - ), - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + query: schema.object({ + type: schema.maybe(itemTypeLiterals), + node: schema.maybe(schema.string()), + showClosedJobs: schema.maybe(schema.boolean()), + }), + }, + }, + }, + + routeGuard.fullLicenseAPIGuard(async ({ mlClient, response, request }) => { + try { + const memoryUsageService = new MemoryUsageService(mlClient); + return response.ok({ + body: await memoryUsageService.getMemorySizes( + request.query.type, + request.query.node, + request.query.showClosedJobs + ), + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/modules.ts b/x-pack/plugins/ml/server/routes/modules.ts index 757012ba140412..9ee469220f9869 100644 --- a/x-pack/plugins/ml/server/routes/modules.ts +++ b/x-pack/plugins/ml/server/routes/modules.ts @@ -13,6 +13,7 @@ import type { SavedObjectsClientContract, } from '@kbn/core/server'; import type { DataViewsService } from '@kbn/data-views-plugin/common'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import type { DatafeedOverride, JobOverride } from '../../common/types/modules'; import { wrapError } from '../client/error_wrapper'; import { dataRecognizerFactory } from '../models/data_recognizer'; @@ -143,7 +144,7 @@ export function dataRecognizer({ router, routeGuard }: RouteInitialization) { /** * @apiGroup Modules * - * @api {get} /api/ml/modules/recognize/:indexPatternTitle Recognize index pattern + * @api {get} /internal/ml/modules/recognize/:indexPatternTitle Recognize index pattern * @apiName RecognizeIndex * @apiDescription By supplying an index pattern, discover if any of the modules are a match for data in that index. * @apiSchema (params) modulesIndexPatternTitleSchema @@ -168,52 +169,59 @@ export function dataRecognizer({ router, routeGuard }: RouteInitialization) { * } * }] */ - router.get( - { - path: '/api/ml/modules/recognize/{indexPatternTitle}', - validate: { - params: modulesIndexPatternTitleSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/modules/recognize/{indexPatternTitle}`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ - client, - mlClient, - request, - response, - context, - mlSavedObjectService, - getDataViewsService, - }) => { - try { - const { indexPatternTitle } = request.params; - const soClient = (await context.core).savedObjects.client; - const dataViewService = await getDataViewsService(); - const results = await recognize( - client, - mlClient, - soClient, - dataViewService, - mlSavedObjectService, - request, - indexPatternTitle - ); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: modulesIndexPatternTitleSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ + client, + mlClient, + request, + response, + context, + mlSavedObjectService, + getDataViewsService, + }) => { + try { + const { indexPatternTitle } = request.params; + const soClient = (await context.core).savedObjects.client; + const dataViewService = await getDataViewsService(); + const results = await recognize( + client, + mlClient, + soClient, + dataViewService, + mlSavedObjectService, + request, + indexPatternTitle + ); - return response.ok({ body: results }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ body: results }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup Modules * - * @api {get} /api/ml/modules/get_module/:moduleId Get module + * @api {get} /internal/ml/modules/get_module/:moduleId Get module * @apiName GetModule * @apiDescription Retrieve a whole ML module, containing jobs, datafeeds and saved objects. If * no module ID is supplied, returns all modules. @@ -318,57 +326,64 @@ export function dataRecognizer({ router, routeGuard }: RouteInitialization) { * "kibana":{} * } */ - router.get( - { - path: '/api/ml/modules/get_module/{moduleId?}', - validate: { - params: optionalModuleIdParamSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/modules/get_module/{moduleId?}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ - client, - mlClient, - request, - response, - context, - mlSavedObjectService, - getDataViewsService, - }) => { - try { - let { moduleId } = request.params; - if (moduleId === '') { - // if the endpoint is called with a trailing / - // the moduleId will be an empty string. - moduleId = undefined; - } - const soClient = (await context.core).savedObjects.client; - const dataViewService = await getDataViewsService(); - const results = await getModule( - client, - mlClient, - soClient, - dataViewService, - mlSavedObjectService, - request, - moduleId - ); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: optionalModuleIdParamSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ + client, + mlClient, + request, + response, + context, + mlSavedObjectService, + getDataViewsService, + }) => { + try { + let { moduleId } = request.params; + if (moduleId === '') { + // if the endpoint is called with a trailing / + // the moduleId will be an empty string. + moduleId = undefined; + } + const soClient = (await context.core).savedObjects.client; + const dataViewService = await getDataViewsService(); + const results = await getModule( + client, + mlClient, + soClient, + dataViewService, + mlSavedObjectService, + request, + moduleId + ); - return response.ok({ body: results }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ body: results }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup Modules * - * @api {post} /api/ml/modules/setup/:moduleId Set up module + * @api {post} /internal/ml/modules/setup/:moduleId Set up module * @apiName SetupModule * @apiDescription Runs the module setup process. * This creates jobs, datafeeds and kibana saved objects. It allows for customization of the module, @@ -505,81 +520,88 @@ export function dataRecognizer({ router, routeGuard }: RouteInitialization) { * }] * } */ - router.post( - { - path: '/api/ml/modules/setup/{moduleId}', - validate: { - params: moduleIdParamSchema, - body: setupModuleBodySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/modules/setup/{moduleId}`, + access: 'internal', options: { tags: ['access:ml:canCreateJob'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ - client, - mlClient, - request, - response, - context, - mlSavedObjectService, - getDataViewsService, - }) => { - try { - const { moduleId } = request.params; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: moduleIdParamSchema, + body: setupModuleBodySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ + client, + mlClient, + request, + response, + context, + mlSavedObjectService, + getDataViewsService, + }) => { + try { + const { moduleId } = request.params; - const { - prefix, - groups, - indexPatternName, - query, - useDedicatedIndex, - startDatafeed, - start, - end, - jobOverrides, - datafeedOverrides, - estimateModelMemory, - applyToAllSpaces, - } = request.body as TypeOf; - const soClient = (await context.core).savedObjects.client; - const dataViewService = await getDataViewsService(); + const { + prefix, + groups, + indexPatternName, + query, + useDedicatedIndex, + startDatafeed, + start, + end, + jobOverrides, + datafeedOverrides, + estimateModelMemory, + applyToAllSpaces, + } = request.body as TypeOf; + const soClient = (await context.core).savedObjects.client; + const dataViewService = await getDataViewsService(); - const result = await setup( - client, - mlClient, - soClient, - dataViewService, - mlSavedObjectService, - request, - moduleId, - prefix, - groups, - indexPatternName, - query, - useDedicatedIndex, - startDatafeed, - start, - end, - jobOverrides, - datafeedOverrides, - estimateModelMemory, - applyToAllSpaces - ); + const result = await setup( + client, + mlClient, + soClient, + dataViewService, + mlSavedObjectService, + request, + moduleId, + prefix, + groups, + indexPatternName, + query, + useDedicatedIndex, + startDatafeed, + start, + end, + jobOverrides, + datafeedOverrides, + estimateModelMemory, + applyToAllSpaces + ); - return response.ok({ body: result }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ body: result }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); /** * @apiGroup Modules * - * @api {get} /api/ml/modules/jobs_exist/:moduleId Check if module jobs exist + * @api {get} /internal/ml/modules/jobs_exist/:moduleId Check if module jobs exist * @apiName CheckExistingModuleJobs * @apiDescription Check whether the jobs in the module with the specified ID exist in the * current list of jobs. The check runs a test to see if any of the jobs in existence @@ -628,45 +650,52 @@ export function dataRecognizer({ router, routeGuard }: RouteInitialization) { * ] * } */ - router.get( - { - path: '/api/ml/modules/jobs_exist/{moduleId}', - validate: { - params: moduleIdParamSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/modules/jobs_exist/{moduleId}`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard( - async ({ - client, - mlClient, - request, - response, - context, - mlSavedObjectService, - getDataViewsService, - }) => { - try { - const { moduleId } = request.params; - const soClient = (await context.core).savedObjects.client; - const dataViewService = await getDataViewsService(); - const result = await dataRecognizerJobsExist( - client, - mlClient, - soClient, - dataViewService, - mlSavedObjectService, - request, - moduleId - ); + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: moduleIdParamSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ + client, + mlClient, + request, + response, + context, + mlSavedObjectService, + getDataViewsService, + }) => { + try { + const { moduleId } = request.params; + const soClient = (await context.core).savedObjects.client; + const dataViewService = await getDataViewsService(); + const result = await dataRecognizerJobsExist( + client, + mlClient, + soClient, + dataViewService, + mlSavedObjectService, + request, + moduleId + ); - return response.ok({ body: result }); - } catch (e) { - return response.customError(wrapError(e)); + return response.ok({ body: result }); + } catch (e) { + return response.customError(wrapError(e)); + } } - } - ) - ); + ) + ); } diff --git a/x-pack/plugins/ml/server/routes/notifications.ts b/x-pack/plugins/ml/server/routes/notifications.ts index 5b267e2d390791..8e67136e83ddda 100644 --- a/x-pack/plugins/ml/server/routes/notifications.ts +++ b/x-pack/plugins/ml/server/routes/notifications.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { NotificationsService } from '../models/notifications_service'; import { getNotificationsCountQuerySchema, @@ -17,16 +18,14 @@ export function notificationsRoutes({ router, routeGuard }: RouteInitialization) /** * @apiGroup Notifications * - * @api {get} /api/ml/notifications Get notifications + * @api {get} /internal/ml/notifications Get notifications * @apiName GetNotifications * @apiDescription Retrieves notifications based on provided criteria. */ - router.get( - { - path: '/api/ml/notifications', - validate: { - query: getNotificationsQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/notifications`, + access: 'internal', options: { tags: [ 'access:ml:canGetJobs', @@ -34,35 +33,44 @@ export function notificationsRoutes({ router, routeGuard }: RouteInitialization) 'access:ml:canGetTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response, mlSavedObjectService }) => { - try { - const notificationsService = new NotificationsService(client, mlSavedObjectService); + }) + .addVersion( + { + version: '1', + validate: { + request: { + query: getNotificationsQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, request, response, mlSavedObjectService }) => { + try { + const notificationsService = new NotificationsService(client, mlSavedObjectService); - const results = await notificationsService.searchMessages(request.query); + const results = await notificationsService.searchMessages(request.query); - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); /** * @apiGroup Notifications * - * @api {get} /api/ml/notifications/count Get notification counts + * @api {get} /internal/ml/notifications/count Get notification counts * @apiName GetNotificationCounts * @apiDescription Counts notifications by level. */ - router.get( - { - path: '/api/ml/notifications/count', - validate: { - query: getNotificationsCountQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/notifications/count`, + access: 'internal', options: { tags: [ 'access:ml:canGetJobs', @@ -70,19 +78,30 @@ export function notificationsRoutes({ router, routeGuard }: RouteInitialization) 'access:ml:canGetTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlSavedObjectService, request, response }) => { - try { - const notificationsService = new NotificationsService(client, mlSavedObjectService); + }) + .addVersion( + { + version: '1', + validate: { + request: { + query: getNotificationsCountQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, mlSavedObjectService, request, response }) => { + try { + const notificationsService = new NotificationsService(client, mlSavedObjectService); - const results = await notificationsService.countMessages(request.query); + const results = await notificationsService.countMessages(request.query); - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); } diff --git a/x-pack/plugins/ml/server/routes/results_service.ts b/x-pack/plugins/ml/server/routes/results_service.ts index 3af4a570ce0736..b2f26de96cf302 100644 --- a/x-pack/plugins/ml/server/routes/results_service.ts +++ b/x-pack/plugins/ml/server/routes/results_service.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { @@ -108,362 +109,440 @@ export function resultsServiceRoutes({ router, routeGuard }: RouteInitialization /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/anomalies_table_data Get anomalies records for table display + * @api {post} /internal/ml/results/anomalies_table_data Get anomalies records for table display * @apiName GetAnomaliesTableData * @apiDescription Retrieves anomaly records for an anomaly detection job and formats them for anomalies table display. * * @apiSchema (body) anomaliesTableDataSchema */ - router.post( - { - path: '/api/ml/results/anomalies_table_data', - validate: { - body: anomaliesTableDataSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/anomalies_table_data`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getAnomaliesTableData(mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: anomaliesTableDataSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getAnomaliesTableData(mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/category_definition Get category definition + * @api {post} /internal/ml/results/category_definition Get category definition * @apiName GetCategoryDefinition * @apiDescription Returns the definition of the category with the specified ID and job ID * * @apiSchema (body) categoryDefinitionSchema */ - router.post( - { - path: '/api/ml/results/category_definition', - validate: { - body: categoryDefinitionSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/category_definition`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getCategoryDefinition(mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: categoryDefinitionSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getCategoryDefinition(mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/max_anomaly_score Get the maximum anomaly_score + * @api {post} /internal/ml/results/max_anomaly_score Get the maximum anomaly_score * @apiName GetMaxAnomalyScore * @apiDescription Returns the maximum anomaly score of the bucket results for the request job ID(s) and time range * * @apiSchema (body) maxAnomalyScoreSchema */ - router.post( - { - path: '/api/ml/results/max_anomaly_score', - validate: { - body: maxAnomalyScoreSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/max_anomaly_score`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getMaxAnomalyScore(mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: maxAnomalyScoreSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getMaxAnomalyScore(mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/category_examples Get category examples + * @api {post} /internal/ml/results/category_examples Get category examples * @apiName GetCategoryExamples * @apiDescription Returns examples for the categories with the specified IDs from the job with the supplied ID * * @apiSchema (body) categoryExamplesSchema */ - router.post( - { - path: '/api/ml/results/category_examples', - validate: { - body: categoryExamplesSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/category_examples`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getCategoryExamples(mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: categoryExamplesSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getCategoryExamples(mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/partition_fields_values Returns partition fields values + * @api {post} /internal/ml/results/partition_fields_values Returns partition fields values * @apiName GetPartitionFieldsValues * @apiDescription Returns the partition fields with values that match the provided criteria for the specified job ID. * * @apiSchema (body) partitionFieldValuesSchema */ - router.post( - { - path: '/api/ml/results/partition_fields_values', - validate: { - body: partitionFieldValuesSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/partition_fields_values`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getPartitionFieldsValues(mlClient, request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: partitionFieldValuesSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getPartitionFieldsValues(mlClient, request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/anomaly_search Run a search on the anomaly results index + * @api {post} /internal/ml/results/anomaly_search Run a search on the anomaly results index * @apiName AnomalySearch * @apiDescription Runs the supplied query against the anomaly results index for the specified job IDs. * @apiSchema (body) anomalySearchSchema */ - router.post( - { - path: '/api/ml/results/anomaly_search', - validate: { - body: anomalySearchSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_search`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { jobIds, query } = request.body; - const body = await mlClient.anomalySearch(query, jobIds); - return response.ok({ - body, - }); - } catch (error) { - return response.customError(wrapError(error)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: anomalySearchSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { jobIds, query } = request.body; + const body = await mlClient.anomalySearch(query, jobIds); + return response.ok({ + body, + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {get} /api/ml/results/:jobId/categorizer_stats Return categorizer statistics + * @api {get} /internal/ml/results/:jobId/categorizer_stats Return categorizer statistics * @apiName GetCategorizerStats * @apiDescription Returns the categorizer stats for the specified job ID * @apiSchema (params) jobIdSchema * @apiSchema (query) getCategorizerStatsSchema */ - router.get( - { - path: '/api/ml/results/{jobId}/categorizer_stats', - validate: { - params: jobIdSchema, - query: getCategorizerStatsSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/results/{jobId}/categorizer_stats`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getCategorizerStats(mlClient, request.params, request.query); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: jobIdSchema, + query: getCategorizerStatsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getCategorizerStats(mlClient, request.params, request.query); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/category_stopped_partitions Get partitions that have stopped being categorized + * @api {post} /internal/ml/results/category_stopped_partitions Get partitions that have stopped being categorized * @apiName GetCategoryStoppedPartitions * @apiDescription Returns information on the partitions that have stopped being categorized due to the categorization status changing from ok to warn. Can return either the list of stopped partitions for each job, or just the list of job IDs. * @apiSchema (body) getCategorizerStoppedPartitionsSchema */ - router.post( - { - path: '/api/ml/results/category_stopped_partitions', - validate: { - body: getCategorizerStoppedPartitionsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/category_stopped_partitions`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const resp = await getCategoryStoppedPartitions(mlClient, request.body); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: getCategorizerStoppedPartitionsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const resp = await getCategoryStoppedPartitions(mlClient, request.body); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/datafeed_results_chart Get datafeed results chart data + * @api {post} /internal/ml/results/datafeed_results_chart Get datafeed results chart data * @apiName GetDatafeedResultsChartData * @apiDescription Returns datafeed results chart data * * @apiSchema (body) getDatafeedResultsChartDataSchema */ - router.post( - { - path: '/api/ml/results/datafeed_results_chart', - validate: { - body: getDatafeedResultsChartDataSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/datafeed_results_chart`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { getDatafeedResultsChartData } = resultsServiceProvider(mlClient, client); - const resp = await getDatafeedResultsChartData(request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: getDatafeedResultsChartDataSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { getDatafeedResultsChartData } = resultsServiceProvider(mlClient, client); + const resp = await getDatafeedResultsChartData(request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/anomaly_charts Get data for anomaly charts + * @api {post} /internal/ml/results/anomaly_charts Get data for anomaly charts * @apiName GetAnomalyChartsData * @apiDescription Returns anomaly charts data * * @apiSchema (body) getAnomalyChartsSchema */ - router.post( - { - path: '/api/ml/results/anomaly_charts', - validate: { - body: getAnomalyChartsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_charts`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { getAnomalyChartsData } = resultsServiceProvider(mlClient, client); - const resp = await getAnomalyChartsData(request.body); - - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: getAnomalyChartsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { getAnomalyChartsData } = resultsServiceProvider(mlClient, client); + const resp = await getAnomalyChartsData(request.body); + + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup ResultsService * - * @api {post} /api/ml/results/anomaly_records Get anomaly records for criteria + * @api {post} /internal/ml/results/anomaly_records Get anomaly records for criteria * @apiName GetAnomalyRecords * @apiDescription Returns anomaly records * * @apiSchema (body) getAnomalyRecordsSchema */ - router.post( - { - path: '/api/ml/results/anomaly_records', - validate: { - body: getAnomalyRecordsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/results/anomaly_records`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { getRecordsForCriteria } = resultsServiceProvider(mlClient, client); + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: getAnomalyRecordsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { + try { + const { getRecordsForCriteria } = resultsServiceProvider(mlClient, client); - const { jobIds, criteriaFields, earliestMs, latestMs, threshold, interval } = request.body; + const { jobIds, criteriaFields, earliestMs, latestMs, threshold, interval } = + request.body; - const resp = await getRecordsForCriteria( - jobIds, - criteriaFields, - threshold, - earliestMs, - latestMs, - interval - ); + const resp = await getRecordsForCriteria( + jobIds, + criteriaFields, + threshold, + earliestMs, + latestMs, + interval + ); - return response.ok({ - body: resp, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body: resp, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/saved_objects.ts b/x-pack/plugins/ml/server/routes/saved_objects.ts index af3ac95315660f..4c9bc7a405efc9 100644 --- a/x-pack/plugins/ml/server/routes/saved_objects.ts +++ b/x-pack/plugins/ml/server/routes/saved_objects.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { ML_EXTERNAL_BASE_PATH, ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization, SavedObjectsRouteDeps } from '../types'; import { checksFactory, syncSavedObjectsFactory } from '../saved_objects'; @@ -30,32 +31,37 @@ export function savedObjectsRoutes( /** * @apiGroup MLSavedObjects * - * @api {get} /api/ml/saved_objects/status Get job and trained model saved object status + * @api {get} /internal/ml/saved_objects/status Get job and trained model saved object status * @apiName SavedObjectsStatus * @apiDescription Lists all jobs, trained models and saved objects to view the relationship status between them * */ - router.get( - { - path: '/api/ml/saved_objects/status', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/status`, + access: 'internal', options: { tags: ['access:ml:canGetJobs', 'access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, response, mlSavedObjectService }) => { - try { - const { checkStatus } = checksFactory(client, mlSavedObjectService); - const status = await checkStatus(); - - return response.ok({ - body: status, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, response, mlSavedObjectService }) => { + try { + const { checkStatus } = checksFactory(client, mlSavedObjectService); + const status = await checkStatus(); + + return response.ok({ + body: status, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup MLSavedObjects @@ -68,12 +74,10 @@ export function savedObjectsRoutes( * removes datafeed IDs for datafeeds which no longer exist. * */ - router.get( - { - path: '/api/ml/saved_objects/sync', - validate: { - query: syncJobObjects, - }, + router.versioned + .get({ + path: `${ML_EXTERNAL_BASE_PATH}/saved_objects/sync`, + access: 'public', options: { tags: [ 'access:ml:canCreateJob', @@ -81,36 +85,45 @@ export function savedObjectsRoutes( 'access:ml:canCreateTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response, mlSavedObjectService }) => { - try { - const { simulate } = request.query; - const { syncSavedObjects } = syncSavedObjectsFactory(client, mlSavedObjectService); - const savedObjects = await syncSavedObjects(simulate); - - return response.ok({ - body: savedObjects, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '2023-05-15', + validate: { + request: { + query: syncJobObjects, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, request, response, mlSavedObjectService }) => { + try { + const { simulate } = request.query; + const { syncSavedObjects } = syncSavedObjectsFactory(client, mlSavedObjectService); + const savedObjects = await syncSavedObjects(simulate); + + return response.ok({ + body: savedObjects, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); /** * @apiGroup MLSavedObjects * - * @api {get} /api/ml/saved_objects/initialize Create saved objects for all job and trained models + * @api {get} /internal/ml/saved_objects/initialize Create saved objects for all job and trained models * @apiName InitializeMLSavedObjects * @apiDescription Create saved objects for jobs and trained models which are missing them. * */ - router.get( - { - path: '/api/ml/saved_objects/initialize', - validate: { - query: syncJobObjects, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/initialize`, + access: 'internal', options: { tags: [ 'access:ml:canCreateJob', @@ -118,36 +131,45 @@ export function savedObjectsRoutes( 'access:ml:canCreateTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response, mlSavedObjectService }) => { - try { - const { simulate } = request.query; - const { initSavedObjects } = syncSavedObjectsFactory(client, mlSavedObjectService); - const savedObjects = await initSavedObjects(simulate); - - return response.ok({ - body: savedObjects, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + query: syncJobObjects, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, request, response, mlSavedObjectService }) => { + try { + const { simulate } = request.query; + const { initSavedObjects } = syncSavedObjectsFactory(client, mlSavedObjectService); + const savedObjects = await initSavedObjects(simulate); + + return response.ok({ + body: savedObjects, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); /** * @apiGroup MLSavedObjects * - * @api {get} /api/ml/saved_objects/sync_needed Check whether job and trained model saved objects need synchronizing + * @api {get} /internal/ml/saved_objects/sync_needed Check whether job and trained model saved objects need synchronizing * @apiName SyncCheck * @apiDescription Check whether job and trained model saved objects need synchronizing. * */ - router.post( - { - path: '/api/ml/saved_objects/sync_check', - validate: { - body: syncCheckSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/sync_check`, + access: 'internal', options: { tags: [ 'access:ml:canGetJobs', @@ -155,137 +177,181 @@ export function savedObjectsRoutes( 'access:ml:canGetTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response, mlSavedObjectService }) => { - try { - const { mlSavedObjectType } = request.body; - const { isSyncNeeded } = syncSavedObjectsFactory(client, mlSavedObjectService); - const result = await isSyncNeeded(mlSavedObjectType as MlSavedObjectType); - - return response.ok({ - body: { result }, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: syncCheckSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ client, request, response, mlSavedObjectService }) => { + try { + const { mlSavedObjectType } = request.body; + const { isSyncNeeded } = syncSavedObjectsFactory(client, mlSavedObjectService); + const result = await isSyncNeeded(mlSavedObjectType as MlSavedObjectType); + + return response.ok({ + body: { result }, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); /** * @apiGroup MLSavedObjects * - * @api {post} /api/ml/saved_objects/update_jobs_spaces Update what spaces jobs are assigned to + * @api {post} /internal/ml/saved_objects/update_jobs_spaces Update what spaces jobs are assigned to * @apiName UpdateJobsSpaces * @apiDescription Update a list of jobs to add and/or remove them from given spaces. * * @apiSchema (body) updateJobsSpaces */ - router.post( - { - path: '/api/ml/saved_objects/update_jobs_spaces', - validate: { - body: updateJobsSpaces, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/update_jobs_spaces`, + access: 'internal', options: { tags: ['access:ml:canCreateJob', 'access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { - try { - const { jobType, jobIds, spacesToAdd, spacesToRemove } = request.body; + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: updateJobsSpaces, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { + try { + const { jobType, jobIds, spacesToAdd, spacesToRemove } = request.body; - const body = await mlSavedObjectService.updateJobsSpaces( - jobType, - jobIds, - spacesToAdd, - spacesToRemove - ); + const body = await mlSavedObjectService.updateJobsSpaces( + jobType, + jobIds, + spacesToAdd, + spacesToRemove + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup MLSavedObjects * - * @api {post} /api/ml/saved_objects/update_trained_models_spaces Update what spaces trained models are assigned to + * @api {post} /internal/ml/saved_objects/update_trained_models_spaces Update what spaces trained models are assigned to * @apiName UpdateTrainedModelsSpaces * @apiDescription Update a list of trained models to add and/or remove them from given spaces. * * @apiSchema (body) updateTrainedModelsSpaces */ - router.post( - { - path: '/api/ml/saved_objects/update_trained_models_spaces', - validate: { - body: updateTrainedModelsSpaces, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/update_trained_models_spaces`, + access: 'internal', options: { tags: ['access:ml:canCreateTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { - try { - const { modelIds, spacesToAdd, spacesToRemove } = request.body; + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: updateTrainedModelsSpaces, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { + try { + const { modelIds, spacesToAdd, spacesToRemove } = request.body; - const body = await mlSavedObjectService.updateTrainedModelsSpaces( - modelIds, - spacesToAdd, - spacesToRemove - ); + const body = await mlSavedObjectService.updateTrainedModelsSpaces( + modelIds, + spacesToAdd, + spacesToRemove + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup MLSavedObjects * - * @api {post} /api/ml/saved_objects/remove_item_from_current_space Remove jobs or trained models from the current space + * @api {post} /internal/ml/saved_objects/remove_item_from_current_space Remove jobs or trained models from the current space * @apiName RemoveMLSpaceAwareItemsFromCurrentSpace * @apiDescription Remove a list of jobs or trained models from the current space. * * @apiSchema (body) itemsAndCurrentSpace */ - router.post( - { - path: '/api/ml/saved_objects/remove_item_from_current_space', - validate: { - body: itemsAndCurrentSpace, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/remove_item_from_current_space`, + access: 'internal', options: { tags: ['access:ml:canCreateJob', 'access:ml:canCreateDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { - try { - const { mlSavedObjectType, ids } = request.body; - const { getCurrentSpaceId } = spacesUtilsProvider(getSpaces, request); + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: itemsAndCurrentSpace, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService }) => { + try { + const { mlSavedObjectType, ids } = request.body; + const { getCurrentSpaceId } = spacesUtilsProvider(getSpaces, request); - const currentSpaceId = await getCurrentSpaceId(); - if (currentSpaceId === null) { - return response.ok({ - body: ids.map((id) => ({ - [id]: { - success: false, - error: 'Cannot remove current space. Spaces plugin is disabled.', - }, - })), - }); - } + const currentSpaceId = await getCurrentSpaceId(); + if (currentSpaceId === null) { + return response.ok({ + body: ids.map((id) => ({ + [id]: { + success: false, + error: 'Cannot remove current space. Spaces plugin is disabled.', + }, + })), + }); + } - if (mlSavedObjectType === 'trained-model') { - const body = await mlSavedObjectService.updateTrainedModelsSpaces( + if (mlSavedObjectType === 'trained-model') { + const body = await mlSavedObjectService.updateTrainedModelsSpaces( + ids, + [], // spacesToAdd + [currentSpaceId] // spacesToRemove + ); + + return response.ok({ + body, + }); + } + + const body = await mlSavedObjectService.updateJobsSpaces( + mlSavedObjectType, ids, [], // spacesToAdd [currentSpaceId] // spacesToRemove @@ -294,88 +360,86 @@ export function savedObjectsRoutes( return response.ok({ body, }); + } catch (e) { + return response.customError(wrapError(e)); } - - const body = await mlSavedObjectService.updateJobsSpaces( - mlSavedObjectType, - ids, - [], // spacesToAdd - [currentSpaceId] // spacesToRemove - ); - - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + }) + ); /** * @apiGroup MLSavedObjects * - * @api {get} /api/ml/saved_objects/jobs_spaces Get all jobs and their spaces + * @api {get} /internal/ml/saved_objects/jobs_spaces Get all jobs and their spaces * @apiName JobsSpaces * @apiDescription List all jobs and their spaces. * */ - router.get( - { - path: '/api/ml/saved_objects/jobs_spaces', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/jobs_spaces`, + access: 'internal', options: { tags: ['access:ml:canGetJobs', 'access:ml:canGetDataFrameAnalytics'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ response, mlSavedObjectService, client }) => { - try { - const { jobsSpaces } = checksFactory(client, mlSavedObjectService); - const jobsStatus = await jobsSpaces(); - - return response.ok({ - body: jobsStatus, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ response, mlSavedObjectService, client }) => { + try { + const { jobsSpaces } = checksFactory(client, mlSavedObjectService); + const jobsStatus = await jobsSpaces(); + + return response.ok({ + body: jobsStatus, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup MLSavedObjects * - * @api {get} /api/ml/saved_objects/trained_models_spaces Get all trained models and their spaces + * @api {get} /internal/ml/saved_objects/trained_models_spaces Get all trained models and their spaces * @apiName TrainedModelsSpaces * @apiDescription List all trained models and their spaces. * */ - router.get( - { - path: '/api/ml/saved_objects/trained_models_spaces', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/trained_models_spaces`, + access: 'internal', options: { tags: ['access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ response, mlSavedObjectService, client }) => { - try { - const { trainedModelsSpaces } = checksFactory(client, mlSavedObjectService); - const modelStatus = await trainedModelsSpaces(); - - return response.ok({ - body: modelStatus, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ response, mlSavedObjectService, client }) => { + try { + const { trainedModelsSpaces } = checksFactory(client, mlSavedObjectService); + const modelStatus = await trainedModelsSpaces(); + + return response.ok({ + body: modelStatus, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup MLSavedObjects * - * @api {post} /api/ml/saved_objects/can_delete_ml_space_aware_item Check whether user can delete a job or trained model + * @api {post} /internal/ml/saved_objects/can_delete_ml_space_aware_item Check whether user can delete a job or trained model * @apiName CanDeleteMLSpaceAwareItems * @apiDescription Check the user's ability to delete jobs or trained models. Returns whether they are able * to fully delete the job or trained model and whether they are able to remove it from @@ -394,13 +458,10 @@ export function savedObjectsRoutes( * } * */ - router.post( - { - path: '/api/ml/saved_objects/can_delete_ml_space_aware_item/{jobType}', - validate: { - params: itemTypeSchema, - body: canDeleteMLSpaceAwareItemsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/saved_objects/can_delete_ml_space_aware_item/{jobType}`, + access: 'internal', options: { tags: [ 'access:ml:canGetJobs', @@ -408,27 +469,39 @@ export function savedObjectsRoutes( 'access:ml:canGetTrainedModels', ], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ request, response, mlSavedObjectService, client }) => { - try { - const { jobType } = request.params; - const { ids } = request.body; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: itemTypeSchema, + body: canDeleteMLSpaceAwareItemsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard( + async ({ request, response, mlSavedObjectService, client }) => { + try { + const { jobType } = request.params; + const { ids } = request.body; - const { canDeleteMLSpaceAwareItems } = checksFactory(client, mlSavedObjectService); - const body = await canDeleteMLSpaceAwareItems( - request, - jobType, - ids, - getSpaces !== undefined, - resolveMlCapabilities - ); + const { canDeleteMLSpaceAwareItems } = checksFactory(client, mlSavedObjectService); + const body = await canDeleteMLSpaceAwareItems( + request, + jobType, + ids, + getSpaces !== undefined, + resolveMlCapabilities + ); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + } + ) + ); } diff --git a/x-pack/plugins/ml/server/routes/system.ts b/x-pack/plugins/ml/server/routes/system.ts index a24810753bb115..812640fbcd3680 100644 --- a/x-pack/plugins/ml/server/routes/system.ts +++ b/x-pack/plugins/ml/server/routes/system.ts @@ -7,6 +7,7 @@ import { schema } from '@kbn/config-schema'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import { mlLog } from '../lib/log'; import { capabilitiesProvider } from '../lib/capabilities'; @@ -24,229 +25,264 @@ export function systemRoutes( /** * @apiGroup SystemRoutes * - * @api {post} /api/ml/_has_privileges Check privileges + * @api {post} /internal/ml/_has_privileges Check privileges * @apiName HasPrivileges * @apiDescription Checks if the user has required privileges */ - router.post( - { - path: '/api/ml/_has_privileges', - validate: { - body: schema.maybe(schema.any()), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/_has_privileges`, + access: 'internal', options: { tags: ['access:ml:canGetMlInfo'], }, - }, - routeGuard.basicLicenseAPIGuard(async ({ mlClient, client, request, response }) => { - try { - const { asCurrentUser } = client; - let upgradeInProgress = false; + }) + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.maybe(schema.any()), + }, + }, + }, + routeGuard.basicLicenseAPIGuard(async ({ mlClient, client, request, response }) => { try { - const body = await mlClient.info(); - // if ml indices are currently being migrated, upgrade_mode will be set to true - // pass this back with the privileges to allow for the disabling of UI controls. - upgradeInProgress = body.upgrade_mode === true; - } catch (error) { - // if the ml.info check fails, it could be due to the user having insufficient privileges - // most likely they do not have the ml_user role and therefore will be blocked from using - // ML at all. However, we need to catch this error so the privilege check doesn't fail. - if (error.status === 403) { - mlLog.info( - 'Unable to determine whether upgrade is being performed due to insufficient user privileges' - ); + const { asCurrentUser } = client; + let upgradeInProgress = false; + try { + const body = await mlClient.info(); + // if ml indices are currently being migrated, upgrade_mode will be set to true + // pass this back with the privileges to allow for the disabling of UI controls. + upgradeInProgress = body.upgrade_mode === true; + } catch (error) { + // if the ml.info check fails, it could be due to the user having insufficient privileges + // most likely they do not have the ml_user role and therefore will be blocked from using + // ML at all. However, we need to catch this error so the privilege check doesn't fail. + if (error.status === 403) { + mlLog.info( + 'Unable to determine whether upgrade is being performed due to insufficient user privileges' + ); + } else { + mlLog.warn('Unable to determine whether upgrade is being performed'); + } + } + + if (mlLicense.isSecurityEnabled() === false) { + // if xpack.security.enabled has been explicitly set to false + // return that security is disabled and don't call the privilegeCheck endpoint + return response.ok({ + body: { + securityDisabled: true, + upgradeInProgress, + }, + }); } else { - mlLog.warn('Unable to determine whether upgrade is being performed'); + const body = await asCurrentUser.security.hasPrivileges({ body: request.body }); + return response.ok({ + body: { + ...body, + upgradeInProgress, + }, + }); } + } catch (error) { + return response.customError(wrapError(error)); } - - if (mlLicense.isSecurityEnabled() === false) { - // if xpack.security.enabled has been explicitly set to false - // return that security is disabled and don't call the privilegeCheck endpoint - return response.ok({ - body: { - securityDisabled: true, - upgradeInProgress, - }, - }); - } else { - const body = await asCurrentUser.security.hasPrivileges({ body: request.body }); - return response.ok({ - body: { - ...body, - upgradeInProgress, - }, - }); - } - } catch (error) { - return response.customError(wrapError(error)); - } - }) - ); + }) + ); /** * @apiGroup SystemRoutes * - * @api {get} /api/ml/ml_capabilities Check ML capabilities + * @api {get} /internal/ml/ml_capabilities Check ML capabilities * @apiName MlCapabilitiesResponse * @apiDescription Checks ML capabilities */ - router.get( - { - path: '/api/ml/ml_capabilities', - validate: false, - }, - routeGuard.basicLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { isMlEnabledInSpace } = spacesUtilsProvider(getSpaces, request); + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/ml_capabilities`, + access: 'internal', + }) + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.basicLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { isMlEnabledInSpace } = spacesUtilsProvider(getSpaces, request); - const mlCapabilities = await resolveMlCapabilities(request); - if (mlCapabilities === null) { - return response.customError(wrapError(new Error('resolveMlCapabilities is not defined'))); - } + const mlCapabilities = await resolveMlCapabilities(request); + if (mlCapabilities === null) { + return response.customError( + wrapError(new Error('resolveMlCapabilities is not defined')) + ); + } - const { getCapabilities } = capabilitiesProvider( - mlClient, - mlCapabilities, - mlLicense, - isMlEnabledInSpace - ); - return response.ok({ - body: await getCapabilities(), - }); - } catch (error) { - return response.customError(wrapError(error)); - } - }) - ); + const { getCapabilities } = capabilitiesProvider( + mlClient, + mlCapabilities, + mlLicense, + isMlEnabledInSpace + ); + return response.ok({ + body: await getCapabilities(), + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); /** * @apiGroup SystemRoutes * - * @api {get} /api/ml/ml_node_count Get the amount of ML nodes + * @api {get} /internal/ml/ml_node_count Get the amount of ML nodes * @apiName MlNodeCount * @apiDescription Returns the amount of ML nodes. */ - router.get( - { - path: '/api/ml/ml_node_count', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/ml_node_count`, + access: 'internal', options: { tags: ['access:ml:canGetJobs', 'access:ml:canGetDatafeeds'], }, - }, - - routeGuard.basicLicenseAPIGuard(async ({ client, response }) => { - try { - return response.ok({ - body: await getMlNodeCount(client), - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.basicLicenseAPIGuard(async ({ client, response }) => { + try { + return response.ok({ + body: await getMlNodeCount(client), + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup SystemRoutes * - * @api {get} /api/ml/info Get ML info + * @api {get} /internal/ml/info Get ML info * @apiName MlInfo * @apiDescription Returns defaults and limits used by machine learning. */ - router.get( - { - path: '/api/ml/info', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/info`, + access: 'internal', options: { tags: ['access:ml:canGetMlInfo'], }, - }, - routeGuard.basicLicenseAPIGuard(async ({ mlClient, response }) => { - try { - const body = await mlClient.info(); - const cloudId = cloud?.cloudId; - const isCloudTrial = cloud?.trialEndDate && Date.now() < cloud.trialEndDate.getTime(); - - return response.ok({ - body: { ...body, cloudId, isCloudTrial }, - }); - } catch (error) { - return response.customError(wrapError(error)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.basicLicenseAPIGuard(async ({ mlClient, response }) => { + try { + const body = await mlClient.info(); + const cloudId = cloud?.cloudId; + const isCloudTrial = cloud?.trialEndDate && Date.now() < cloud.trialEndDate.getTime(); + + return response.ok({ + body: { ...body, cloudId, isCloudTrial }, + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); /** * @apiGroup SystemRoutes * * @apiDeprecated * - * @api {post} /api/ml/es_search ES Search wrapper + * @api {post} /internal/ml/es_search ES Search wrapper * @apiName MlEsSearch */ - router.post( - { - path: '/api/ml/es_search', - validate: { - body: schema.maybe(schema.any()), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/es_search`, + access: 'internal', options: { tags: ['access:ml:canGetJobs'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const body = await client.asCurrentUser.search(request.body); - return response.ok({ - body, - }); - } catch (error) { - return response.customError(wrapError(error)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: schema.maybe(schema.any()), + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const body = await client.asCurrentUser.search(request.body); + return response.ok({ + body, + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); /** * @apiGroup SystemRoutes * - * @api {post} /api/ml/index_exists ES Field caps wrapper checks if index exists + * @api {post} /internal/ml/index_exists ES Field caps wrapper checks if index exists * @apiName MlIndexExists */ - router.post( - { - path: '/api/ml/index_exists', - validate: { - body: schema.object({ indices: schema.arrayOf(schema.string()) }), - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/index_exists`, + access: 'internal', options: { tags: ['access:ml:canGetFieldInfo'], }, - }, - routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { indices } = request.body; + }) + .addVersion( + { + version: '1', + validate: { + request: { body: schema.object({ indices: schema.arrayOf(schema.string()) }) }, + }, + }, + routeGuard.basicLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { indices } = request.body; - const results = await Promise.all( - indices.map(async (index) => - client.asCurrentUser.indices.exists({ - index, - allow_no_indices: false, - }) - ) - ); + const results = await Promise.all( + indices.map(async (index) => + client.asCurrentUser.indices.exists({ + index, + allow_no_indices: false, + }) + ) + ); - const result = indices.reduce((acc, cur, i) => { - acc[cur] = { exists: results[i] }; - return acc; - }, {} as Record); + const result = indices.reduce((acc, cur, i) => { + acc[cur] = { exists: results[i] }; + return acc; + }, {} as Record); - return response.ok({ - body: result, - }); - } catch (error) { - return response.customError(wrapError(error)); - } - }) - ); + return response.ok({ + body: result, + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/routes/trained_models.ts b/x-pack/plugins/ml/server/routes/trained_models.ts index 026bc3109b36f7..dd1d4fa693a84f 100644 --- a/x-pack/plugins/ml/server/routes/trained_models.ts +++ b/x-pack/plugins/ml/server/routes/trained_models.ts @@ -7,6 +7,7 @@ import { schema } from '@kbn/config-schema'; import { ErrorType } from '@kbn/ml-error-utils'; +import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { RouteInitialization } from '../types'; import { wrapError } from '../client/error_wrapper'; import { @@ -31,442 +32,514 @@ export function trainedModelsRoutes({ router, routeGuard }: RouteInitialization) /** * @apiGroup TrainedModels * - * @api {get} /api/ml/trained_models/:modelId Get info of a trained inference model + * @api {get} /internal/ml/trained_models/:modelId Get info of a trained inference model * @apiName GetTrainedModel * @apiDescription Retrieves configuration information for a trained model. */ - router.get( - { - path: '/api/ml/trained_models/{modelId?}', - validate: { - params: optionalModelIdSchema, - query: getInferenceQuerySchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId?}`, + access: 'internal', options: { tags: ['access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { - try { - const { modelId } = request.params; - const { with_pipelines: withPipelines, ...query } = request.query; - const body = await mlClient.getTrainedModels({ - // @ts-expect-error @elastic-elasticsearch not sure why this is an error, size is a number - size: 1000, - ...query, - ...(modelId ? { model_id: modelId } : {}), - }); - // model_type is missing - // @ts-ignore - const result = body.trained_model_configs as TrainedModelConfigResponse[]; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: optionalModelIdSchema, + query: getInferenceQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, request, response }) => { try { - if (withPipelines) { - // Also need to retrieve the list of deployment IDs from stats - const stats = await mlClient.getTrainedModelsStats({ - ...(modelId ? { model_id: modelId } : {}), - size: 10000, - }); + const { modelId } = request.params; + const { with_pipelines: withPipelines, ...query } = request.query; + const body = await mlClient.getTrainedModels({ + // @ts-expect-error @elastic-elasticsearch not sure why this is an error, size is a number + size: 1000, + ...query, + ...(modelId ? { model_id: modelId } : {}), + }); + // model_type is missing + // @ts-ignore + const result = body.trained_model_configs as TrainedModelConfigResponse[]; + try { + if (withPipelines) { + // Also need to retrieve the list of deployment IDs from stats + const stats = await mlClient.getTrainedModelsStats({ + ...(modelId ? { model_id: modelId } : {}), + size: 10000, + }); - const modelDeploymentsMap = stats.trained_model_stats.reduce((acc, curr) => { - if (!curr.deployment_stats) return acc; - // @ts-ignore elasticsearch-js client is missing deployment_id - const deploymentId = curr.deployment_stats.deployment_id; - if (acc[curr.model_id]) { - acc[curr.model_id].push(deploymentId); - } else { - acc[curr.model_id] = [deploymentId]; - } - return acc; - }, {} as Record); + const modelDeploymentsMap = stats.trained_model_stats.reduce((acc, curr) => { + if (!curr.deployment_stats) return acc; + // @ts-ignore elasticsearch-js client is missing deployment_id + const deploymentId = curr.deployment_stats.deployment_id; + if (acc[curr.model_id]) { + acc[curr.model_id].push(deploymentId); + } else { + acc[curr.model_id] = [deploymentId]; + } + return acc; + }, {} as Record); - const modelIdsAndAliases: string[] = Array.from( - new Set([ - ...result - .map(({ model_id: id, metadata }) => { - return [id, ...(metadata?.model_aliases ?? [])]; - }) - .flat(), - ...Object.values(modelDeploymentsMap).flat(), - ]) - ); + const modelIdsAndAliases: string[] = Array.from( + new Set([ + ...result + .map(({ model_id: id, metadata }) => { + return [id, ...(metadata?.model_aliases ?? [])]; + }) + .flat(), + ...Object.values(modelDeploymentsMap).flat(), + ]) + ); - const pipelinesResponse = await modelsProvider(client).getModelsPipelines( - modelIdsAndAliases - ); - for (const model of result) { - model.pipelines = { - ...(pipelinesResponse.get(model.model_id) ?? {}), - ...(model.metadata?.model_aliases ?? []).reduce((acc, alias) => { - return Object.assign(acc, pipelinesResponse.get(alias) ?? {}); - }, {}), - ...(modelDeploymentsMap[model.model_id] ?? []).reduce((acc, deploymentId) => { - return Object.assign(acc, pipelinesResponse.get(deploymentId) ?? {}); - }, {}), - }; + const pipelinesResponse = await modelsProvider(client).getModelsPipelines( + modelIdsAndAliases + ); + for (const model of result) { + model.pipelines = { + ...(pipelinesResponse.get(model.model_id) ?? {}), + ...(model.metadata?.model_aliases ?? []).reduce((acc, alias) => { + return Object.assign(acc, pipelinesResponse.get(alias) ?? {}); + }, {}), + ...(modelDeploymentsMap[model.model_id] ?? []).reduce((acc, deploymentId) => { + return Object.assign(acc, pipelinesResponse.get(deploymentId) ?? {}); + }, {}), + }; + } } + } catch (e) { + // the user might not have required permissions to fetch pipelines + // log the error to the debug log as this might be a common situation and + // we don't need to fill kibana's log with these messages. + mlLog.debug(e); } + + return response.ok({ + body: result, + }); } catch (e) { - // the user might not have required permissions to fetch pipelines - // log the error to the debug log as this might be a common situation and - // we don't need to fill kibana's log with these messages. - mlLog.debug(e); + return response.customError(wrapError(e)); } - - return response.ok({ - body: result, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + }) + ); /** * @apiGroup TrainedModels * - * @api {get} /api/ml/trained_models/_stats Get stats for all trained models + * @api {get} /internal/ml/trained_models/_stats Get stats for all trained models * @apiName GetTrainedModelStats * @apiDescription Retrieves usage information for all trained models. */ - router.get( - { - path: '/api/ml/trained_models/_stats', - validate: false, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const body = await mlClient.getTrainedModelsStats(); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: false, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const body = await mlClient.getTrainedModelsStats(); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {get} /api/ml/trained_models/:modelId/_stats Get stats of a trained model + * @api {get} /internal/ml/trained_models/:modelId/_stats Get stats of a trained model * @apiName GetTrainedModelStatsById * @apiDescription Retrieves usage information for trained models. */ - router.get( - { - path: '/api/ml/trained_models/{modelId}/_stats', - validate: { - params: modelIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}/_stats`, + access: 'internal', options: { tags: ['access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId } = request.params; - const body = await mlClient.getTrainedModelsStats({ - ...(modelId ? { model_id: modelId } : {}), - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId } = request.params; + const body = await mlClient.getTrainedModelsStats({ + ...(modelId ? { model_id: modelId } : {}), + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {get} /api/ml/trained_models/:modelId/pipelines Get trained model pipelines + * @api {get} /internal/ml/trained_models/:modelId/pipelines Get trained model pipelines * @apiName GetTrainedModelPipelines * @apiDescription Retrieves pipelines associated with a trained model */ - router.get( - { - path: '/api/ml/trained_models/{modelId}/pipelines', - validate: { - params: modelIdSchema, - }, + router.versioned + .get({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}/pipelines`, + access: 'internal', options: { tags: ['access:ml:canGetTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, mlClient, response }) => { - try { - const { modelId } = request.params; - const result = await modelsProvider(client).getModelsPipelines(modelId.split(',')); - return response.ok({ - body: [...result].map(([id, pipelines]) => ({ model_id: id, pipelines })), - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, mlClient, response }) => { + try { + const { modelId } = request.params; + const result = await modelsProvider(client).getModelsPipelines(modelId.split(',')); + return response.ok({ + body: [...result].map(([id, pipelines]) => ({ model_id: id, pipelines })), + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {put} /api/ml/trained_models/:modelId Put a trained model + * @api {put} /internal/ml/trained_models/:modelId Put a trained model * @apiName PutTrainedModel * @apiDescription Adds a new trained model */ - router.put( - { - path: '/api/ml/trained_models/{modelId}', - validate: { - params: modelIdSchema, - body: schema.any(), - query: putTrainedModelQuerySchema, - }, + router.versioned + .put({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}`, + access: 'internal', options: { tags: ['access:ml:canCreateTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId } = request.params; - const body = await mlClient.putTrainedModel({ - model_id: modelId, - body: request.body, - ...(request.query?.defer_definition_decompression - ? { defer_definition_decompression: true } - : {}), - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelIdSchema, + body: schema.any(), + query: putTrainedModelQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId } = request.params; + const body = await mlClient.putTrainedModel({ + model_id: modelId, + body: request.body, + ...(request.query?.defer_definition_decompression + ? { defer_definition_decompression: true } + : {}), + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {delete} /api/ml/trained_models/:modelId Delete a trained model + * @api {delete} /internal/ml/trained_models/:modelId Delete a trained model * @apiName DeleteTrainedModel * @apiDescription Deletes an existing trained model that is currently not referenced by an ingest pipeline. */ - router.delete( - { - path: '/api/ml/trained_models/{modelId}', - validate: { - params: modelIdSchema, - }, + router.versioned + .delete({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}`, + access: 'internal', options: { tags: ['access:ml:canDeleteTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId } = request.params; - const body = await mlClient.deleteTrainedModel({ - model_id: modelId, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelIdSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId } = request.params; + const body = await mlClient.deleteTrainedModel({ + model_id: modelId, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {post} /api/ml/trained_models/:modelId/deployment/_start Start trained model deployment + * @api {post} /internal/ml/trained_models/:modelId/deployment/_start Start trained model deployment * @apiName StartTrainedModelDeployment * @apiDescription Starts trained model deployment. */ - router.post( - { - path: '/api/ml/trained_models/{modelId}/deployment/_start', - validate: { - params: modelIdSchema, - query: threadingParamsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}/deployment/_start`, + access: 'internal', options: { tags: ['access:ml:canStartStopTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId } = request.params; - const body = await mlClient.startTrainedModelDeployment({ - model_id: modelId, - ...(request.query ? request.query : {}), - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelIdSchema, + query: threadingParamsSchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId } = request.params; + const body = await mlClient.startTrainedModelDeployment({ + model_id: modelId, + ...(request.query ? request.query : {}), + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {post} /api/ml/trained_models/:modelId/deployment/_update Update trained model deployment + * @api {post} /internal/ml/trained_models/:modelId/deployment/_update Update trained model deployment * @apiName UpdateTrainedModelDeployment * @apiDescription Updates trained model deployment. */ - router.post( - { - path: '/api/ml/trained_models/{modelId}/{deploymentId}/deployment/_update', - validate: { - params: modelAndDeploymentIdSchema, - body: updateDeploymentParamsSchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}/{deploymentId}/deployment/_update`, + access: 'internal', options: { tags: ['access:ml:canStartStopTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId, deploymentId } = request.params; - const body = await mlClient.updateTrainedModelDeployment({ - model_id: modelId, - deployment_id: deploymentId, - ...request.body, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { params: modelAndDeploymentIdSchema, body: updateDeploymentParamsSchema }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId, deploymentId } = request.params; + const body = await mlClient.updateTrainedModelDeployment({ + model_id: modelId, + deployment_id: deploymentId, + ...request.body, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {post} /api/ml/trained_models/:modelId/deployment/_stop Stop trained model deployment + * @api {post} /internal/ml/trained_models/:modelId/deployment/_stop Stop trained model deployment * @apiName StopTrainedModelDeployment * @apiDescription Stops trained model deployment. */ - router.post( - { - path: '/api/ml/trained_models/{modelId}/{deploymentId}/deployment/_stop', - validate: { - params: modelAndDeploymentIdSchema, - query: forceQuerySchema, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/{modelId}/{deploymentId}/deployment/_stop`, + access: 'internal', options: { tags: ['access:ml:canStartStopTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { deploymentId, modelId } = request.params; + }) + .addVersion( + { + version: '1', + validate: { + request: { + params: modelAndDeploymentIdSchema, + query: forceQuerySchema, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { deploymentId, modelId } = request.params; - const results: Record = {}; + const results: Record = {}; - for (const id of deploymentId.split(',')) { - try { - const { stopped: success } = await mlClient.stopTrainedModelDeployment({ - model_id: modelId, - deployment_id: id, - force: request.query.force ?? false, - allow_no_match: false, - }); - results[id] = { success }; - } catch (error) { - results[id] = { success: false, error }; + for (const id of deploymentId.split(',')) { + try { + const { stopped: success } = await mlClient.stopTrainedModelDeployment({ + model_id: modelId, + deployment_id: id, + force: request.query.force ?? false, + allow_no_match: false, + }); + results[id] = { success }; + } catch (error) { + results[id] = { success: false, error }; + } } + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); } - return response.ok({ - body: results, - }); - } catch (e) { - return response.customError(wrapError(e)); - } - }) - ); + }) + ); /** * @apiGroup TrainedModels * - * @api {post} /api/ml/trained_models/pipeline_simulate Simulates an ingest pipeline + * @api {post} /internal/ml/trained_models/pipeline_simulate Simulates an ingest pipeline * @apiName SimulateIngestPipeline * @apiDescription Simulates an ingest pipeline. */ - router.post( - { - path: '/api/ml/trained_models/pipeline_simulate', - validate: { - body: pipelineSimulateBody, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/pipeline_simulate`, + access: 'internal', options: { tags: ['access:ml:canTestTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { - try { - const { pipeline, docs } = request.body; - const body = await client.asInternalUser.ingest.simulate({ - pipeline, - docs, - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + body: pipelineSimulateBody, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ client, request, response }) => { + try { + const { pipeline, docs } = request.body; + const body = await client.asInternalUser.ingest.simulate({ + pipeline, + docs, + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); /** * @apiGroup TrainedModels * - * @api {post} /api/ml/trained_models/infer/:modelId Evaluates a trained model + * @api {post} /internal/ml/trained_models/infer/:modelId Evaluates a trained model * @apiName InferTrainedModelDeployment * @apiDescription Evaluates a trained model. */ - router.post( - { - path: '/api/ml/trained_models/infer/{modelId}/{deploymentId}', - validate: { - params: modelAndDeploymentIdSchema, - query: inferTrainedModelQuery, - body: inferTrainedModelBody, - }, + router.versioned + .post({ + path: `${ML_INTERNAL_BASE_PATH}/trained_models/infer/{modelId}/{deploymentId}`, + access: 'internal', options: { tags: ['access:ml:canTestTrainedModels'], }, - }, - routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { - try { - const { modelId, deploymentId } = request.params; - const body = await mlClient.inferTrainedModel({ - model_id: modelId, - deployment_id: deploymentId, - body: { - docs: request.body.docs, - ...(request.body.inference_config - ? { inference_config: request.body.inference_config } - : {}), - }, - ...(request.query.timeout ? { timeout: request.query.timeout } : {}), - }); - return response.ok({ - body, - }); - } catch (e) { - return response.customError(wrapError(e)); - } }) - ); + .addVersion( + { + version: '1', + validate: { + request: { + params: modelAndDeploymentIdSchema, + query: inferTrainedModelQuery, + body: inferTrainedModelBody, + }, + }, + }, + routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { + try { + const { modelId, deploymentId } = request.params; + const body = await mlClient.inferTrainedModel({ + model_id: modelId, + deployment_id: deploymentId, + body: { + docs: request.body.docs, + ...(request.body.inference_config + ? { inference_config: request.body.inference_config } + : {}), + }, + ...(request.query.timeout ? { timeout: request.query.timeout } : {}), + }); + return response.ok({ + body, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); } diff --git a/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_search.ts b/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_search.ts index d7cfa924b0de07..aeaad66de2e550 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_search.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_search.ts @@ -28,9 +28,10 @@ export const anomaliesSearch = async ( signal: AbortSignal ): Promise => { return KibanaServices.get().http.fetch( - '/api/ml/results/anomaly_search', + '/internal/ml/results/anomaly_search', { method: 'POST', + version: '1', body: JSON.stringify(body), asSystemRequest: true, signal, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts b/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts index f22820ab4e2200..3b1ea298e7ba9e 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts @@ -24,8 +24,9 @@ export interface Body { } export const anomaliesTableData = async (body: Body, signal: AbortSignal): Promise => { - return KibanaServices.get().http.fetch('/api/ml/results/anomalies_table_data', { + return KibanaServices.get().http.fetch('/internal/ml/results/anomalies_table_data', { method: 'POST', + version: '1', body: JSON.stringify(body), asSystemRequest: true, signal, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs.ts b/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs.ts index 286ae6b8e5ce41..232e4e6b871618 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs.ts @@ -28,8 +28,9 @@ export const getJobs = async ({ jobIds, signal, }: GetJobsArgs): Promise => - http.fetch('/api/ml/jobs/jobs', { + http.fetch('/internal/ml/jobs/jobs', { method: 'POST', + version: '1', body: JSON.stringify({ jobIds }), asSystemRequest: true, signal, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs_summary.ts b/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs_summary.ts index 19c7e12b85c692..550c60d18b1234 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs_summary.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/api/get_jobs_summary.ts @@ -25,8 +25,9 @@ export const getJobsSummary = async ({ jobIds, signal, }: GetJobsSummaryArgs): Promise => - KibanaServices.get().http.fetch('/api/ml/jobs/jobs_summary', { + KibanaServices.get().http.fetch('/internal/ml/jobs/jobs_summary', { method: 'POST', + version: '1', body: JSON.stringify({ jobIds: jobIds ?? [] }), asSystemRequest: true, signal, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/api/get_ml_capabilities.ts b/x-pack/plugins/security_solution/public/common/components/ml/api/get_ml_capabilities.ts index 28d5a8c35e2f01..ff150ce270c86c 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/api/get_ml_capabilities.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/api/get_ml_capabilities.ts @@ -29,8 +29,9 @@ export const getMlCapabilities = async ({ http: HttpSetup; signal: AbortSignal; }): Promise => - http.fetch('/api/ml/ml_capabilities', { + http.fetch('/internal/ml/ml_capabilities', { method: 'GET', + version: '1', asSystemRequest: true, signal, }); diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/api.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/api.ts index 9da104b3623610..5db2562032661e 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/api.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/api.ts @@ -33,9 +33,10 @@ export const checkRecognizer = async ({ signal, }: CheckRecognizerProps): Promise => KibanaServices.get().http.fetch( - `/api/ml/modules/recognize/${indexPatternName}`, + `/internal/ml/modules/recognize/${indexPatternName}`, { method: 'GET', + version: '1', asSystemRequest: true, signal, } @@ -50,8 +51,9 @@ export const checkRecognizer = async ({ * @throws An error if response is not OK */ export const getModules = async ({ moduleId = '', signal }: GetModulesProps): Promise => - KibanaServices.get().http.fetch(`/api/ml/modules/get_module/${moduleId}`, { + KibanaServices.get().http.fetch(`/internal/ml/modules/get_module/${moduleId}`, { method: 'GET', + version: '1', asSystemRequest: true, signal, }); @@ -75,9 +77,10 @@ export const setupMlJob = async ({ prefix = '', }: MlSetupArgs): Promise => { const response = await KibanaServices.get().http.fetch( - `/api/ml/modules/setup/${configTemplate}`, + `/internal/ml/modules/setup/${configTemplate}`, { method: 'POST', + version: '1', body: JSON.stringify({ prefix, groups, @@ -110,9 +113,10 @@ export const startDatafeeds = async ({ start: number; }): Promise => { const response = await KibanaServices.get().http.fetch( - '/api/ml/jobs/force_start_datafeeds', + '/internal/ml/jobs/force_start_datafeeds', { method: 'POST', + version: '1', body: JSON.stringify({ datafeedIds, ...(start !== 0 && { start }), @@ -138,9 +142,10 @@ export const stopDatafeeds = async ({ datafeedIds: string[]; }): Promise<[StopDatafeedResponse | ErrorResponse, CloseJobsResponse]> => { const stopDatafeedsResponse = await KibanaServices.get().http.fetch( - '/api/ml/jobs/stop_datafeeds', + '/internal/ml/jobs/stop_datafeeds', { method: 'POST', + version: '1', body: JSON.stringify({ datafeedIds, }), @@ -150,9 +155,10 @@ export const stopDatafeeds = async ({ const datafeedPrefix = 'datafeed-'; const closeJobsResponse = await KibanaServices.get().http.fetch( - '/api/ml/jobs/close_jobs', + '/internal/ml/jobs/close_jobs', { method: 'POST', + version: '1', body: JSON.stringify({ jobIds: datafeedIds.map((dataFeedId) => dataFeedId.startsWith(datafeedPrefix) diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_modules_query.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_modules_query.ts index 806bbd413f6671..810801e96a5e57 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_modules_query.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_modules_query.ts @@ -12,7 +12,7 @@ import { getModules } from '../api'; import type { GetModulesProps, Module } from '../types'; const ONE_MINUTE = 60000; -export const GET_MODULES_QUERY_KEY = ['GET', '/api/ml/modules/get_module/:moduleId']; +export const GET_MODULES_QUERY_KEY = ['GET', '/internal/ml/modules/get_module/:moduleId']; export const useFetchModulesQuery = ( queryArgs: Omit, diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_recognizer_query.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_recognizer_query.ts index 9bcd327451ce82..bd17b82cc564fe 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_recognizer_query.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_fetch_recognizer_query.ts @@ -12,7 +12,7 @@ import { checkRecognizer } from '../api'; import type { CheckRecognizerProps, RecognizerModule } from '../types'; const ONE_MINUTE = 60000; -export const GET_RECOGNIZER_QUERY_KEY = ['GET', '/api/ml/modules/recognize/:indexPatterns']; +export const GET_RECOGNIZER_QUERY_KEY = ['GET', '/internal/ml/modules/recognize/:indexPatterns']; export const useFetchRecognizerQuery = ( queryArgs: Omit, diff --git a/x-pack/plugins/synthetics/common/constants/rest_api.ts b/x-pack/plugins/synthetics/common/constants/rest_api.ts index 552980758c3ec3..3ea905d34d0dd0 100644 --- a/x-pack/plugins/synthetics/common/constants/rest_api.ts +++ b/x-pack/plugins/synthetics/common/constants/rest_api.ts @@ -24,11 +24,11 @@ export enum API_URLS { JOURNEY_SCREENSHOT_BLOCKS = `/internal/uptime/journey/screenshot/block`, LOG_PAGE_VIEW = `/internal/uptime/log_page_view`, - ML_MODULE_JOBS = `/api/ml/modules/jobs_exist/`, - ML_SETUP_MODULE = '/api/ml/modules/setup/', - ML_DELETE_JOB = `/api/ml/jobs/delete_jobs`, - ML_CAPABILITIES = '/api/ml/ml_capabilities', - ML_ANOMALIES_RESULT = `/api/ml/results/anomalies_table_data`, + ML_MODULE_JOBS = `/internal/ml/modules/jobs_exist/`, + ML_SETUP_MODULE = '/internal/ml/modules/setup/', + ML_DELETE_JOB = `/internal/ml/jobs/delete_jobs`, + ML_CAPABILITIES = '/internal/ml/ml_capabilities', + ML_ANOMALIES_RESULT = `/internal/ml/results/anomalies_table_data`, RULE_CONNECTORS = '/api/actions/connectors', CREATE_RULE = '/api/alerting/rule', diff --git a/x-pack/test/api_integration/apis/ml/annotations/create_annotations.ts b/x-pack/test/api_integration/apis/ml/annotations/create_annotations.ts index 4e52f6e1304846..192177a086d22b 100644 --- a/x-pack/test/api_integration/apis/ml/annotations/create_annotations.ts +++ b/x-pack/test/api_integration/apis/ml/annotations/create_annotations.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Annotation } from '@kbn/ml-plugin/common/types/annotations'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { createJobConfig, createAnnotationRequestBody } from './common_jobs'; export default ({ getService }: FtrProviderContext) => { @@ -35,9 +35,9 @@ export default ({ getService }: FtrProviderContext) => { it('should successfully create annotations for anomaly job', async () => { const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(annotationRequestBody); ml.api.assertResponseStatusCode(200, status, body); const annotationId = body._id; @@ -57,9 +57,9 @@ export default ({ getService }: FtrProviderContext) => { it('should successfully create annotation for user with ML read permissions', async () => { const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(annotationRequestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -77,9 +77,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to create annotation for unauthorized user', async () => { const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(annotationRequestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/annotations/delete_annotations.ts b/x-pack/test/api_integration/apis/ml/annotations/delete_annotations.ts index 11cc38da82a02c..421d59d3d7b50d 100644 --- a/x-pack/test/api_integration/apis/ml/annotations/delete_annotations.ts +++ b/x-pack/test/api_integration/apis/ml/annotations/delete_annotations.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { testSetupJobConfigs, jobIds, testSetupAnnotations } from './common_jobs'; @@ -42,9 +42,9 @@ export default ({ getService }: FtrProviderContext) => { const annotationIdToDelete = annotationsForJob[0]._id; const { body, status } = await supertest - .delete(`/api/ml/annotations/delete/${annotationIdToDelete}`) + .delete(`/internal/ml/annotations/delete/${annotationIdToDelete}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body._id).to.eql(annotationIdToDelete); @@ -60,9 +60,9 @@ export default ({ getService }: FtrProviderContext) => { const annotationIdToDelete = annotationsForJob[0]._id; const { body, status } = await supertest - .delete(`/api/ml/annotations/delete/${annotationIdToDelete}`) + .delete(`/internal/ml/annotations/delete/${annotationIdToDelete}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body._id).to.eql(annotationIdToDelete); @@ -78,9 +78,9 @@ export default ({ getService }: FtrProviderContext) => { const annotationIdToDelete = annotationsForJob[0]._id; const { body, status } = await supertest - .delete(`/api/ml/annotations/delete/${annotationIdToDelete}`) + .delete(`/internal/ml/annotations/delete/${annotationIdToDelete}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/annotations/get_annotations.ts b/x-pack/test/api_integration/apis/ml/annotations/get_annotations.ts index 9e18722373b8d4..00cfda209b4fba 100644 --- a/x-pack/test/api_integration/apis/ml/annotations/get_annotations.ts +++ b/x-pack/test/api_integration/apis/ml/annotations/get_annotations.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { omit } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { testSetupJobConfigs, jobIds, testSetupAnnotations } from './common_jobs'; @@ -44,9 +44,9 @@ export default ({ getService }: FtrProviderContext) => { maxAnnotations: 500, }; const { body, status } = await supertest - .post('/api/ml/annotations') + .post('/internal/ml/annotations') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -69,9 +69,9 @@ export default ({ getService }: FtrProviderContext) => { maxAnnotations: 500, }; const { body, status } = await supertest - .post('/api/ml/annotations') + .post('/internal/ml/annotations') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -94,9 +94,9 @@ export default ({ getService }: FtrProviderContext) => { maxAnnotations: 500, }; const { body, status } = await supertest - .post('/api/ml/annotations') + .post('/internal/ml/annotations') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -119,9 +119,9 @@ export default ({ getService }: FtrProviderContext) => { maxAnnotations: 500, }; const { body, status } = await supertest - .post('/api/ml/annotations') + .post('/internal/ml/annotations') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/annotations/update_annotations.ts b/x-pack/test/api_integration/apis/ml/annotations/update_annotations.ts index 7227b33f059017..dd7ff75374490e 100644 --- a/x-pack/test/api_integration/apis/ml/annotations/update_annotations.ts +++ b/x-pack/test/api_integration/apis/ml/annotations/update_annotations.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { ANNOTATION_TYPE } from '@kbn/ml-plugin/common/constants/annotations'; import { Annotation } from '@kbn/ml-plugin/common/types/annotations'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { testSetupJobConfigs, jobIds, testSetupAnnotations } from './common_jobs'; @@ -60,9 +60,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(annotationUpdateRequestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -91,9 +91,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(annotationUpdateRequestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -122,9 +122,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(annotationUpdateRequestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -151,9 +151,9 @@ export default ({ getService }: FtrProviderContext) => { _id: originalAnnotation._id, }; const { body, status } = await supertest - .put('/api/ml/annotations/index') + .put('/internal/ml/annotations/index') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(annotationUpdateRequestBodyWithMissingFields); ml.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/close_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/close_with_spaces.ts index dbdf96821779d1..d4d243e13e509a 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/close_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/close_with_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { JOB_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -22,12 +22,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(jobId: string, expectedStatusCode: number, space?: string) { const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors/${jobId}/_close`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors/${jobId}/_close`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create.ts index 26d15e2626ae53..44854dcaeece65 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -111,9 +111,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`${testData.testTitle}`, async () => { const { body, status } = await supertest - .put(`/api/ml/anomaly_detectors/${testData.jobId}`) + .put(`/internal/ml/anomaly_detectors/${testData.jobId}`) .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_datafeed.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_datafeed.ts index b0f2976ff33439..be22385be88fd7 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_datafeed.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_datafeed.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -76,9 +76,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`${testData.testTitle}`, async () => { const { body, status } = await supertest - .put(`/api/ml/anomaly_detectors/${testData.jobId}`) + .put(`/internal/ml/anomaly_detectors/${testData.jobId}`) .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_spaces.ts index e6bd7d2bb4792a..a3a20966d1ae85 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/create_with_spaces.ts @@ -7,7 +7,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -38,12 +38,12 @@ export default ({ getService }: FtrProviderContext) => { await ml.testExecution.logTestStep('should create job'); const { body, status } = await supertest - .put(`/s/${idSpace1}/api/ml/anomaly_detectors/${jobIdSpace1}`) + .put(`/s/${idSpace1}/internal/ml/anomaly_detectors/${jobIdSpace1}`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(jobConfig); ml.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/delete_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/delete_with_spaces.ts index 518374c152cb7d..d100d6060c5d1d 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/delete_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/delete_with_spaces.ts @@ -7,7 +7,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -20,12 +20,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(jobId: string, expectedStatusCode: number, space?: string) { const { body, status } = await supertest - .delete(`${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors/${jobId}`) + .delete(`${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors/${jobId}`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/forecast_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/forecast_with_spaces.ts index e5cd2295d09894..1176452408762a 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/forecast_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/forecast_with_spaces.ts @@ -8,7 +8,7 @@ import { JOB_STATE, DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -29,9 +29,9 @@ export default ({ getService }: FtrProviderContext) => { expectedStatusCode: number ) { const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors/${jobId}/_forecast`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors/${jobId}/_forecast`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ duration }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get.ts index 3ac0bacf8b4298..4dcd8f0d8c98c2 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -72,9 +72,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetAnomalyDetectors', () => { it('should fetch all anomaly detector jobs', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors`) + .get(`/internal/ml/anomaly_detectors`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -85,9 +85,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve jobs for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors`) + .get(`/internal/ml/anomaly_detectors`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -98,9 +98,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetAnomalyDetectorsById', () => { it('should fetch single anomaly detector job by id', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(1); @@ -110,9 +110,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch anomaly detector jobs based on provided ids', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1,${jobId}_2`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1,${jobId}_2`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -123,9 +123,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve a job for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -136,9 +136,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetAnomalyDetectorsStats', () => { it('should fetch jobs stats', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/_stats`) + .get(`/internal/ml/anomaly_detectors/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -156,9 +156,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve jobs stats for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/_stats`) + .get(`/internal/ml/anomaly_detectors/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -169,9 +169,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetAnomalyDetectorsStatsById', () => { it('should fetch single job stats', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1/_stats`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(1); @@ -188,9 +188,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch multiple jobs stats based on provided ids', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1,${jobId}_2/_stats`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1,${jobId}_2/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -208,9 +208,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve a job stats for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/anomaly_detectors/${jobId}_1/_stats`) + .get(`/internal/ml/anomaly_detectors/${jobId}_1/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_stats_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_stats_with_spaces.ts index 12530e34d51b61..6a82281d852ac8 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_stats_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_stats_with_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -29,7 +29,7 @@ export default ({ getService }: FtrProviderContext) => { ) { const { body, status } = await supertest .get( - `${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors${ + `${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors${ jobOrGroup ? `/${jobOrGroup}` : '' }/_stats` ) @@ -37,7 +37,7 @@ export default ({ getService }: FtrProviderContext) => { USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_with_spaces.ts index 95d234791b5240..908ee1728e8147 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/get_with_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -29,7 +29,7 @@ export default ({ getService }: FtrProviderContext) => { ) { const { body, status } = await supertest .get( - `${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors${ + `${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors${ jobOrGroup ? `/${jobOrGroup}` : '' }` ) @@ -37,7 +37,7 @@ export default ({ getService }: FtrProviderContext) => { USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/anomaly_detectors/open_with_spaces.ts b/x-pack/test/api_integration/apis/ml/anomaly_detectors/open_with_spaces.ts index 2fcdcdacfe9270..8cf0ab02507a0a 100644 --- a/x-pack/test/api_integration/apis/ml/anomaly_detectors/open_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/anomaly_detectors/open_with_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { JOB_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -22,12 +22,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(jobId: string, expectedStatusCode: number, space?: string) { const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors/${jobId}/_open`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors/${jobId}/_open`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts index 79c1d8c49f6049..fdd3d6b2806fc4 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -39,9 +39,9 @@ export default ({ getService }: FtrProviderContext) => { it('should successfully create calendar by id', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars`) + .put(`/internal/ml/calendars`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -57,9 +57,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not create new calendar for user without required permission', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars`) + .put(`/internal/ml/calendars`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -70,9 +70,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not create new calendar for unauthorized user', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars`) + .put(`/internal/ml/calendars`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts index 1f2f2455c97a68..fdbefbba6a8daf 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -43,9 +43,9 @@ export default ({ getService }: FtrProviderContext) => { it('should delete calendar by id', async () => { const { body, status } = await supertest - .delete(`/api/ml/calendars/${calendarId}`) + .delete(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.acknowledged).to.eql(true); @@ -54,9 +54,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not delete calendar for user without required permission', async () => { const { body, status } = await supertest - .delete(`/api/ml/calendars/${calendarId}`) + .delete(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -65,9 +65,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not delete calendar for unauthorized user', async () => { const { body, status } = await supertest - .delete(`/api/ml/calendars/${calendarId}`) + .delete(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -76,9 +76,9 @@ export default ({ getService }: FtrProviderContext) => { it('should return 404 if invalid calendarId', async () => { const { body, status } = await supertest - .delete(`/api/ml/calendars/calendar_id_dne`) + .delete(`/internal/ml/calendars/calendar_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); diff --git a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts index cca564e33cb911..941700e86f4880 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -47,9 +47,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all calendars', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars`) + .get(`/internal/ml/calendars`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).to.have.length(testCalendars.length); @@ -59,9 +59,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all calendars for user with view permission', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars`) + .get(`/internal/ml/calendars`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).to.have.length(testCalendars.length); @@ -71,9 +71,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not fetch calendars for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars`) + .get(`/internal/ml/calendars`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -99,9 +99,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch calendar & associated events by id', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars/${calendarId}`) + .get(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.job_ids).to.eql(testCalendar.job_ids); @@ -112,9 +112,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch calendar & associated events by id for user with view permission', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars/${calendarId}`) + .get(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.job_ids).to.eql(testCalendar.job_ids); @@ -125,9 +125,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not fetch calendars for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars/${calendarId}`) + .get(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -136,9 +136,9 @@ export default ({ getService }: FtrProviderContext) => { it('should return 404 if invalid calendar id', async () => { const { body, status } = await supertest - .get(`/api/ml/calendars/calendar_id_dne`) + .get(`/internal/ml/calendars/calendar_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); diff --git a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts index 0ccf60fd88dce2..c0c6b03cdf73f0 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -51,9 +51,9 @@ export default ({ getService }: FtrProviderContext) => { it('should update calendar by id with new settings', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars/${calendarId}`) + .put(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateCalendarRequestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -76,27 +76,27 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to update calendar for user without required permission', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars/${calendarId}`) + .put(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateCalendarRequestBody); ml.api.assertResponseStatusCode(403, status, body); }); it('should not allow to update calendar for unauthorized user', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars/${calendarId}`) + .put(`/internal/ml/calendars/${calendarId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateCalendarRequestBody); ml.api.assertResponseStatusCode(403, status, body); }); it('should return error if invalid calendarId', async () => { const { body, status } = await supertest - .put(`/api/ml/calendars/calendar_id_dne`) + .put(`/internal/ml/calendars/calendar_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateCalendarRequestBody); ml.api.assertResponseStatusCode(404, status, body); }); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/create_job.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/create_job.ts index 22d01b3596af3c..a05589bdf8ae7b 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/create_job.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/create_job.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -92,9 +92,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testConfig.config; const { body, status } = await supertest - .put(`/api/ml/data_frame/analytics/${analyticsId}`) + .put(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -114,9 +114,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testJobConfigs[0].config; const { body, status } = await supertest - .put(`/api/ml/data_frame/analytics/${analyticsId}`) + .put(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -129,9 +129,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testJobConfigs[0].config; const { body, status } = await supertest - .put(`/api/ml/data_frame/analytics/${analyticsId}`) + .put(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts index cee102eb4697aa..f3921b38ece903 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -78,9 +78,9 @@ export default ({ getService }: FtrProviderContext) => { it('should delete analytics jobs by id', async () => { const analyticsId = `${jobId}_1`; const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.analyticsJobDeleted.success).to.eql(true); @@ -90,9 +90,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve analytics jobs for unauthorized user', async () => { const analyticsId = `${jobId}_2`; const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -103,9 +103,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve analytics jobs for the user with only view permission', async () => { const analyticsId = `${jobId}_2`; const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -116,9 +116,9 @@ export default ({ getService }: FtrProviderContext) => { it('should show 404 error if job does not exist or has already been deleted', async () => { const id = `${jobId}_invalid`; const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${id}`) + .delete(`/internal/ml/data_frame/analytics/${id}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); @@ -140,10 +140,10 @@ export default ({ getService }: FtrProviderContext) => { it('should delete job and destination index by id', async () => { const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .query({ deleteDestIndex: true }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.analyticsJobDeleted.success).to.eql(true); @@ -169,10 +169,10 @@ export default ({ getService }: FtrProviderContext) => { it('should delete job and index pattern by id', async () => { const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .query({ deleteDestIndexPattern: true }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.analyticsJobDeleted.success).to.eql(true); @@ -201,10 +201,10 @@ export default ({ getService }: FtrProviderContext) => { it('should delete job, target index, and index pattern by id', async () => { const { body, status } = await supertest - .delete(`/api/ml/data_frame/analytics/${analyticsId}`) + .delete(`/internal/ml/data_frame/analytics/${analyticsId}`) .query({ deleteDestIndex: true, deleteDestIndexPattern: true }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.analyticsJobDeleted.success).to.eql(true); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete_spaces.ts index 48933e837baeaf..eb3b4cb93340bb 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -23,12 +23,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(jobId: string, space: string, expectedStatusCode: number) { const { body, status } = await supertest - .delete(`/s/${space}/api/ml/data_frame/analytics/${jobId}`) + .delete(`/s/${space}/internal/ml/data_frame/analytics/${jobId}`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/evaluate.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/evaluate.ts index eb3b0734158219..3bd62b64e18c1d 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/evaluate.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/evaluate.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -132,9 +132,9 @@ export default ({ getService }: FtrProviderContext) => { describe(`EvaluateDataFrameAnalytics ${testConfig.jobType}`, async () => { it(`should evaluate ${testConfig.jobType} analytics job`, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/_evaluate`) + .post(`/internal/ml/data_frame/_evaluate`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.eval); ml.api.assertResponseStatusCode(200, status, body); @@ -155,9 +155,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should evaluate ${testConfig.jobType} job for the user with only view permission`, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/_evaluate`) + .post(`/internal/ml/data_frame/_evaluate`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.eval); ml.api.assertResponseStatusCode(200, status, body); @@ -178,9 +178,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow unauthorized user to evaluate ${testConfig.jobType} job`, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/_evaluate`) + .post(`/internal/ml/data_frame/_evaluate`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.eval); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/explain.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/explain.ts index 8be131781eeaed..d6d1e1ea3099f0 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/explain.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/explain.ts @@ -9,7 +9,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -91,9 +91,9 @@ export default ({ getService }: FtrProviderContext) => { describe(`ExplainDataFrameAnalytics ${testConfig.jobType}`, async () => { it(`should explain ${testConfig.jobType} analytics job`, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/_explain`) + .post(`/internal/ml/data_frame/analytics/_explain`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.config); ml.api.assertResponseStatusCode(200, status, body); @@ -112,9 +112,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow user with only view permission to use explain endpoint for ${testConfig.jobType} job `, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/_explain`) + .post(`/internal/ml/data_frame/analytics/_explain`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.config); ml.api.assertResponseStatusCode(403, status, body); @@ -124,9 +124,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow unauthorized user to use explain endpoint for ${testConfig.jobType} job`, async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/_explain`) + .post(`/internal/ml/data_frame/analytics/_explain`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testConfig.config); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/get.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/get.ts index bef0f56a77ac7b..f03a84adf54ef9 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/get.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/get.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -96,9 +96,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetDataFrameAnalytics', () => { it('should fetch all analytics jobs', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics`) + .get(`/internal/ml/data_frame/analytics`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -109,9 +109,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve analytics jobs for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics`) + .get(`/internal/ml/data_frame/analytics`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -122,9 +122,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetDataFrameAnalyticsById', () => { it('should fetch single analytics job by id', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(1); @@ -134,9 +134,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch analytics jobs based on provided ids', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1,${jobId}_2`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1,${jobId}_2`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -147,9 +147,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve a job for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -160,9 +160,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetDataFrameAnalyticsStats', () => { it('should fetch analytics jobs stats', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/_stats`) + .get(`/internal/ml/data_frame/analytics/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -180,9 +180,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve jobs stats for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/_stats`) + .get(`/internal/ml/data_frame/analytics/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -193,9 +193,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetDataFrameAnalyticsStatsById', () => { it('should fetch single analytics job stats by id', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1/_stats`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(1); @@ -212,9 +212,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch multiple analytics jobs stats based on provided ids', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1,${jobId}_2/_stats`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1,${jobId}_2/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(2); @@ -232,9 +232,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve a job stats for the user without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1/_stats`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -245,9 +245,9 @@ export default ({ getService }: FtrProviderContext) => { describe('GetDataFrameAnalyticsIdMap', () => { it('should return a map of objects leading up to analytics job id', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/map/${jobId}_1`) + .get(`/internal/ml/data_frame/analytics/map/${jobId}_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).to.have.keys('elements', 'details', 'error'); @@ -266,9 +266,9 @@ export default ({ getService }: FtrProviderContext) => { it('should return empty results and an error message if the job does not exist', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/map/${jobId}_fake`) + .get(`/internal/ml/data_frame/analytics/map/${jobId}_fake`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.elements.length).to.eql(0); @@ -283,9 +283,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch single analytics job messages by id', async () => { await retry.tryForTime(5000, async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1/messages`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1/messages`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.length).to.eql(1); @@ -303,9 +303,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to retrieve job messages without required permissions', async () => { const { body, status } = await supertest - .get(`/api/ml/data_frame/analytics/${jobId}_1/messages`) + .get(`/internal/ml/data_frame/analytics/${jobId}_1/messages`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/get_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/get_spaces.ts index 2b853ef92ff181..e294ddb51d7eae 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/get_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/get_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -31,7 +31,7 @@ export default ({ getService }: FtrProviderContext) => { ) { const { body, status } = await supertest .get( - `/s/${space}/api/ml/data_frame/analytics${jobId ? `/${jobId}` : ''}${ + `/s/${space}/internal/ml/data_frame/analytics${jobId ? `/${jobId}` : ''}${ requestStats ? '/_stats' : '' }` ) @@ -39,7 +39,7 @@ export default ({ getService }: FtrProviderContext) => { USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; @@ -47,12 +47,12 @@ export default ({ getService }: FtrProviderContext) => { async function runMapRequest(space: string, expectedStatusCode: number, jobId: string) { const { body, status } = await supertest - .get(`/s/${space}/api/ml/data_frame/analytics/map/${jobId}`) + .get(`/s/${space}/internal/ml/data_frame/analytics/map/${jobId}`) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/jobs_exist_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/jobs_exist_spaces.ts index bf81e4df2a5a4d..73b609961fc585 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/jobs_exist_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/jobs_exist_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -31,12 +31,12 @@ export default ({ getService }: FtrProviderContext) => { allSpaces?: boolean ) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/data_frame/analytics/jobs_exist`) + .post(`/s/${space}/internal/ml/data_frame/analytics/jobs_exist`) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(allSpaces ? { analyticsIds, allSpaces } : { analyticsIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/new_job_caps.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/new_job_caps.ts index cd2349cc6fba53..e37d800b40d306 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/new_job_caps.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/new_job_caps.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -18,7 +18,7 @@ export default ({ getService }: FtrProviderContext) => { const testIndexPattern = 'ft_bank_marketing'; async function runRequest(indexPattern: string, expectedStatusCode: number, rollup?: boolean) { - let url = `/api/ml/data_frame/analytics/new_job_caps/${indexPattern}`; + let url = `/internal/ml/data_frame/analytics/new_job_caps/${indexPattern}`; if (rollup !== undefined) { url += `?rollup=${rollup}`; } @@ -28,7 +28,7 @@ export default ({ getService }: FtrProviderContext) => { USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/start.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/start.ts index 431d249d95ee78..160373d5adf314 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/start.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/start.ts @@ -11,7 +11,7 @@ import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { DATA_FRAME_TASK_STATE } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -79,9 +79,9 @@ export default ({ getService }: FtrProviderContext) => { const analyticsId = `${jobId}_0`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_start`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_start`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).not.to.be(undefined); @@ -97,9 +97,9 @@ export default ({ getService }: FtrProviderContext) => { const message = `No known job with id '${id}'`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${id}/_start`) + .post(`/internal/ml/data_frame/analytics/${id}/_start`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); @@ -110,9 +110,9 @@ export default ({ getService }: FtrProviderContext) => { const analyticsId = `${jobId}_0`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_start`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_start`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -123,9 +123,9 @@ export default ({ getService }: FtrProviderContext) => { const analyticsId = `${jobId}_0`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_start`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_start`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/start_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/start_spaces.ts index 67a5dd3f37900f..ee40465679717f 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/start_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/start_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { DATA_FRAME_TASK_STATE } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -27,12 +27,12 @@ export default ({ getService }: FtrProviderContext) => { async function runStartRequest(jobId: string, space: string, expectedStatusCode: number) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/data_frame/analytics/${jobId}/_start`) + .post(`/s/${space}/internal/ml/data_frame/analytics/${jobId}/_start`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop.ts index 7a11ddb1de1b15..fa819d31dcd394 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { DATA_FRAME_TASK_STATE } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -41,9 +41,9 @@ export default ({ getService }: FtrProviderContext) => { describe('StopsDataFrameAnalyticsJob', () => { it('should stop analytics job for specified id when job exists', async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_stop`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_stop`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).not.to.be(undefined); @@ -56,9 +56,9 @@ export default ({ getService }: FtrProviderContext) => { const message = `No known job with id '${id}'`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${id}/_stop`) + .post(`/internal/ml/data_frame/analytics/${id}/_stop`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); @@ -67,9 +67,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to stop analytics job for unauthorized user', async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_stop`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_stop`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -78,9 +78,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to stop analytics job for user with view only permission', async () => { const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_stop`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_stop`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop_spaces.ts index 30a516a46ea186..6006b33ffb93d5 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/stop_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { DATA_FRAME_TASK_STATE } from '@kbn/ml-plugin/common/constants/data_frame_analytics'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -30,12 +30,12 @@ export default ({ getService }: FtrProviderContext) => { expectedStatusCode: number ) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/data_frame/analytics/${jobId}/${action}`) + .post(`/s/${space}/internal/ml/data_frame/analytics/${jobId}/${action}`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts index 565333adefaa13..b716ca2361f65a 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -70,9 +70,9 @@ export default ({ getService }: FtrProviderContext) => { async function getDFAJob(id: string) { const { body } = await supertest - .get(`/api/ml/data_frame/analytics/${id}`) + .get(`/internal/ml/data_frame/analytics/${id}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); return body.data_frame_analytics[0]; } @@ -100,9 +100,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -124,9 +124,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -148,9 +148,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -172,9 +172,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -196,9 +196,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -219,9 +219,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -240,9 +240,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .post(`/internal/ml/data_frame/analytics/${analyticsId}/_update`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -262,9 +262,9 @@ export default ({ getService }: FtrProviderContext) => { const message = `No known job with id '${id}'`; const { body, status } = await supertest - .post(`/api/ml/data_frame/analytics/${id}/_update`) + .post(`/internal/ml/data_frame/analytics/${id}/_update`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(404, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/update_spaces.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update_spaces.ts index ff3235a00592b6..6b62502827c6b8 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/update_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -32,12 +32,12 @@ export default ({ getService }: FtrProviderContext) => { requestBody: unknown ) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/data_frame/analytics/${jobId}/_update`) + .post(`/s/${space}/internal/ml/data_frame/analytics/${jobId}/_update`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/validate.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/validate.ts index 51a0c9743de4a8..bc643a00af2af2 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/validate.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/validate.ts @@ -10,7 +10,7 @@ import { DataFrameAnalyticsConfig } from '@kbn/ml-plugin/public/application/data import { DeepPartial } from '@kbn/ml-plugin/common/types/common'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -91,9 +91,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testConfig.config; const { body, status } = await supertest - .post('/api/ml/data_frame/analytics/validate') + .post('/internal/ml/data_frame/analytics/validate') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -107,9 +107,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testJobConfigs[0].config; const { body, status } = await supertest - .post('/api/ml/data_frame/analytics/validate') + .post('/internal/ml/data_frame/analytics/validate') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -121,9 +121,9 @@ export default ({ getService }: FtrProviderContext) => { const requestBody = testJobConfigs[0].config; const { body, status } = await supertest - .post('/api/ml/data_frame/analytics/validate') + .post('/internal/ml/data_frame/analytics/validate') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/datafeeds/get_stats_with_spaces.ts b/x-pack/test/api_integration/apis/ml/datafeeds/get_stats_with_spaces.ts index 6fef5c8ed8172d..0b74e67278943a 100644 --- a/x-pack/test/api_integration/apis/ml/datafeeds/get_stats_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/datafeeds/get_stats_with_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -28,13 +28,15 @@ export default ({ getService }: FtrProviderContext) => { ) { const { body, status } = await supertest .get( - `${space ? `/s/${space}` : ''}/api/ml/datafeeds${datafeedId ? `/${datafeedId}` : ''}/_stats` + `${space ? `/s/${space}` : ''}/internal/ml/datafeeds${ + datafeedId ? `/${datafeedId}` : '' + }/_stats` ) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/datafeeds/get_with_spaces.ts b/x-pack/test/api_integration/apis/ml/datafeeds/get_with_spaces.ts index 086f555baa72c0..152f8ceba28e05 100644 --- a/x-pack/test/api_integration/apis/ml/datafeeds/get_with_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/datafeeds/get_with_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -27,12 +27,14 @@ export default ({ getService }: FtrProviderContext) => { space?: string ) { const { body, status } = await supertest - .get(`${space ? `/s/${space}` : ''}/api/ml/datafeeds${datafeedId ? `/${datafeedId}` : ''}`) + .get( + `${space ? `/s/${space}` : ''}/internal/ml/datafeeds${datafeedId ? `/${datafeedId}` : ''}` + ) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/datafeeds/update.ts b/x-pack/test/api_integration/apis/ml/datafeeds/update.ts index 89262e2cbb8feb..dabf2deb1de674 100644 --- a/x-pack/test/api_integration/apis/ml/datafeeds/update.ts +++ b/x-pack/test/api_integration/apis/ml/datafeeds/update.ts @@ -9,7 +9,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -31,9 +31,9 @@ export default ({ getService }: FtrProviderContext) => { ) { const datafeedId = datafeedConfig.datafeed_id; const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/datafeeds/${datafeedId}/_update`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/datafeeds/${datafeedId}/_update`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(datafeedConfig.body); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/fields_service/field_cardinality.ts b/x-pack/test/api_integration/apis/ml/fields_service/field_cardinality.ts index 5bfbada12200ad..e6b7af719a73cd 100644 --- a/x-pack/test/api_integration/apis/ml/fields_service/field_cardinality.ts +++ b/x-pack/test/api_integration/apis/ml/fields_service/field_cardinality.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -97,9 +97,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`${testData.testTitle}`, async () => { const { body, status } = await supertest - .post('/api/ml/fields_service/field_cardinality') + .post('/internal/ml/fields_service/field_cardinality') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.statusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/fields_service/time_field_range.ts b/x-pack/test/api_integration/apis/ml/fields_service/time_field_range.ts index 3f1a21b40784a5..6f55439b8e11f0 100644 --- a/x-pack/test/api_integration/apis/ml/fields_service/time_field_range.ts +++ b/x-pack/test/api_integration/apis/ml/fields_service/time_field_range.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -85,9 +85,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`${testData.testTitle}`, async () => { const { body, status } = await supertest - .post('/api/ml/fields_service/time_field_range') + .post('/internal/ml/fields_service/time_field_range') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/filters/create_filters.ts b/x-pack/test/api_integration/apis/ml/filters/create_filters.ts index 6eec47456fb512..91d468593df822 100644 --- a/x-pack/test/api_integration/apis/ml/filters/create_filters.ts +++ b/x-pack/test/api_integration/apis/ml/filters/create_filters.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -108,9 +108,9 @@ export default ({ getService }: FtrProviderContext) => { const { testTitle, user, requestBody, expected } = testData; it(`${testTitle}`, async () => { const { body, status } = await supertest - .put(`/api/ml/filters`) + .put(`/internal/ml/filters`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts b/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts index 0cd06f64ba7711..0afdf94813a95b 100644 --- a/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts +++ b/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -50,9 +50,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should delete filter by id`, async () => { const { filterId } = validFilters[0]; const { body, status } = await supertest - .delete(`/api/ml/filters/${filterId}`) + .delete(`/internal/ml/filters/${filterId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.acknowledged).to.eql(true); @@ -62,9 +62,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not delete filter for user without required permission`, async () => { const { filterId } = validFilters[1]; const { body, status } = await supertest - .delete(`/api/ml/filters/${filterId}`) + .delete(`/internal/ml/filters/${filterId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -74,9 +74,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not delete filter for unauthorized user`, async () => { const { filterId } = validFilters[2]; const { body, status } = await supertest - .delete(`/api/ml/filters/${filterId}`) + .delete(`/internal/ml/filters/${filterId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -85,9 +85,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow user to delete filter if invalid filterId`, async () => { const { body, status } = await supertest - .delete(`/api/ml/filters/filter_id_dne`) + .delete(`/internal/ml/filters/filter_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); diff --git a/x-pack/test/api_integration/apis/ml/filters/get_filters.ts b/x-pack/test/api_integration/apis/ml/filters/get_filters.ts index 0cfd91ffb90359..791d14ad240896 100644 --- a/x-pack/test/api_integration/apis/ml/filters/get_filters.ts +++ b/x-pack/test/api_integration/apis/ml/filters/get_filters.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -44,9 +44,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should fetch all filters`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters`) + .get(`/internal/ml/filters`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).to.have.length(validFilters.length); @@ -54,9 +54,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow to retrieve filters for user without required permission`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters`) + .get(`/internal/ml/filters`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -65,9 +65,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow to retrieve filters for unauthorized user`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters`) + .get(`/internal/ml/filters`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -77,9 +77,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should fetch single filter by id`, async () => { const { filterId, requestBody } = validFilters[0]; const { body, status } = await supertest - .get(`/api/ml/filters/${filterId}`) + .get(`/internal/ml/filters/${filterId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.filter_id).to.eql(filterId); @@ -89,9 +89,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should return 404 if filterId does not exist`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters/filter_id_dne`) + .get(`/internal/ml/filters/filter_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); expect(body.error).to.eql('Not Found'); diff --git a/x-pack/test/api_integration/apis/ml/filters/get_filters_stats.ts b/x-pack/test/api_integration/apis/ml/filters/get_filters_stats.ts index 9e6c560c135c2a..c0c2e115eb7ba1 100644 --- a/x-pack/test/api_integration/apis/ml/filters/get_filters_stats.ts +++ b/x-pack/test/api_integration/apis/ml/filters/get_filters_stats.ts @@ -10,7 +10,7 @@ import { Job } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FilterStats } from '@kbn/ml-plugin/common/types/filters'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -174,9 +174,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should fetch all filters stats`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters/_stats`) + .get(`/internal/ml/filters/_stats`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body).to.have.length(testDataList.length); @@ -206,9 +206,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow retrieving filters stats for user without required permission`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters/_stats`) + .get(`/internal/ml/filters/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); @@ -217,9 +217,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow retrieving filters stats for unauthorized user`, async () => { const { body, status } = await supertest - .get(`/api/ml/filters/_stats`) + .get(`/internal/ml/filters/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/filters/update_filters.ts b/x-pack/test/api_integration/apis/ml/filters/update_filters.ts index 7515cabca7998c..9fabcb9c427c51 100644 --- a/x-pack/test/api_integration/apis/ml/filters/update_filters.ts +++ b/x-pack/test/api_integration/apis/ml/filters/update_filters.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -55,9 +55,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should update filter by id`, async () => { const { filterId } = validFilters[0]; const { body, status } = await supertest - .put(`/api/ml/filters/${filterId}`) + .put(`/internal/ml/filters/${filterId}`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateFilterRequestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -69,9 +69,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow to update filter for user without required permission`, async () => { const { filterId, requestBody: oldFilterRequest } = validFilters[1]; const { body, status } = await supertest - .put(`/api/ml/filters/${filterId}`) + .put(`/internal/ml/filters/${filterId}`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateFilterRequestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -89,9 +89,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should not allow to update filter for unauthorized user`, async () => { const { filterId, requestBody: oldFilterRequest } = validFilters[2]; const { body, status } = await supertest - .put(`/api/ml/filters/${filterId}`) + .put(`/internal/ml/filters/${filterId}`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateFilterRequestBody); ml.api.assertResponseStatusCode(403, status, body); @@ -106,9 +106,9 @@ export default ({ getService }: FtrProviderContext) => { it(`should return appropriate error if invalid filterId`, async () => { const { body, status } = await supertest - .put(`/api/ml/filters/filter_id_dne`) + .put(`/internal/ml/filters/filter_id_dne`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(updateFilterRequestBody); ml.api.assertResponseStatusCode(404, status, body); diff --git a/x-pack/test/api_integration/apis/ml/indices/field_caps.ts b/x-pack/test/api_integration/apis/ml/indices/field_caps.ts index 829430024599cb..c979600a161383 100644 --- a/x-pack/test/api_integration/apis/ml/indices/field_caps.ts +++ b/x-pack/test/api_integration/apis/ml/indices/field_caps.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -21,9 +21,9 @@ export default ({ getService }: FtrProviderContext) => { fields?: string[] ): Promise<{ indices: string[]; fields: any }> { const { body, status } = await supertest - .post(`/api/ml/indices/field_caps`) + .post(`/internal/ml/indices/field_caps`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ index, fields }); ml.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/ml/job_audit_messages/clear_messages.ts b/x-pack/test/api_integration/apis/ml/job_audit_messages/clear_messages.ts index 2ce349bde39eef..4d266055dc54aa 100644 --- a/x-pack/test/api_integration/apis/ml/job_audit_messages/clear_messages.ts +++ b/x-pack/test/api_integration/apis/ml/job_audit_messages/clear_messages.ts @@ -10,7 +10,7 @@ import { omit } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { getJobConfig } from '.'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -30,9 +30,9 @@ export default ({ getService }: FtrProviderContext) => { } const { body, status } = await supertest - .get(`/api/ml/job_audit_messages/messages`) + .get(`/internal/ml/job_audit_messages/messages`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); notificationIndices = body.notificationIndices; @@ -46,9 +46,9 @@ export default ({ getService }: FtrProviderContext) => { const timestamp = Date.now(); const { body, status } = await supertest - .put(`/api/ml/job_audit_messages/clear_messages`) + .put(`/internal/ml/job_audit_messages/clear_messages`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobId: 'test_get_job_audit_messages_1', notificationIndices, @@ -60,9 +60,9 @@ export default ({ getService }: FtrProviderContext) => { await retry.tryForTime(5000, async () => { const { body: getBody, status: getStatus } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, getStatus, getBody); expect(getBody.messages.length).to.eql( @@ -82,9 +82,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not mark audit messages as cleared for the user with ML read permissions', async () => { const { body, status } = await supertest - .put(`/api/ml/job_audit_messages/clear_messages`) + .put(`/internal/ml/job_audit_messages/clear_messages`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobId: 'test_get_job_audit_messages_2', notificationIndices, @@ -95,9 +95,9 @@ export default ({ getService }: FtrProviderContext) => { expect(body.message).to.eql('Forbidden'); const { body: getBody, status: getStatus } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_2`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_2`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, getStatus, getBody); expect(getBody.messages[0].cleared).to.not.eql(true); @@ -105,9 +105,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not mark audit messages as cleared for unauthorized user', async () => { const { body, status } = await supertest - .put(`/api/ml/job_audit_messages/clear_messages`) + .put(`/internal/ml/job_audit_messages/clear_messages`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobId: 'test_get_job_audit_messages_2', notificationIndices, @@ -118,9 +118,9 @@ export default ({ getService }: FtrProviderContext) => { expect(body.message).to.eql('Forbidden'); const { body: getBody, status: getStatus } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_2`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_2`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, getStatus, getBody); expect(getBody.messages[0].cleared).to.not.eql(true); diff --git a/x-pack/test/api_integration/apis/ml/job_audit_messages/get_job_audit_messages.ts b/x-pack/test/api_integration/apis/ml/job_audit_messages/get_job_audit_messages.ts index 046aa248a19515..907624586a6415 100644 --- a/x-pack/test/api_integration/apis/ml/job_audit_messages/get_job_audit_messages.ts +++ b/x-pack/test/api_integration/apis/ml/job_audit_messages/get_job_audit_messages.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { omit, keyBy } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { getJobConfig } from '.'; @@ -35,9 +35,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all audit messages', async () => { await retry.tryForTime(5000, async () => { const { body, status } = await supertest - .get(`/api/ml/job_audit_messages/messages`) + .get(`/internal/ml/job_audit_messages/messages`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.messages.length).to.eql( @@ -69,9 +69,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch audit messages for specified job', async () => { await retry.tryForTime(5000, async () => { const { body, status } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.messages.length).to.eql( @@ -91,9 +91,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch audit messages for user with ML read permissions', async () => { await retry.tryForTime(5000, async () => { const { body, status } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.messages.length).to.eql( @@ -112,9 +112,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not allow to fetch audit messages for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) + .get(`/internal/ml/job_audit_messages/messages/test_get_job_audit_messages_1`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.eql('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/bucket_span_estimator.ts b/x-pack/test/api_integration/apis/ml/job_validation/bucket_span_estimator.ts index 8baffcd9ae0ea5..e6c058acc36957 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/bucket_span_estimator.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/bucket_span_estimator.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -96,9 +96,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`estimates the bucket span ${testData.testTitleSuffix}`, async () => { const { body, status } = await supertest - .post('/api/ml/validate/estimate_bucket_span') + .post('/internal/ml/validate/estimate_bucket_span') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); @@ -126,9 +126,9 @@ export default ({ getService }: FtrProviderContext) => { it(`estimates the bucket span`, async () => { const { body, status } = await supertest - .post('/api/ml/validate/estimate_bucket_span') + .post('/internal/ml/validate/estimate_bucket_span') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); @@ -155,9 +155,9 @@ export default ({ getService }: FtrProviderContext) => { it(`estimates the bucket span`, async () => { const { body, status } = await supertest - .post('/api/ml/validate/estimate_bucket_span') + .post('/internal/ml/validate/estimate_bucket_span') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/calculate_model_memory_limit.ts b/x-pack/test/api_integration/apis/ml/job_validation/calculate_model_memory_limit.ts index 67570039b915f4..1052591735446c 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/calculate_model_memory_limit.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/calculate_model_memory_limit.ts @@ -7,7 +7,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -152,9 +152,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(`calculates the model memory limit ${testData.testTitleSuffix}`, async () => { const { body, status } = await supertest - .post('/api/ml/validate/calculate_model_memory_limit') + .post('/internal/ml/validate/calculate_model_memory_limit') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/cardinality.ts b/x-pack/test/api_integration/apis/ml/job_validation/cardinality.ts index 7d199ab28101a5..7f625efc9d7760 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/cardinality.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/cardinality.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -55,9 +55,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/cardinality') + .post('/internal/ml/validate/cardinality') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -92,9 +92,9 @@ export default ({ getService }: FtrProviderContext) => { }, }; const { body, status } = await supertest - .post('/api/ml/validate/cardinality') + .post('/internal/ml/validate/cardinality') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -144,9 +144,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/cardinality') + .post('/internal/ml/validate/cardinality') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(400, status, body); @@ -184,9 +184,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/cardinality') + .post('/internal/ml/validate/cardinality') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts b/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts index df6b530ecdf61d..a392ea9751ba05 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts @@ -15,7 +15,7 @@ import expect from '@kbn/expect'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; const farequoteMappings: estypes.MappingTypeMapping = { properties: { @@ -101,9 +101,9 @@ export default ({ getService }: FtrProviderContext) => { const job = getBaseJobConfig(); const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job }); ml.api.assertResponseStatusCode(200, status, body); @@ -119,9 +119,9 @@ export default ({ getService }: FtrProviderContext) => { job.analysis_config.detectors[0].field_name = 'no_such_field'; const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job }); ml.api.assertResponseStatusCode(200, status, body); @@ -137,9 +137,9 @@ export default ({ getService }: FtrProviderContext) => { job.datafeed_config.indices = ['farequote_empty']; const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job }); ml.api.assertResponseStatusCode(200, status, body); @@ -154,9 +154,9 @@ export default ({ getService }: FtrProviderContext) => { const job = getBaseJobConfig(); const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job }); ml.api.assertResponseStatusCode(403, status, body); }); @@ -165,9 +165,9 @@ export default ({ getService }: FtrProviderContext) => { const job = getBaseJobConfig(); const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job }); ml.api.assertResponseStatusCode(403, status, body); }); @@ -176,9 +176,9 @@ export default ({ getService }: FtrProviderContext) => { const job = getBaseJobConfig(); const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, start: 1454889600000, end: 1454976000000 }); ml.api.assertResponseStatusCode(200, status, body); @@ -193,9 +193,9 @@ export default ({ getService }: FtrProviderContext) => { const job = getBaseJobConfig(); const { body, status } = await supertest - .post('/api/ml/validate/datafeed_preview') + .post('/internal/ml/validate/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, start: 0, end: 1249497607000 }); ml.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/validate.ts b/x-pack/test/api_integration/apis/ml/job_validation/validate.ts index 88daa234db3be1..8a7cb38f8dba8d 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/validate.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/validate.ts @@ -13,7 +13,7 @@ import { } from '@kbn/ml-plugin/common/constants/messages.test.mock'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -71,9 +71,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/job') + .post('/internal/ml/validate/job') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -115,9 +115,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/job') + .post('/internal/ml/validate/job') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -165,9 +165,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/job') + .post('/internal/ml/validate/job') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -232,9 +232,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/job') + .post('/internal/ml/validate/job') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(400, status, body); @@ -278,9 +278,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/validate/job') + .post('/internal/ml/validate/job') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/categorization_field_examples.ts b/x-pack/test/api_integration/apis/ml/jobs/categorization_field_examples.ts index 480a6350e7ca50..654588eef4e4c7 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/categorization_field_examples.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/categorization_field_examples.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; const start = 1554463535770; const end = 1574316073914; @@ -293,9 +293,9 @@ export default ({ getService }: FtrProviderContext) => { for (const testData of testDataList) { it(testData.title, async () => { const { body, status } = await supertest - .post('/api/ml/jobs/categorization_field_examples') + .post('/internal/ml/jobs/categorization_field_examples') .auth(testData.user, ml.securityCommon.getPasswordForUser(testData.user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(testData.requestBody); ml.api.assertResponseStatusCode(testData.expected.responseCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/close_jobs.ts b/x-pack/test/api_integration/apis/ml/jobs/close_jobs.ts index 62250c63fc0005..4f759a1c5a932a 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/close_jobs.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/close_jobs.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { JOB_STATE, DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; @@ -26,9 +26,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise { const { body, status } = await supertest - .post('/api/ml/jobs/close_jobs') + .post('/internal/ml/jobs/close_jobs') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/close_jobs_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/close_jobs_spaces.ts index 5e291bac8d716e..510b3990d45a01 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/close_jobs_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/close_jobs_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { JOB_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -24,12 +24,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(space: string, expectedStatusCode: number, jobIds?: string[]) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/close_jobs`) + .post(`/s/${space}/internal/ml/jobs/close_jobs`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/datafeed_preview.ts b/x-pack/test/api_integration/apis/ml/jobs/datafeed_preview.ts index 33817adb8b27c4..8b453c21a0428f 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/datafeed_preview.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/datafeed_preview.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -66,9 +66,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(200, status, body); @@ -103,9 +103,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(200, status, body); @@ -145,9 +145,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(200, status, body); @@ -190,9 +190,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(200, status, body); @@ -225,9 +225,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(403, status, body); }); @@ -250,9 +250,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post('/api/ml/jobs/datafeed_preview') + .post('/internal/ml/jobs/datafeed_preview') .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ job, datafeed }); ml.api.assertResponseStatusCode(403, status, body); }); diff --git a/x-pack/test/api_integration/apis/ml/jobs/delete_jobs.ts b/x-pack/test/api_integration/apis/ml/jobs/delete_jobs.ts index 7ef6b49f563a7e..9d59531c65ecf3 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/delete_jobs.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/delete_jobs.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG } from './common_jobs'; @@ -69,9 +69,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise { const { body, status } = await supertest - .post('/api/ml/jobs/delete_jobs') + .post('/internal/ml/jobs/delete_jobs') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/delete_jobs_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/delete_jobs_spaces.ts index 58fd588db11f85..72f87c0a564890 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/delete_jobs_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/delete_jobs_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -23,12 +23,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(space: string, expectedStatusCode: number, jobIds?: string[]) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/delete_jobs`) + .post(`/s/${space}/internal/ml/jobs/delete_jobs`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds.ts b/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds.ts index b331f5f10878c6..381b25318cedc2 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds.ts @@ -10,7 +10,7 @@ import { JOB_STATE, DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/state import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -25,9 +25,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise> { const { body, status } = await supertest - .post('/api/ml/jobs/force_start_datafeeds') + .post('/internal/ml/jobs/force_start_datafeeds') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds_spaces.ts index b1bbc4fcd22f3e..132685ba96572d 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/force_start_datafeeds_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -35,12 +35,12 @@ export default ({ getService }: FtrProviderContext) => { end: number ): Promise> { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/force_start_datafeeds`) + .post(`/s/${space}/internal/ml/jobs/force_start_datafeeds`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ datafeedIds, start, end }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/get_groups.ts b/x-pack/test/api_integration/apis/ml/jobs/get_groups.ts index 9cccdfe65869c0..eb8d64258cf0a6 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/get_groups.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/get_groups.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import type { Group } from '@kbn/ml-plugin/common/types/groups'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG } from './common_jobs'; @@ -39,9 +39,9 @@ export default ({ getService }: FtrProviderContext) => { async function runGetGroupsRequest(user: USER, expectedResponsecode: number): Promise { const { body, status } = await supertest - .get('/api/ml/jobs/groups') + .get('/internal/ml/jobs/groups') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs.ts index c843aab29dc481..3929ed377a51ca 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import type { CombinedJobWithStats } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; @@ -49,11 +49,12 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number, space?: string ): Promise { - const path = space === undefined ? '/api/ml/jobs/jobs' : `/s/${space}/api/ml/jobs/jobs`; + const path = + space === undefined ? '/internal/ml/jobs/jobs' : `/s/${space}/internal/ml/jobs/jobs`; const { body, status } = await supertest .post(path) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_exist.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_exist.ts index a3ba73338bee93..f45f7052b65c61 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_exist.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_exist.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; @@ -71,9 +71,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise { const { body, status } = await supertest - .post('/api/ml/jobs/jobs_exist') + .post('/internal/ml/jobs/jobs_exist') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_exist_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_exist_spaces.ts index 8a7ddb91b76239..023b367bd8cfd8 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_exist_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_exist_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -24,12 +24,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(space: string, expectedStatusCode: number, jobIds?: string[]) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/jobs_exist`) + .post(`/s/${space}/internal/ml/jobs/jobs_exist`) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts index 38d257837fbf5c..a85b0f5d2ececf 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { sortBy } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG } from './common_jobs'; @@ -175,9 +175,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise { const { body, status } = await supertest - .post('/api/ml/jobs/jobs_summary') + .post('/internal/ml/jobs/jobs_summary') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary_spaces.ts index afc9b9085ea2ff..a650b0a1d19514 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -22,12 +22,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(space: string, expectedStatusCode: number, jobIds?: string[]) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/jobs_summary`) + .post(`/s/${space}/internal/ml/jobs/jobs_summary`) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/reset.ts b/x-pack/test/api_integration/apis/ml/jobs/reset.ts index 668e3a8ccc0bb9..b6ac5906c1b1dd 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/reset.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/reset.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { ANNOTATION_TYPE } from '@kbn/ml-plugin/common/constants/annotations'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; @@ -26,9 +26,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise { const { body, status } = await supertest - .post('/api/ml/jobs/reset_jobs') + .post('/internal/ml/jobs/reset_jobs') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds.ts b/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds.ts index 936a1547ea1614..330a059d6c4e5b 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds.ts @@ -10,7 +10,7 @@ import { JOB_STATE, DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/state import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; import { MULTI_METRIC_JOB_CONFIG, SINGLE_METRIC_JOB_CONFIG, DATAFEED_CONFIG } from './common_jobs'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -25,9 +25,9 @@ export default ({ getService }: FtrProviderContext) => { expectedResponsecode: number ): Promise> { const { body, status } = await supertest - .post('/api/ml/jobs/stop_datafeeds') + .post('/internal/ml/jobs/stop_datafeeds') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedResponsecode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds_spaces.ts b/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds_spaces.ts index 55f6b70b8a5abd..9e8c342c8ced4e 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/stop_datafeeds_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; export default ({ getService }: FtrProviderContext) => { @@ -31,12 +31,12 @@ export default ({ getService }: FtrProviderContext) => { datafeedIds: string[] ): Promise> { const { body, status } = await supertest - .post(`/s/${space}/api/ml/jobs/stop_datafeeds`) + .post(`/s/${space}/internal/ml/jobs/stop_datafeeds`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ datafeedIds }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/management/get_list.ts b/x-pack/test/api_integration/apis/ml/management/get_list.ts index d0cb73566fa33d..9cecacfa3da2c5 100644 --- a/x-pack/test/api_integration/apis/ml/management/get_list.ts +++ b/x-pack/test/api_integration/apis/ml/management/get_list.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import type { MlSavedObjectType } from '@kbn/ml-plugin/common/types/saved_objects'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -31,12 +31,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(listType: MlSavedObjectType, space?: string) { const { body, status } = await supertest - .get(`${space ? `/s/${space}` : ''}/api/ml/management/list/${listType}`) + .get(`${space ? `/s/${space}` : ''}/internal/ml/management/list/${listType}`) .auth( USER.ML_POWERUSER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/modules/get_module.ts b/x-pack/test/api_integration/apis/ml/modules/get_module.ts index e09b79557cf7e9..7c72f18f918e39 100644 --- a/x-pack/test/api_integration/apis/ml/modules/get_module.ts +++ b/x-pack/test/api_integration/apis/ml/modules/get_module.ts @@ -10,7 +10,7 @@ import expect from '@kbn/expect'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; const moduleIds = [ 'apache_data_stream', @@ -41,9 +41,9 @@ export default ({ getService }: FtrProviderContext) => { async function executeGetModuleRequest(module: string, user: USER, rspCode: number) { const { body, status } = await supertest - .get(`/api/ml/modules/get_module/${module}`) + .get(`/internal/ml/modules/get_module/${module}`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(rspCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/modules/jobs_exist.ts b/x-pack/test/api_integration/apis/ml/modules/jobs_exist.ts index 3e5cd0aa996d6d..0f59baa11d1374 100644 --- a/x-pack/test/api_integration/apis/ml/modules/jobs_exist.ts +++ b/x-pack/test/api_integration/apis/ml/modules/jobs_exist.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -26,9 +26,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(moduleId: string, expectedStatusCode: number, user: USER) { const { body, status } = await supertest - .get(`/api/ml/modules/jobs_exist/${moduleId}`) + .get(`/internal/ml/modules/jobs_exist/${moduleId}`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/modules/recognize_module.ts b/x-pack/test/api_integration/apis/ml/modules/recognize_module.ts index 611c6a24cd6bd3..0c03b65dcced02 100644 --- a/x-pack/test/api_integration/apis/ml/modules/recognize_module.ts +++ b/x-pack/test/api_integration/apis/ml/modules/recognize_module.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -205,9 +205,9 @@ export default ({ getService }: FtrProviderContext) => { async function executeRecognizeModuleRequest(indexPattern: string, user: USER, rspCode: number) { const { body, status } = await supertest - .get(`/api/ml/modules/recognize/${indexPattern}`) + .get(`/internal/ml/modules/recognize/${indexPattern}`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(rspCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/modules/setup_module.ts b/x-pack/test/api_integration/apis/ml/modules/setup_module.ts index 1b2ce178dabb17..1eb327c897b084 100644 --- a/x-pack/test/api_integration/apis/ml/modules/setup_module.ts +++ b/x-pack/test/api_integration/apis/ml/modules/setup_module.ts @@ -12,7 +12,7 @@ import { JOB_STATE, DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/state import { Job } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -681,9 +681,9 @@ export default ({ getService }: FtrProviderContext) => { rspCode: number ) { const { body, status } = await supertest - .post(`/api/ml/modules/setup/${module}`) + .post(`/internal/ml/modules/setup/${module}`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(rqBody); ml.api.assertResponseStatusCode(rspCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts b/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts index fa3e12448be070..a066999a08b51b 100644 --- a/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts +++ b/x-pack/test/api_integration/apis/ml/notifications/count_notifications.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import moment from 'moment'; import type { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -19,10 +19,10 @@ export default ({ getService }: FtrProviderContext) => { describe('when no ML entities present', () => { it('return a default response', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications/count`) + .get(`/internal/ml/notifications/count`) .query({ lastCheckedAt: moment().subtract(7, 'd').valueOf() }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.info).to.eql(0); @@ -49,10 +49,10 @@ export default ({ getService }: FtrProviderContext) => { it('return notifications count by level', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications/count`) + .get(`/internal/ml/notifications/count`) .query({ lastCheckedAt: moment().subtract(7, 'd').valueOf() }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.info).to.eql(1); @@ -62,9 +62,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns an error for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications/count`) + .get(`/internal/ml/notifications/count`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts b/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts index 992065cdae67d9..e13f1869e66592 100644 --- a/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts +++ b/x-pack/test/api_integration/apis/ml/notifications/get_notifications.ts @@ -12,7 +12,7 @@ import type { } from '@kbn/ml-plugin/common/types/notifications'; import type { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -44,10 +44,10 @@ export default ({ getService }: FtrProviderContext) => { it('return all notifications ', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications`) + .get(`/internal/ml/notifications`) .query({ earliest: 'now-1d', latest: 'now' }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect((body as NotificationsSearchResponse).total).to.eql(2); @@ -55,10 +55,10 @@ export default ({ getService }: FtrProviderContext) => { it('return notifications based on the query string', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications`) + .get(`/internal/ml/notifications`) .query({ earliest: 'now-1d', latest: 'now', queryString: 'job_type:anomaly_detector' }) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect((body as NotificationsSearchResponse).total).to.eql(1); @@ -71,10 +71,10 @@ export default ({ getService }: FtrProviderContext) => { it('supports sorting asc sorting by field', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications`) + .get(`/internal/ml/notifications`) .query({ earliest: 'now-1d', latest: 'now', sortField: 'job_id', sortDirection: 'asc' }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.results[0].job_id).to.eql('df_job'); @@ -82,10 +82,10 @@ export default ({ getService }: FtrProviderContext) => { it('supports sorting desc sorting by field', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications`) + .get(`/internal/ml/notifications`) .query({ earliest: 'now-1h', latest: 'now', sortField: 'job_id', sortDirection: 'desc' }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.results[0].job_id).to.eql('fq_job'); @@ -93,9 +93,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns an error for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/notifications`) + .get(`/internal/ml/notifications`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/ml/results/get_anomalies_table_data.ts b/x-pack/test/api_integration/apis/ml/results/get_anomalies_table_data.ts index 547d1bc469a114..5cff7bca0981bd 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_anomalies_table_data.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_anomalies_table_data.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Datafeed, Job } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { USER } from '../../../../functional/services/ml/security_common'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -73,9 +73,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/results/anomalies_table_data`) + .post(`/internal/ml/results/anomalies_table_data`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -98,9 +98,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/results/anomalies_table_data`) + .post(`/internal/ml/results/anomalies_table_data`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(400, status, body); @@ -123,9 +123,9 @@ export default ({ getService }: FtrProviderContext) => { maxRecords: 500, }; const { body, status } = await supertest - .post(`/api/ml/results/anomalies_table_data`) + .post(`/internal/ml/results/anomalies_table_data`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/results/get_anomaly_search.ts b/x-pack/test/api_integration/apis/ml/results/get_anomaly_search.ts index 67202d6d903fac..5cfe728abb8b7a 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_anomaly_search.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_anomaly_search.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -41,9 +41,9 @@ export default ({ getService }: FtrProviderContext) => { user: USER ) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/results/anomaly_search`) + .post(`/s/${space}/internal/ml/results/anomaly_search`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/results/get_categorizer_stats.ts b/x-pack/test/api_integration/apis/ml/results/get_categorizer_stats.ts index 92b2fe2a1401ff..9c0add9e6be9cb 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_categorizer_stats.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_categorizer_stats.ts @@ -10,7 +10,7 @@ import { Datafeed } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import type { MlAnomalyCategorizerStatsDoc } from '@kbn/ml-anomaly-utils'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -66,9 +66,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all the categorizer stats for job id', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); body.forEach((doc: MlAnomalyCategorizerStatsDoc) => { @@ -81,9 +81,9 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch categorizer stats for job id for user with view permission', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); body.forEach((doc: MlAnomalyCategorizerStatsDoc) => { @@ -96,9 +96,9 @@ export default ({ getService }: FtrProviderContext) => { it('should not fetch categorizer stats for job id for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.be('Forbidden'); @@ -107,10 +107,10 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all the categorizer stats with per-partition value for job id', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .query({ partitionByValue: 'sample_web_logs' }) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); body.forEach((doc: MlAnomalyCategorizerStatsDoc) => { @@ -123,10 +123,10 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch categorizer stats with per-partition value for user with view permission', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .query({ partitionByValue: 'sample_web_logs' }) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); body.forEach((doc: MlAnomalyCategorizerStatsDoc) => { @@ -139,10 +139,10 @@ export default ({ getService }: FtrProviderContext) => { it('should not fetch categorizer stats with per-partition value for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/results/${jobId}/categorizer_stats`) + .get(`/internal/ml/results/${jobId}/categorizer_stats`) .query({ partitionByValue: 'sample_web_logs' }) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.be('Forbidden'); diff --git a/x-pack/test/api_integration/apis/ml/results/get_category_definition.ts b/x-pack/test/api_integration/apis/ml/results/get_category_definition.ts index a349c799e1763d..09ce02a3538e2b 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_category_definition.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_category_definition.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Datafeed } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -67,9 +67,9 @@ export default ({ getService }: FtrProviderContext) => { space?: string ) { const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/results/category_definition`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/results/category_definition`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobId, categoryId }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/results/get_category_examples.ts b/x-pack/test/api_integration/apis/ml/results/get_category_examples.ts index 6b0a0823faacaf..9b906bf46b6dae 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_category_examples.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_category_examples.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Datafeed } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -68,9 +68,9 @@ export default ({ getService }: FtrProviderContext) => { space?: string ) { const { body, status } = await supertest - .post(`${space ? `/s/${space}` : ''}/api/ml/results/category_examples`) + .post(`${space ? `/s/${space}` : ''}/internal/ml/results/category_examples`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ jobId, categoryIds, maxExamples }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/results/get_datafeed_results_chart.ts b/x-pack/test/api_integration/apis/ml/results/get_datafeed_results_chart.ts index b50676b8591efd..07e544fd1ec2c9 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_datafeed_results_chart.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_datafeed_results_chart.ts @@ -10,7 +10,7 @@ import { Datafeed, Job } from '@kbn/ml-plugin/common/types/anomaly_detection_job import { ANNOTATION_TYPE } from '@kbn/ml-plugin/common/constants/annotations'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -79,9 +79,9 @@ export default ({ getService }: FtrProviderContext) => { it('it should fetch datafeed chart data', async () => { const { body, status } = await supertest - .post(`/api/ml/results/datafeed_results_chart`) + .post(`/internal/ml/results/datafeed_results_chart`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); @@ -99,9 +99,9 @@ export default ({ getService }: FtrProviderContext) => { }; const { body, status } = await supertest - .post(`/api/ml/results/datafeed_results_chart`) + .post(`/internal/ml/results/datafeed_results_chart`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(incompleteRequestBody); ml.api.assertResponseStatusCode(400, status, body); @@ -113,9 +113,9 @@ export default ({ getService }: FtrProviderContext) => { it('it should not allow fetching of datafeed chart data without required permissions', async () => { const { body, status } = await supertest - .post(`/api/ml/results/datafeed_results_chart`) + .post(`/internal/ml/results/datafeed_results_chart`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(403, status, body); diff --git a/x-pack/test/api_integration/apis/ml/results/get_partition_fields_values.ts b/x-pack/test/api_integration/apis/ml/results/get_partition_fields_values.ts index 6e2ca3b06c4c18..cdb6b1df28c9ef 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_partition_fields_values.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_partition_fields_values.ts @@ -10,7 +10,7 @@ import { Datafeed, Job } from '@kbn/ml-plugin/common/types/anomaly_detection_job import type { PartitionFieldValueResponse } from '@kbn/ml-plugin/server/models/results_service/get_partition_fields_values'; import { USER } from '../../../../functional/services/ml/security_common'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -61,9 +61,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(requestBody: object): Promise { const { body, status } = await supertest - .post(`/api/ml/results/partition_fields_values`) + .post(`/internal/ml/results/partition_fields_values`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(200, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/results/get_stopped_partitions.ts b/x-pack/test/api_integration/apis/ml/results/get_stopped_partitions.ts index f676ab68e7806c..d7221412823281 100644 --- a/x-pack/test/api_integration/apis/ml/results/get_stopped_partitions.ts +++ b/x-pack/test/api_integration/apis/ml/results/get_stopped_partitions.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Datafeed, Job } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -103,10 +103,10 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch all the stopped partitions correctly', async () => { const { jobId } = testSetUps[0]; const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) .send({ jobIds: [jobId] }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.jobs).to.not.be(undefined); @@ -117,10 +117,10 @@ export default ({ getService }: FtrProviderContext) => { it('should not return jobId in response if stopped_on_warn is false', async () => { const { jobId } = testSetUps[1]; const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) .send({ jobIds: [jobId] }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.jobs).to.not.be(undefined); @@ -130,10 +130,10 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch stopped partitions for user with view permission', async () => { const { jobId } = testSetUps[2]; const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) .send({ jobIds: [jobId] }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.jobs).to.not.be(undefined); @@ -145,10 +145,10 @@ export default ({ getService }: FtrProviderContext) => { const { jobId } = testSetUps[3]; const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) .send({ jobIds: [jobId] }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); expect(body.error).to.be('Forbidden'); @@ -157,10 +157,10 @@ export default ({ getService }: FtrProviderContext) => { it('should fetch stopped partitions for multiple job ids', async () => { const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) .send({ jobIds: testJobIds }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.jobs).to.not.be(undefined); @@ -175,10 +175,10 @@ export default ({ getService }: FtrProviderContext) => { it('should return array of jobIds with stopped_partitions for multiple job ids when bucketed by job_id', async () => { const { body, status } = await supertest - .post(`/api/ml/results/category_stopped_partitions`) + .post(`/internal/ml/results/category_stopped_partitions`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) .send({ jobIds: testJobIds, fieldToBucket: 'job_id' }) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.jobs).to.not.be(undefined); diff --git a/x-pack/test/api_integration/apis/ml/results/max_anomaly_score.ts b/x-pack/test/api_integration/apis/ml/results/max_anomaly_score.ts index c706ee0ff96ee5..cf0a145d71ea40 100644 --- a/x-pack/test/api_integration/apis/ml/results/max_anomaly_score.ts +++ b/x-pack/test/api_integration/apis/ml/results/max_anomaly_score.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { Datafeed, Job } from '@kbn/ml-plugin/common/types/anomaly_detection_jobs'; import { USER } from '../../../../functional/services/ml/security_common'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -47,9 +47,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(requestBody: object) { const { body, status } = await supertest - .post(`/api/ml/results/max_anomaly_score`) + .post(`/internal/ml/results/max_anomaly_score`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); return { body, status }; } diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_job.ts b/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_job.ts index c20348e63a0283..bce96de95a6439 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_job.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_job.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { MlSavedObjectType } from '@kbn/ml-plugin/common/types/saved_objects'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -32,10 +32,10 @@ export default ({ getService }: FtrProviderContext) => { .post( `${ space ? `/s/${space}` : '' - }/api/ml/saved_objects/can_delete_ml_space_aware_item/${mlSavedObjectType}` + }/internal/ml/saved_objects/can_delete_ml_space_aware_item/${mlSavedObjectType}` ) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ ids }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_trained_model.ts b/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_trained_model.ts index 53252ab4c5e4df..eeb07b1b67b2d6 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_trained_model.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/can_delete_trained_model.ts @@ -10,7 +10,7 @@ import { TrainedModelType } from '@kbn/ml-plugin/common/types/saved_objects'; import { PutTrainedModelConfig } from '@kbn/ml-plugin/common/types/trained_models'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; type ModelType = 'regression' | 'classification'; @@ -35,10 +35,10 @@ export default ({ getService }: FtrProviderContext) => { .post( `${ space ? `/s/${space}` : '' - }/api/ml/saved_objects/can_delete_ml_space_aware_item/${jobType}` + }/internal/ml/saved_objects/can_delete_ml_space_aware_item/${jobType}` ) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ ids }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/get_jobs_spaces.ts b/x-pack/test/api_integration/apis/ml/saved_objects/get_jobs_spaces.ts index 2aa2c7e13c4abd..df539b07e48957 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/get_jobs_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/get_jobs_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -25,9 +25,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(expectedStatusCode: number, user: USER) { const { body, status } = await supertest - .get(`/api/ml/saved_objects/jobs_spaces`) + .get(`/internal/ml/saved_objects/jobs_spaces`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/get_trained_model_spaces.ts b/x-pack/test/api_integration/apis/ml/saved_objects/get_trained_model_spaces.ts index 7f18b518d063bc..834d214a9bb059 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/get_trained_model_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/get_trained_model_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -23,9 +23,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(expectedStatusCode: number, user: USER) { const { body, status } = await supertest - .get(`/api/ml/saved_objects/trained_models_spaces`) + .get(`/internal/ml/saved_objects/trained_models_spaces`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/initialize_jobs.ts b/x-pack/test/api_integration/apis/ml/saved_objects/initialize_jobs.ts index 2507a011e2035d..39ea1aee4a10e5 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/initialize_jobs.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/initialize_jobs.ts @@ -10,7 +10,7 @@ import { sortBy } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -22,9 +22,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(user: USER, expectedStatusCode: number) { const { body, status } = await supertest - .get(`/api/ml/saved_objects/initialize`) + .get(`/internal/ml/saved_objects/initialize`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/initialize_trained_models.ts b/x-pack/test/api_integration/apis/ml/saved_objects/initialize_trained_models.ts index 26acb658fa32f3..bc7f4b100c28d4 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/initialize_trained_models.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/initialize_trained_models.ts @@ -11,7 +11,7 @@ import { sortBy } from 'lodash'; import { PutTrainedModelConfig } from '@kbn/ml-plugin/common/types/trained_models'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; type ModelType = 'regression' | 'classification'; @@ -31,9 +31,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(user: USER, expectedStatusCode: number) { const { body, status } = await supertest - .get(`/api/ml/saved_objects/initialize`) + .get(`/internal/ml/saved_objects/initialize`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/remove_from_current_space.ts b/x-pack/test/api_integration/apis/ml/saved_objects/remove_from_current_space.ts index 3e98c51ea047e8..44232ef2dd01bc 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/remove_from_current_space.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/remove_from_current_space.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { MlSavedObjectType } from '@kbn/ml-plugin/common/types/saved_objects'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -34,9 +34,9 @@ export default ({ getService }: FtrProviderContext) => { user: USER ) { const { body, status } = await supertest - .post(`/s/${space}/api/ml/saved_objects/remove_item_from_current_space`) + .post(`/s/${space}/internal/ml/saved_objects/remove_item_from_current_space`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/status.ts b/x-pack/test/api_integration/apis/ml/saved_objects/status.ts index ec5429193dd3fb..ff6ca3792de938 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/status.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/status.ts @@ -10,7 +10,7 @@ import { sortBy } from 'lodash'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -27,12 +27,12 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(expectedStatusCode: number) { const { body, status } = await supertest - .get(`/api/ml/saved_objects/status`) + .get(`/internal/ml/saved_objects/status`) .auth( USER.ML_VIEWER_ALL_SPACES, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER_ALL_SPACES) ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/sync_jobs.ts b/x-pack/test/api_integration/apis/ml/saved_objects/sync_jobs.ts index 8f2dda89a8ab59..2c1abcc7ab4190 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/sync_jobs.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/sync_jobs.ts @@ -10,7 +10,7 @@ import { cloneDeep } from 'lodash'; import { MlSavedObjectType } from '@kbn/ml-plugin/common/types/saved_objects'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -27,7 +27,7 @@ export default ({ getService }: FtrProviderContext) => { const { body, status } = await supertest .get(`/s/${idSpace1}/api/ml/saved_objects/sync`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('2023-05-15')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; @@ -39,9 +39,9 @@ export default ({ getService }: FtrProviderContext) => { expectedStatusCode: number ) { const { body, status } = await supertest - .post(`/s/${idSpace1}/api/ml/saved_objects/sync_check`) + .post(`/s/${idSpace1}/internal/ml/saved_objects/sync_check`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ mlSavedObjectType }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/sync_trained_models.ts b/x-pack/test/api_integration/apis/ml/saved_objects/sync_trained_models.ts index 220bea2393adaa..dfbe53851926b0 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/sync_trained_models.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/sync_trained_models.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { PutTrainedModelConfig } from '@kbn/ml-plugin/common/types/trained_models'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; type ModelType = 'regression' | 'classification'; @@ -30,7 +30,7 @@ export default ({ getService }: FtrProviderContext) => { const { body, status } = await supertest .get(`/s/${idSpace1}/api/ml/saved_objects/sync`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('2023-05-15')); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; @@ -38,9 +38,9 @@ export default ({ getService }: FtrProviderContext) => { async function runSyncCheckRequest(user: USER, expectedStatusCode: number) { const { body, status } = await supertest - .post(`/s/${idSpace1}/api/ml/saved_objects/sync_check`) + .post(`/s/${idSpace1}/internal/ml/saved_objects/sync_check`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ mlSavedObjectType: 'trained-model' }); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/update_jobs_spaces.ts b/x-pack/test/api_integration/apis/ml/saved_objects/update_jobs_spaces.ts index 452bce090eacff..cbe3c584e89ffd 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/update_jobs_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/update_jobs_spaces.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { JobType } from '@kbn/ml-plugin/common/types/saved_objects'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -34,9 +34,9 @@ export default ({ getService }: FtrProviderContext) => { user: USER ) { const { body, status } = await supertest - .post(`/api/ml/saved_objects/update_jobs_spaces`) + .post(`/internal/ml/saved_objects/update_jobs_spaces`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/saved_objects/update_trained_model_spaces.ts b/x-pack/test/api_integration/apis/ml/saved_objects/update_trained_model_spaces.ts index d8c764bf6535a2..69f5acdbcb03d7 100644 --- a/x-pack/test/api_integration/apis/ml/saved_objects/update_trained_model_spaces.ts +++ b/x-pack/test/api_integration/apis/ml/saved_objects/update_trained_model_spaces.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const ml = getService('ml'); @@ -30,9 +30,9 @@ export default ({ getService }: FtrProviderContext) => { user: USER ) { const { body, status } = await supertest - .post(`/api/ml/saved_objects/update_trained_models_spaces`) + .post(`/internal/ml/saved_objects/update_trained_models_spaces`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/system/capabilities.ts b/x-pack/test/api_integration/apis/ml/system/capabilities.ts index e48c312faad95a..98e154d46e41e0 100644 --- a/x-pack/test/api_integration/apis/ml/system/capabilities.ts +++ b/x-pack/test/api_integration/apis/ml/system/capabilities.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { MlCapabilitiesResponse } from '@kbn/ml-plugin/common/types/capabilities'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; const NUMBER_OF_CAPABILITIES = 38; @@ -20,9 +20,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(user: USER): Promise { const { body, status } = await supertest - .get(`/api/ml/ml_capabilities`) + .get(`/internal/ml/ml_capabilities`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/system/index_exists.ts b/x-pack/test/api_integration/apis/ml/system/index_exists.ts index 6cd68d82f0b88f..797ee2b80a7103 100644 --- a/x-pack/test/api_integration/apis/ml/system/index_exists.ts +++ b/x-pack/test/api_integration/apis/ml/system/index_exists.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); @@ -64,9 +64,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(user: USER, requestBody: object, expectedStatusCode: number) { const { body, status } = await supertest - .post('/api/ml/index_exists') + .post('/internal/ml/index_exists') .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); diff --git a/x-pack/test/api_integration/apis/ml/system/space_capabilities.ts b/x-pack/test/api_integration/apis/ml/system/space_capabilities.ts index 6ab935b501b8bf..8a26ed93a17bb4 100644 --- a/x-pack/test/api_integration/apis/ml/system/space_capabilities.ts +++ b/x-pack/test/api_integration/apis/ml/system/space_capabilities.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { MlCapabilitiesResponse } from '@kbn/ml-plugin/common/types/capabilities'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; import { USER } from '../../../../functional/services/ml/security_common'; const idSpaceWithMl = 'space_with_ml'; @@ -24,9 +24,9 @@ export default ({ getService }: FtrProviderContext) => { async function runRequest(user: USER, space?: string): Promise { const { body, status } = await supertest - .get(`${space ? `/s/${space}` : ''}/api/ml/ml_capabilities`) + .get(`${space ? `/s/${space}` : ''}/internal/ml/ml_capabilities`) .auth(user, ml.securityCommon.getPasswordForUser(user)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); return body; diff --git a/x-pack/test/api_integration/apis/ml/trained_models/delete_model.ts b/x-pack/test/api_integration/apis/ml/trained_models/delete_model.ts index 1f34dbe360276d..2f286506f913e0 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/delete_model.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/delete_model.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -28,41 +28,41 @@ export default ({ getService }: FtrProviderContext) => { it('deletes trained model by id', async () => { const { body: deleteResponseBody, status: deleteResponseStatus } = await supertest - .delete(`/api/ml/trained_models/dfa_regression_model_n_0`) + .delete(`/internal/ml/trained_models/dfa_regression_model_n_0`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, deleteResponseStatus, deleteResponseBody); expect(deleteResponseBody).to.eql({ acknowledged: true }); // verify that model is actually deleted const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_0`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_0`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); }); it('returns 404 if requested trained model does not exist', async () => { const { body, status } = await supertest - .delete(`/api/ml/trained_models/not_existing_model`) + .delete(`/internal/ml/trained_models/not_existing_model`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); }); it('does not allow to delete trained model if the user does not have required permissions', async () => { const { body: deleteResponseBody, status: deleteResponseStatus } = await supertest - .delete(`/api/ml/trained_models/dfa_regression_model_n_1`) + .delete(`/internal/ml/trained_models/dfa_regression_model_n_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, deleteResponseStatus, deleteResponseBody); // verify that model has not been deleted const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_1`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_1`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/ml/trained_models/get_model_pipelines.ts b/x-pack/test/api_integration/apis/ml/trained_models/get_model_pipelines.ts index 27859d850e1191..8d5fd0eaa7417e 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/get_model_pipelines.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/get_model_pipelines.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -30,9 +30,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns trained model pipelines by id', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_0/pipelines`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_0/pipelines`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.length).to.eql(1); @@ -42,9 +42,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns an error in case user does not have required permission', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_0/pipelines`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_0/pipelines`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/ml/trained_models/get_model_stats.ts b/x-pack/test/api_integration/apis/ml/trained_models/get_model_stats.ts index ea5e49619032ba..8d0ba0c0c36d95 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/get_model_stats.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/get_model_stats.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -26,9 +26,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns trained model stats by id', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_0/_stats`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_0/_stats`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.count).to.eql(1); @@ -37,17 +37,17 @@ export default ({ getService }: FtrProviderContext) => { it('returns 404 if requested trained model does not exist', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/not_existing_model/_stats`) + .get(`/internal/ml/trained_models/not_existing_model/_stats`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); }); it('returns an error for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_0/_stats`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_0/_stats`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/ml/trained_models/get_models.ts b/x-pack/test/api_integration/apis/ml/trained_models/get_models.ts index 28c82dabf88cd0..2633423b5855e8 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/get_models.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/get_models.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertestWithoutAuth'); @@ -38,9 +38,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns all trained models with associated pipelines including aliases', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models?with_pipelines=true`) + .get(`/internal/ml/trained_models?with_pipelines=true`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); // Created models + system model @@ -52,9 +52,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns models without pipeline in case user does not have required permission', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models?with_pipelines=true`) + .get(`/internal/ml/trained_models?with_pipelines=true`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); // Created models + system model @@ -65,9 +65,9 @@ export default ({ getService }: FtrProviderContext) => { it('returns trained model by id', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_1`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_1`) .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(200, status, body); expect(body.length).to.eql(1); @@ -76,17 +76,17 @@ export default ({ getService }: FtrProviderContext) => { it('returns 404 if requested trained model does not exist', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/not_existing_model`) + .get(`/internal/ml/trained_models/not_existing_model`) .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(404, status, body); }); it('returns an error for unauthorized user', async () => { const { body, status } = await supertest - .get(`/api/ml/trained_models/dfa_regression_model_n_1`) + .get(`/internal/ml/trained_models/dfa_regression_model_n_1`) .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); ml.api.assertResponseStatusCode(403, status, body); }); }); diff --git a/x-pack/test/api_integration/apis/transform/delete_transforms.ts b/x-pack/test/api_integration/apis/transform/delete_transforms.ts index 541418889970f7..ad65da8bdf7fd9 100644 --- a/x-pack/test/api_integration/apis/transform/delete_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/delete_transforms.ts @@ -10,7 +10,7 @@ import expect from '@kbn/expect'; import { DeleteTransformsRequestSchema } from '@kbn/transform-plugin/common/api_schemas/delete_transforms'; import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -60,7 +60,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -81,7 +81,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(403, status, body); @@ -101,7 +101,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -139,7 +139,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -163,7 +163,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send({ ...reqBody, transformsInfo: [ @@ -213,7 +213,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -252,7 +252,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -292,7 +292,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/transform/reauthorize_transforms.ts b/x-pack/test/api_integration/apis/transform/reauthorize_transforms.ts index a33ef09063d37a..eef58531cc5eaa 100644 --- a/x-pack/test/api_integration/apis/transform/reauthorize_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/reauthorize_transforms.ts @@ -9,7 +9,7 @@ import { ReauthorizeTransformsRequestSchema } from '@kbn/transform-plugin/common import expect from '@kbn/expect'; import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; import type { SecurityCreateApiKeyResponse } from '@elastic/elasticsearch/lib/api/types'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -27,7 +27,7 @@ export default ({ getService }: FtrProviderContext) => { function generateHeaders(apiKey: SecurityCreateApiKeyResponse) { return { - ...COMMON_REQUEST_HEADERS, + ...getCommonRequestHeader(), 'es-secondary-authorization': `ApiKey ${apiKey.encoded}`, }; } @@ -137,7 +137,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_UNAUTHORIZED, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_UNAUTHORIZED) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); expect(body[transformCreatedByViewerId].success).to.eql( @@ -157,7 +157,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); expect(body[transformCreatedByViewerId].success).to.eql( @@ -177,7 +177,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); expect(body[transformCreatedByViewerId].success).to.eql( @@ -206,7 +206,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -252,7 +252,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send([...reqBody, { id: invalidTransformId }]); transform.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/transform/reset_transforms.ts b/x-pack/test/api_integration/apis/transform/reset_transforms.ts index 4a219b2d2280a7..5bf2163c82adf3 100644 --- a/x-pack/test/api_integration/apis/transform/reset_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/reset_transforms.ts @@ -10,7 +10,7 @@ import expect from '@kbn/expect'; import { ResetTransformsRequestSchema } from '@kbn/transform-plugin/common/api_schemas/reset_transforms'; import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -78,7 +78,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -108,7 +108,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(403, status, body); @@ -132,7 +132,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -180,7 +180,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -219,7 +219,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send({ ...reqBody, transformsInfo: [ diff --git a/x-pack/test/api_integration/apis/transform/schedule_now_transforms.ts b/x-pack/test/api_integration/apis/transform/schedule_now_transforms.ts index 4573ec6d42ac0d..7962c6ccd380a1 100644 --- a/x-pack/test/api_integration/apis/transform/schedule_now_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/schedule_now_transforms.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { ScheduleNowTransformsRequestSchema } from '@kbn/transform-plugin/common/api_schemas/schedule_now_transforms'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -55,7 +55,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -71,7 +71,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -89,7 +89,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -129,7 +129,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -146,7 +146,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send([{ id: reqBody[0].id }, { id: invalidTransformId }, { id: reqBody[1].id }]); transform.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/transform/start_transforms.ts b/x-pack/test/api_integration/apis/transform/start_transforms.ts index 682003fc6b8252..a163064f1ea3c2 100644 --- a/x-pack/test/api_integration/apis/transform/start_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/start_transforms.ts @@ -10,7 +10,7 @@ import expect from '@kbn/expect'; import { StartTransformsRequestSchema } from '@kbn/transform-plugin/common/api_schemas/start_transforms'; import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -54,7 +54,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -72,7 +72,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -93,7 +93,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -129,7 +129,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -148,7 +148,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send([{ id: reqBody[0].id }, { id: invalidTransformId }, { id: reqBody[1].id }]); transform.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/transform/stop_transforms.ts b/x-pack/test/api_integration/apis/transform/stop_transforms.ts index 302e53e1fbbaef..c2ae1079687cf2 100644 --- a/x-pack/test/api_integration/apis/transform/stop_transforms.ts +++ b/x-pack/test/api_integration/apis/transform/stop_transforms.ts @@ -13,7 +13,7 @@ import { isStopTransformsResponseSchema } from '@kbn/transform-plugin/common/api import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -72,7 +72,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -93,7 +93,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -117,7 +117,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -154,7 +154,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(reqBody); transform.api.assertResponseStatusCode(200, status, body); @@ -175,7 +175,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send([ { id: reqBody[0].id, state: reqBody[0].state }, { id: invalidTransformId, state: TRANSFORM_STATE.STOPPED }, diff --git a/x-pack/test/api_integration/apis/transform/transforms.ts b/x-pack/test/api_integration/apis/transform/transforms.ts index 88c9929f8ed730..402234ae31c53f 100644 --- a/x-pack/test/api_integration/apis/transform/transforms.ts +++ b/x-pack/test/api_integration/apis/transform/transforms.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import type { GetTransformsResponseSchema } from '@kbn/transform-plugin/common/api_schemas/transforms'; import { isGetTransformsResponseSchema } from '@kbn/transform-plugin/common/api_schemas/type_guards'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -100,7 +100,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -114,7 +114,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -130,7 +130,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -144,7 +144,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -158,7 +158,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(404, status, body); }); diff --git a/x-pack/test/api_integration/apis/transform/transforms_create.ts b/x-pack/test/api_integration/apis/transform/transforms_create.ts index 512bd16969e2df..736cd8c2c21de4 100644 --- a/x-pack/test/api_integration/apis/transform/transforms_create.ts +++ b/x-pack/test/api_integration/apis/transform/transforms_create.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { generateTransformConfig } from './common'; @@ -36,7 +36,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send({ ...generateTransformConfig(transformId), latest: { @@ -60,7 +60,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(config); transform.api.assertResponseStatusCode(400, status, body); diff --git a/x-pack/test/api_integration/apis/transform/transforms_nodes.ts b/x-pack/test/api_integration/apis/transform/transforms_nodes.ts index 98ed88375c62a4..ea1285c2ef0c8b 100644 --- a/x-pack/test/api_integration/apis/transform/transforms_nodes.ts +++ b/x-pack/test/api_integration/apis/transform/transforms_nodes.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import type { GetTransformNodesResponseSchema } from '@kbn/transform-plugin/common/api_schemas/transforms'; import { isGetTransformNodesResponseSchema } from '@kbn/transform-plugin/common/api_schemas/type_guards'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -38,7 +38,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -52,7 +52,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -66,7 +66,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_UNAUTHORIZED, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_UNAUTHORIZED) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(403, status, body); }); diff --git a/x-pack/test/api_integration/apis/transform/transforms_preview.ts b/x-pack/test/api_integration/apis/transform/transforms_preview.ts index 6b1f636e051c6a..9c292f15b1e1ee 100644 --- a/x-pack/test/api_integration/apis/transform/transforms_preview.ts +++ b/x-pack/test/api_integration/apis/transform/transforms_preview.ts @@ -10,7 +10,7 @@ import expect from '@kbn/expect'; import type { PostTransformsPreviewRequestSchema } from '@kbn/transform-plugin/common/api_schemas/transforms'; import { FtrProviderContext } from '../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { generateTransformConfig } from './common'; @@ -49,7 +49,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(getTransformPreviewConfig()); transform.api.assertResponseStatusCode(200, status, body); @@ -66,7 +66,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send({ ...getTransformPreviewConfig(), pivot: { @@ -90,7 +90,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(getTransformPreviewConfig()); transform.api.assertResponseStatusCode(403, status, body); }); diff --git a/x-pack/test/api_integration/apis/transform/transforms_stats.ts b/x-pack/test/api_integration/apis/transform/transforms_stats.ts index 6343a2c9f002fc..27dea00d558f64 100644 --- a/x-pack/test/api_integration/apis/transform/transforms_stats.ts +++ b/x-pack/test/api_integration/apis/transform/transforms_stats.ts @@ -11,7 +11,7 @@ import type { GetTransformsStatsResponseSchema } from '@kbn/transform-plugin/com import { isGetTransformsStatsResponseSchema } from '@kbn/transform-plugin/common/api_schemas/type_guards'; import { TRANSFORM_STATE } from '@kbn/transform-plugin/common/constants'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -79,7 +79,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); @@ -93,7 +93,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, status, body); diff --git a/x-pack/test/api_integration/apis/transform/transforms_update.ts b/x-pack/test/api_integration/apis/transform/transforms_update.ts index f08dd282bed011..647972a497a748 100644 --- a/x-pack/test/api_integration/apis/transform/transforms_update.ts +++ b/x-pack/test/api_integration/apis/transform/transforms_update.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -import { COMMON_REQUEST_HEADERS } from '../../../functional/services/ml/common_api'; +import { getCommonRequestHeader } from '../../../functional/services/ml/common_api'; import { USER } from '../../../functional/services/transform/security_common'; import { generateTransformConfig } from './common'; @@ -76,7 +76,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, transformOriginalStatus, transformOriginalBody); @@ -99,7 +99,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(getTransformUpdateConfig()); transform.api.assertResponseStatusCode( 200, @@ -123,7 +123,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_POWERUSER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_POWERUSER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(); transform.api.assertResponseStatusCode(200, transformUpdatedStatus, transformUpdatedBody); @@ -149,7 +149,7 @@ export default ({ getService }: FtrProviderContext) => { USER.TRANSFORM_VIEWER, transform.securityCommon.getPasswordForUser(USER.TRANSFORM_VIEWER) ) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader()) .send(getTransformUpdateConfig()); transform.api.assertResponseStatusCode(403, status, body); }); diff --git a/x-pack/test/detection_engine_api_integration/utils/machine_learning_setup.ts b/x-pack/test/detection_engine_api_integration/utils/machine_learning_setup.ts index b376df9407c4bc..84eeeea137cb0b 100644 --- a/x-pack/test/detection_engine_api_integration/utils/machine_learning_setup.ts +++ b/x-pack/test/detection_engine_api_integration/utils/machine_learning_setup.ts @@ -17,7 +17,7 @@ export const executeSetupModuleRequest = async ({ supertest: SuperTest.SuperTest; }) => { const { body } = await supertest - .post(`/api/ml/modules/setup/${module}`) + .post(`/internal/ml/modules/setup/${module}`) .set('kbn-xsrf', 'true') .send({ prefix: '', @@ -42,7 +42,7 @@ export const forceStartDatafeeds = async ({ supertest: SuperTest.SuperTest; }) => { const { body } = await supertest - .post(`/api/ml/jobs/force_start_datafeeds`) + .post(`/supertest/ml/jobs/force_start_datafeeds`) .set('kbn-xsrf', 'true') .send({ datafeedIds: [`datafeed-${jobId}`], diff --git a/x-pack/test/functional/apps/transform/actions/reauthorizing.ts b/x-pack/test/functional/apps/transform/actions/reauthorizing.ts index 89acef449c2e7c..f3a68ae35df8bd 100644 --- a/x-pack/test/functional/apps/transform/actions/reauthorizing.ts +++ b/x-pack/test/functional/apps/transform/actions/reauthorizing.ts @@ -14,7 +14,7 @@ import type { SecurityCreateApiKeyResponse } from '@elastic/elasticsearch/lib/ap import type { FtrProviderContext } from '../../../ftr_provider_context'; import { getLatestTransformConfig, getPivotTransformConfig } from '../helpers'; import { USER } from '../../../services/transform/security_common'; -import { COMMON_REQUEST_HEADERS } from '../../../services/ml/common_api'; +import { getCommonRequestHeader } from '../../../services/ml/common_api'; interface TestDataPivot { suiteTitle: string; @@ -48,7 +48,7 @@ type TestData = TestDataPivot | TestDataLatest; function generateHeaders(apiKey: SecurityCreateApiKeyResponse) { return { - ...COMMON_REQUEST_HEADERS, + ...getCommonRequestHeader(), 'es-secondary-authorization': `ApiKey ${apiKey.encoded}`, }; } diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 69544632d088a8..f50df8fcf557c7 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -24,7 +24,7 @@ import { ML_ANNOTATIONS_INDEX_ALIAS_WRITE, } from '@kbn/ml-plugin/common/constants/index_patterns'; import { PutTrainedModelConfig } from '@kbn/ml-plugin/common/types/trained_models'; -import { COMMON_REQUEST_HEADERS } from './common_api'; +import { getCommonRequestHeader } from './common_api'; import { FtrProviderContext } from '../../ftr_provider_context'; export type MlApi = ProvidedType; @@ -680,8 +680,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { ); const { body, status } = await kbnSupertest - .put(`${space ? `/s/${space}` : ''}/api/ml/anomaly_detectors/${jobId}`) - .set(COMMON_REQUEST_HEADERS) + .put(`${space ? `/s/${space}` : ''}/internal/ml/anomaly_detectors/${jobId}`) + .set(getCommonRequestHeader('1')) .send(jobConfig); this.assertResponseStatusCode(200, status, body); @@ -765,8 +765,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { `Creating datafeed with id '${datafeedId}' ${space ? `in space '${space}' ` : ''}...` ); const { body, status } = await kbnSupertest - .put(`${space ? `/s/${space}` : ''}/api/ml/datafeeds/${datafeedId}`) - .set(COMMON_REQUEST_HEADERS) + .put(`${space ? `/s/${space}` : ''}/internal/ml/datafeeds/${datafeedId}`) + .set(getCommonRequestHeader('1')) .send(datafeedConfig); this.assertResponseStatusCode(200, status, body); @@ -918,8 +918,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }...` ); const { body, status } = await kbnSupertest - .put(`${space ? `/s/${space}` : ''}/api/ml/data_frame/analytics/${analyticsId}`) - .set(COMMON_REQUEST_HEADERS) + .put(`${space ? `/s/${space}` : ''}/internal/ml/data_frame/analytics/${analyticsId}`) + .set(getCommonRequestHeader('1')) .send(analyticsConfig); this.assertResponseStatusCode(200, status, body); @@ -932,7 +932,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { log.debug(`Creating data frame analytic job with id '${analyticsId}' via ES API...`); const { body, status } = await esSupertest .put(`/_ml/data_frame/analytics/${analyticsId}`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(analyticsConfig); this.assertResponseStatusCode(200, status, body); @@ -1177,8 +1177,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { space?: string ) { const { body, status } = await kbnSupertest - .post(`${space ? `/s/${space}` : ''}/api/ml/saved_objects/update_jobs_spaces`) - .set(COMMON_REQUEST_HEADERS) + .post(`${space ? `/s/${space}` : ''}/internal/ml/saved_objects/update_jobs_spaces`) + .set(getCommonRequestHeader('1')) .send({ jobType, jobIds: [jobId], spacesToAdd, spacesToRemove }); this.assertResponseStatusCode(200, status, body); @@ -1187,8 +1187,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async assertJobSpaces(jobId: string, jobType: JobType, expectedSpaces: string[]) { const { body, status } = await kbnSupertest - .get('/api/ml/saved_objects/jobs_spaces') - .set(COMMON_REQUEST_HEADERS); + .get('/internal/ml/saved_objects/jobs_spaces') + .set(getCommonRequestHeader('1')); this.assertResponseStatusCode(200, status, body); if (expectedSpaces.length > 0) { @@ -1212,8 +1212,10 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { space?: string ) { const { body, status } = await kbnSupertest - .post(`${space ? `/s/${space}` : ''}/api/ml/saved_objects/update_trained_models_spaces`) - .set(COMMON_REQUEST_HEADERS) + .post( + `${space ? `/s/${space}` : ''}/internal/ml/saved_objects/update_trained_models_spaces` + ) + .set(getCommonRequestHeader('1')) .send({ modelIds: [modelId], spacesToAdd, spacesToRemove }); this.assertResponseStatusCode(200, status, body); @@ -1224,8 +1226,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async assertTrainedModelSpaces(modelId: string, expectedSpaces: string[]) { const { body, status } = await kbnSupertest - .get('/api/ml/saved_objects/trained_models_spaces') - .set(COMMON_REQUEST_HEADERS); + .get('/internal/ml/saved_objects/trained_models_spaces') + .set(getCommonRequestHeader('1')); this.assertResponseStatusCode(200, status, body); if (expectedSpaces.length > 0) { // Should list expected spaces correctly @@ -1244,7 +1246,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async syncSavedObjects(simulate: boolean = false, space?: string) { const { body, status } = await kbnSupertest .get(`${space ? `/s/${space}` : ''}/api/ml/saved_objects/sync?simulate=${simulate}`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('2023-05-15')); this.assertResponseStatusCode(200, status, body); return body; @@ -1252,8 +1254,10 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async initSavedObjects(simulate: boolean = false, space?: string) { const { body, status } = await kbnSupertest - .get(`${space ? `/s/${space}` : ''}/api/ml/saved_objects/initialize?simulate=${simulate}`) - .set(COMMON_REQUEST_HEADERS); + .get( + `${space ? `/s/${space}` : ''}/internal/ml/saved_objects/initialize?simulate=${simulate}` + ) + .set(getCommonRequestHeader('1')); this.assertResponseStatusCode(200, status, body); return body; }, @@ -1261,8 +1265,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async createTrainedModel(modelId: string, body: PutTrainedModelConfig, space?: string) { log.debug(`Creating trained model with id "${modelId}"`); const { body: model, status } = await kbnSupertest - .put(`${space ? `/s/${space}` : ''}/api/ml/trained_models/${modelId}`) - .set(COMMON_REQUEST_HEADERS) + .put(`${space ? `/s/${space}` : ''}/internal/ml/trained_models/${modelId}`) + .set(getCommonRequestHeader('1')) .send(body); this.assertResponseStatusCode(200, status, model); @@ -1498,8 +1502,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { ) { log.debug(`Setting up module with ID: "${moduleId}"`); const { body: module, status } = await kbnSupertest - .post(`${space ? `/s/${space}` : ''}/api/ml/modules/setup/${moduleId}`) - .set(COMMON_REQUEST_HEADERS) + .post(`${space ? `/s/${space}` : ''}/internal/ml/modules/setup/${moduleId}`) + .set(getCommonRequestHeader('1')) .send(body); this.assertResponseStatusCode(200, status, module); diff --git a/x-pack/test/functional/services/ml/common_api.ts b/x-pack/test/functional/services/ml/common_api.ts index 02cfecfc5208fe..36529dceb118f0 100644 --- a/x-pack/test/functional/services/ml/common_api.ts +++ b/x-pack/test/functional/services/ml/common_api.ts @@ -9,7 +9,7 @@ import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; -export const COMMON_REQUEST_HEADERS = { +const COMMON_REQUEST_HEADERS = { 'kbn-xsrf': 'some-xsrf-token', }; @@ -17,8 +17,14 @@ export type MlCommonAPI = ProvidedType; export function MachineLearningCommonAPIProvider({}: FtrProviderContext) { return { - async getCommonRequestHeader() { - return COMMON_REQUEST_HEADERS; - }, + getCommonRequestHeader, }; } + +export function getCommonRequestHeader(apiVersion?: string) { + if (apiVersion === undefined) { + return COMMON_REQUEST_HEADERS; + } + + return Object.assign(COMMON_REQUEST_HEADERS, { 'elastic-api-version': apiVersion }); +} diff --git a/x-pack/test/functional/services/ml/test_resources.ts b/x-pack/test/functional/services/ml/test_resources.ts index 03cf56c3322ad9..e8fb9b4e8a1525 100644 --- a/x-pack/test/functional/services/ml/test_resources.ts +++ b/x-pack/test/functional/services/ml/test_resources.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { ProvidedType } from '@kbn/test'; import { JobType } from '@kbn/ml-plugin/common/types/saved_objects'; import { savedSearches, dashboards } from './test_resources_data'; -import { COMMON_REQUEST_HEADERS } from './common_api'; +import { getCommonRequestHeader } from './common_api'; import { MlApi } from './api'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -88,7 +88,7 @@ export function MachineLearningTestResourcesProvider( .get( `${space ? `/s/${space}` : ''}/api/saved_objects/_find?type=${objectType}&per_page=10000` ) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, findResponse); for (const savedObject of findResponse.saved_objects) { @@ -107,7 +107,7 @@ export function MachineLearningTestResourcesProvider( log.debug(`Searching for '${objectType}' ...`); const { body: findResponse, status } = await supertest .get(`/api/saved_objects/_find?type=${objectType}&per_page=10000`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, findResponse); findResponse.saved_objects.forEach((element: any) => { @@ -146,7 +146,7 @@ export function MachineLearningTestResourcesProvider( const { body: createResponse, status } = await supertest .post(`${space ? `/s/${space}` : ''}/api/saved_objects/${SavedObjectType.INDEX_PATTERN}`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send({ attributes: { title, timeFieldName } }); mlApi.assertResponseStatusCode(200, status, createResponse); @@ -161,7 +161,7 @@ export function MachineLearningTestResourcesProvider( const { body: createResponse, status } = await supertest .post(`/api/saved_objects/_bulk_create`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(body); mlApi.assertResponseStatusCode(200, status, createResponse); @@ -192,7 +192,7 @@ export function MachineLearningTestResourcesProvider( const { body: createResponse, status } = await supertest .post(`/api/saved_objects/${SavedObjectType.SEARCH}`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(body); mlApi.assertResponseStatusCode(200, status, createResponse); @@ -207,7 +207,7 @@ export function MachineLearningTestResourcesProvider( const { body: createResponse, status } = await supertest .post(`/api/saved_objects/${SavedObjectType.DASHBOARD}`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .send(body); mlApi.assertResponseStatusCode(200, status, createResponse); @@ -336,7 +336,7 @@ export function MachineLearningTestResourcesProvider( } else { const { body, status } = await supertest .delete(`${space ? `/s/${space}` : ''}/api/saved_objects/${objectType}/${id}`) - .set(COMMON_REQUEST_HEADERS) + .set(getCommonRequestHeader('1')) .query({ force }); mlApi.assertResponseStatusCode(200, status, body); @@ -557,7 +557,7 @@ export function MachineLearningTestResourcesProvider( await retry.tryForTime(2 * 60 * 1000, async () => { const { body, status } = await supertest .post(`/api/fleet/setup`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, body); }); log.debug(` > Setup done`); @@ -571,7 +571,7 @@ export function MachineLearningTestResourcesProvider( await retry.tryForTime(30 * 1000, async () => { const { body, status } = await supertest .post(`/api/fleet/epm/packages/${packageName}/${version}`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, body); }); @@ -585,7 +585,7 @@ export function MachineLearningTestResourcesProvider( await retry.tryForTime(30 * 1000, async () => { const { body, status } = await supertest .delete(`/api/fleet/epm/packages/${packageName}/${version}`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, body); }); @@ -599,7 +599,7 @@ export function MachineLearningTestResourcesProvider( await retry.tryForTime(10 * 1000, async () => { const { body, status } = await supertest .get(`/api/fleet/epm/packages?experimental=true`) - .set(COMMON_REQUEST_HEADERS); + .set(getCommonRequestHeader('1')); mlApi.assertResponseStatusCode(200, status, body); packageVersion =