From 731551376718e2f5158a5a4843ef19c72fb365e2 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 14:32:16 -0700 Subject: [PATCH 01/25] simplify serverfacade definition --- .../reporting/server/lib/once_per_server.ts | 4 ---- x-pack/legacy/plugins/reporting/types.d.ts | 15 ++++++++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/once_per_server.ts b/x-pack/legacy/plugins/reporting/server/lib/once_per_server.ts index d73a5b73fecd0..ae3636079a9bb 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/once_per_server.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/once_per_server.ts @@ -27,10 +27,6 @@ export function oncePerServer(fn: ServerFn) { throw new TypeError('This function expects to be called with a single argument'); } - if (!server || typeof server.expose !== 'function') { - throw new TypeError('This function expects to be passed the server'); - } - // @ts-ignore return fn.call(this, server); }); diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index c17b969d5d7fa..9239f0020d272 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -74,13 +74,22 @@ interface DownloadParams { export type ReportingPluginSpecOptions = Legacy.PluginSpecOptions; -export type ServerFacade = Legacy.Server & { +type LegacyPlugins = Legacy.Server['plugins']; + +export interface ServerFacade { + config: Legacy.Server['config']; + info: Legacy.Server['info']; + newPlatform: Legacy.Server['newPlatform']; plugins: { - xpack_main?: XPackMainPlugin & { + elasticsearch: LegacyPlugins['elasticsearch']; + xpack_main: XPackMainPlugin & { status?: any; }; }; -}; + route: Legacy.Server['route']; + savedObjects: Legacy.Server['savedObjects']; + uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; +} interface ReportingRequest { query: ListQuery & GenerateQuery; From d954ef0ad77f01ab02cc05fa580851d014eea4c8 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 14:35:07 -0700 Subject: [PATCH 02/25] simplify requestfacade definition --- x-pack/legacy/plugins/reporting/types.d.ts | 31 +++++++++++----------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 9239f0020d272..a63f675312b7e 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -64,9 +64,6 @@ interface GenerateQuery { interface GenerateExportTypePayload { jobParams: string; } -interface DownloadParams { - docId: string; -} /* * Legacy System @@ -79,6 +76,7 @@ type LegacyPlugins = Legacy.Server['plugins']; export interface ServerFacade { config: Legacy.Server['config']; info: Legacy.Server['info']; + log: Legacy.Server['log']; newPlatform: Legacy.Server['newPlatform']; plugins: { elasticsearch: LegacyPlugins['elasticsearch']; @@ -91,18 +89,6 @@ export interface ServerFacade { uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; } -interface ReportingRequest { - query: ListQuery & GenerateQuery; - params: DownloadParams; - payload: GenerateExportTypePayload; - pre: { - management: { - jobTypes: any; - }; - user: any; - }; -} - export type EnqueueJobFn = ( parentLogger: LevelLogger, exportTypeId: string, @@ -112,7 +98,20 @@ export type EnqueueJobFn = ( request: RequestFacade ) => Promise; -export type RequestFacade = ReportingRequest & Legacy.Request; +export interface RequestFacade { + getBasePath: Legacy.Request['getBasePath']; + getSavedObjectsClient: Legacy.Request['getSavedObjectsClient']; + headers: Legacy.Request['headers']; + params: Legacy.Request['params']; + query: ListQuery & GenerateQuery; + payload: JobParamPostPayload | GenerateExportTypePayload; + pre: { + management: { + jobTypes: any; + }; + user: any; + }; +} export type ResponseFacade = ResponseObject & { isBoom: boolean; From bb6524517148b93a90ca5d7d2b072451bcb600d2 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 16:19:17 -0700 Subject: [PATCH 03/25] makeRequestFacade --- .../server/routes/generate_from_jobparams.ts | 4 +- .../routes/generate_from_savedobject.ts | 4 +- .../generate_from_savedobject_immediate.ts | 6 ++- .../reporting/server/routes/generation.ts | 4 +- .../plugins/reporting/server/routes/jobs.ts | 39 ++++++++++++------- .../server/routes/lib/make_request_facade.ts | 19 +++++++++ 6 files changed, 56 insertions(+), 20 deletions(-) create mode 100644 x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts index 128cc44db4dc4..0066399ebe758 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts @@ -14,6 +14,7 @@ import { GetRouteConfigFactoryFn, RouteConfigFactory, } from './lib/route_config_factories'; +import { makeRequestFacade } from './lib/make_request_facade'; import { HandlerErrorFunction, HandlerFunction } from './types'; const BASE_GENERATE = `${API_BASE_URL}/generate`; @@ -54,7 +55,8 @@ export function registerGenerateFromJobParams( path: `${BASE_GENERATE}/{exportType}`, method: 'POST', options: getRouteConfig(), - handler: async (request: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(originalRequest); let jobParamsRison: string | null; if (request.payload) { diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts index 72c8055614065..c87d22a716ea4 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts @@ -9,6 +9,7 @@ import { API_BASE_GENERATE_V1, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../commo import { ServerFacade, RequestFacade, ReportingResponseToolkit } from '../../types'; import { HandlerErrorFunction, HandlerFunction, QueuedJobPayload } from './types'; import { getRouteOptionsCsv } from './lib/route_config_factories'; +import { makeRequestFacade } from './lib/make_request_facade'; import { getJobParamsFromRequest } from '../../export_types/csv_from_savedobject/server/lib/get_job_params_from_request'; /* @@ -31,7 +32,8 @@ export function registerGenerateCsvFromSavedObject( path: `${API_BASE_GENERATE_V1}/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (request: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(originalRequest); /* * 1. Build `jobParams` object: job data that execution will need to reference in various parts of the lifecycle * 2. Pass the jobParams and other common params to `handleRoute`, a shared function to enqueue the job with the params diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts index bc96c27f64c10..a7ec4d69c55bc 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts @@ -16,8 +16,9 @@ import { JobDocOutputExecuted, } from '../../types'; import { JobDocPayloadPanelCsv } from '../../export_types/csv_from_savedobject/types'; -import { getRouteOptionsCsv } from './lib/route_config_factories'; import { getJobParamsFromRequest } from '../../export_types/csv_from_savedobject/server/lib/get_job_params_from_request'; +import { getRouteOptionsCsv } from './lib/route_config_factories'; +import { makeRequestFacade } from './lib/make_request_facade'; /* * This function registers API Endpoints for immediate Reporting jobs. The API inputs are: @@ -43,7 +44,8 @@ export function registerGenerateCsvFromSavedObjectImmediate( path: `${API_BASE_GENERATE_V1}/immediate/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (request: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(originalRequest); const logger = parentLogger.clone(['savedobject-csv']); const jobParams = getJobParamsFromRequest(request, { isImmediate: true }); diff --git a/x-pack/legacy/plugins/reporting/server/routes/generation.ts b/x-pack/legacy/plugins/reporting/server/routes/generation.ts index 73450b7641c8e..2a3a87e69aa49 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generation.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generation.ts @@ -18,6 +18,7 @@ import { registerGenerateFromJobParams } from './generate_from_jobparams'; import { registerGenerateCsvFromSavedObject } from './generate_from_savedobject'; import { registerGenerateCsvFromSavedObjectImmediate } from './generate_from_savedobject_immediate'; import { createQueueFactory, enqueueJobFactory } from '../lib'; +import { makeRequestFacade } from './lib/make_request_facade'; export function registerJobGenerationRoutes( server: ServerFacade, @@ -39,9 +40,10 @@ export function registerJobGenerationRoutes( async function handler( exportTypeId: string, jobParams: object, - request: RequestFacade, + originalRequest: RequestFacade, h: ReportingResponseToolkit ) { + const request = makeRequestFacade(originalRequest); const user = request.pre.user; const headers = request.headers; diff --git a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts index fd5014911d262..d039845380165 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts @@ -23,6 +23,7 @@ import { getRouteConfigFactoryDownloadPre, getRouteConfigFactoryManagementPre, } from './lib/route_config_factories'; +import { makeRequestFacade } from './lib/make_request_facade'; const MAIN_ENTRY = `${API_BASE_URL}/jobs`; @@ -40,15 +41,16 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/list`, method: 'GET', options: getRouteConfig(), - handler: (request: RequestFacade) => { - const { page: queryPage, size: querySize, ids: queryIds } = request.query; + handler: (originalRequest: RequestFacade) => { + const requestFacade = makeRequestFacade(originalRequest); + const { page: queryPage, size: querySize, ids: queryIds } = requestFacade.query; const page = parseInt(queryPage, 10) || 0; const size = Math.min(100, parseInt(querySize, 10) || 10); const jobIds = queryIds ? queryIds.split(',') : null; const results = jobsQuery.list( - request.pre.management.jobTypes, - request.pre.user, + requestFacade.pre.management.jobTypes, + requestFacade.pre.user, page, size, jobIds @@ -62,8 +64,12 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/count`, method: 'GET', options: getRouteConfig(), - handler: (request: RequestFacade) => { - const results = jobsQuery.count(request.pre.management.jobTypes, request.pre.user); + handler: (originalRequest: RequestFacade) => { + const requestFacade = makeRequestFacade(originalRequest); + const results = jobsQuery.count( + requestFacade.pre.management.jobTypes, + requestFacade.pre.user + ); return results; }, }); @@ -73,17 +79,18 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/output/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (request: RequestFacade) => { - const { docId } = request.params; + handler: (originalRequest: RequestFacade) => { + const requestFacade = makeRequestFacade(originalRequest); + const { docId } = requestFacade.params; - return jobsQuery.get(request.pre.user, docId, { includeContent: true }).then( + return jobsQuery.get(requestFacade.pre.user, docId, { includeContent: true }).then( ({ _source: job }: JobSource): JobDocOutput => { if (!job) { throw boom.notFound(); } const { jobtype: jobType } = job; - if (!request.pre.management.jobTypes.includes(jobType)) { + if (!requestFacade.pre.management.jobTypes.includes(jobType)) { throw boom.unauthorized(`Sorry, you are not authorized to download ${jobType} reports`); } @@ -98,18 +105,19 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/info/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (request: RequestFacade) => { - const { docId } = request.params; + handler: (originalRequest: RequestFacade) => { + const requestFacade = makeRequestFacade(originalRequest); + const { docId } = requestFacade.params; return jobsQuery - .get(request.pre.user, docId) + .get(requestFacade.pre.user, docId) .then(({ _source: job }: JobSource): JobSource['_source'] => { if (!job) { throw boom.notFound(); } const { jobtype: jobType, payload } = job; - if (!request.pre.management.jobTypes.includes(jobType)) { + if (!requestFacade.pre.management.jobTypes.includes(jobType)) { throw boom.unauthorized(`Sorry, you are not authorized to view ${jobType} info`); } @@ -130,7 +138,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/download/{docId}`, method: 'GET', options: getRouteConfigDownload(), - handler: async (request: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(originalRequest); const { docId } = request.params; let response = await jobResponseHandler( diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts new file mode 100644 index 0000000000000..e73e80a40da7d --- /dev/null +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { RequestFacade } from '../../../types'; + +export function makeRequestFacade(request: RequestFacade): RequestFacade { + return { + headers: request.headers, + params: request.params, + payload: request.payload, + query: request.query, + pre: request.pre, + getBasePath: request.getBasePath, + getSavedObjectsClient: request.getSavedObjectsClient, + }; +} From 79a9288ad1261e89c93bcaa942329119cb785e61 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 16:46:27 -0700 Subject: [PATCH 04/25] requestFacade --- .../plugins/reporting/server/routes/lib/make_request_facade.ts | 3 ++- x-pack/legacy/plugins/reporting/types.d.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index e73e80a40da7d..1dcb271c134f1 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -14,6 +14,7 @@ export function makeRequestFacade(request: RequestFacade): RequestFacade { query: request.query, pre: request.pre, getBasePath: request.getBasePath, - getSavedObjectsClient: request.getSavedObjectsClient, + getSavedObjectsClient: request.getSavedObjectsClient.bind(request), + route: request.route, }; } diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index a63f675312b7e..47d088bb249f0 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -103,8 +103,9 @@ export interface RequestFacade { getSavedObjectsClient: Legacy.Request['getSavedObjectsClient']; headers: Legacy.Request['headers']; params: Legacy.Request['params']; - query: ListQuery & GenerateQuery; payload: JobParamPostPayload | GenerateExportTypePayload; + query: ListQuery & GenerateQuery; + route: Legacy.Request['route']; pre: { management: { jobTypes: any; From c931081d85c18149c7e2c65a76cb1a75f2e9c0da Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 15:55:35 -0700 Subject: [PATCH 05/25] use the shim --- x-pack/legacy/plugins/reporting/index.ts | 23 +++++++++--------- .../plugins/reporting/make_server_facade.ts | 24 +++++++++++++++++++ .../server/lib/{get_user.js => get_user.ts} | 6 +++-- .../reporting/server/lib/level_logger.ts | 8 +++---- .../routes/lib/authorized_user_pre_routing.js | 1 + .../server/routes/lib/make_request_facade.ts | 1 + x-pack/legacy/plugins/reporting/types.d.ts | 2 ++ 7 files changed, 48 insertions(+), 17 deletions(-) create mode 100644 x-pack/legacy/plugins/reporting/make_server_facade.ts rename x-pack/legacy/plugins/reporting/server/lib/{get_user.js => get_user.ts} (75%) diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index faa27bfb2d6ea..19b8f09aed4fa 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -17,10 +17,11 @@ import { runValidations, } from './server/lib'; import { config as reportingConfig } from './config'; -import { logConfiguration } from './log_configuration'; import { createBrowserDriverFactory } from './server/browsers'; import { registerReportingUsageCollector } from './server/usage'; import { ReportingConfigOptions, ReportingPluginSpecOptions, ServerFacade } from './types.d'; +import { logConfiguration } from './log_configuration'; +import { makeServerFacade } from './make_server_facade'; const kbToBase64Length = (kb: number) => { return Math.floor((kb * 1024 * 8) / 6); @@ -70,28 +71,28 @@ export const reporting = (kibana: any) => { }, }, - // TODO: Decouple Hapi: Build a server facade object based on the server to - // pass through to the libs. Do not pass server directly async init(server: ServerFacade) { + const serverFacade = makeServerFacade(server); + const exportTypesRegistry = getExportTypesRegistry(); let isCollectorReady = false; // Register a function with server to manage the collection of usage stats - const { usageCollection } = server.newPlatform.setup.plugins; + const { usageCollection } = serverFacade.newPlatform.setup.plugins; registerReportingUsageCollector( usageCollection, - server, + serverFacade, () => isCollectorReady, exportTypesRegistry ); - const logger = LevelLogger.createForServer(server, [PLUGIN_ID]); - const browserDriverFactory = await createBrowserDriverFactory(server); + const logger = LevelLogger.createForServer(serverFacade, [PLUGIN_ID]); + const browserDriverFactory = await createBrowserDriverFactory(serverFacade); - logConfiguration(server, logger); - runValidations(server, logger, browserDriverFactory); + logConfiguration(serverFacade, logger); + runValidations(serverFacade, logger, browserDriverFactory); - const { xpack_main: xpackMainPlugin } = server.plugins; + const { xpack_main: xpackMainPlugin } = serverFacade.plugins; mirrorPluginStatus(xpackMainPlugin, this); const checkLicense = checkLicenseFactory(exportTypesRegistry); (xpackMainPlugin as any).status.once('green', () => { @@ -104,7 +105,7 @@ export const reporting = (kibana: any) => { isCollectorReady = true; // Reporting routes - registerRoutes(server, exportTypesRegistry, browserDriverFactory, logger); + registerRoutes(serverFacade, exportTypesRegistry, browserDriverFactory, logger); }, deprecations({ unused }: any) { diff --git a/x-pack/legacy/plugins/reporting/make_server_facade.ts b/x-pack/legacy/plugins/reporting/make_server_facade.ts new file mode 100644 index 0000000000000..0c951c8076752 --- /dev/null +++ b/x-pack/legacy/plugins/reporting/make_server_facade.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ServerFacade } from './types'; + +export function makeServerFacade(server: ServerFacade): ServerFacade { + return { + config: server.config, + info: server.info, + route: server.route.bind(server), + newPlatform: server.newPlatform, + plugins: { + elasticsearch: server.plugins.elasticsearch, + xpack_main: server.plugins.xpack_main, + security: server.plugins.security, + }, + savedObjects: server.savedObjects, + uiSettingsServiceFactory: server.uiSettingsServiceFactory, + log: server.log.bind(server), + }; +} diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.js b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts similarity index 75% rename from x-pack/legacy/plugins/reporting/server/lib/get_user.js rename to x-pack/legacy/plugins/reporting/server/lib/get_user.ts index 04c9516cb99d4..e7957a85b4947 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.js +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -4,8 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -export function getUserFactory(server) { - return async request => { +import { RequestFacade, ServerFacade } from '../../types'; + +export function getUserFactory(server: ServerFacade) { + return async (request: RequestFacade) => { if (!server.plugins.security) { return null; } diff --git a/x-pack/legacy/plugins/reporting/server/lib/level_logger.ts b/x-pack/legacy/plugins/reporting/server/lib/level_logger.ts index c67a9cd32d50d..839fa16a716b7 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/level_logger.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/level_logger.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -type ServerLog = (tags: string[], msg: string) => void; +import { ServerFacade } from '../../types'; const trimStr = (toTrim: string) => { return typeof toTrim === 'string' ? toTrim.trim() : toTrim; @@ -16,12 +16,12 @@ export class LevelLogger { public warn: (msg: string, tags?: string[]) => void; - static createForServer(server: any, tags: string[]) { - const serverLog: ServerLog = (tgs: string[], msg: string) => server.log(tgs, msg); + static createForServer(server: ServerFacade, tags: string[]) { + const serverLog: ServerFacade['log'] = (tgs: string[], msg: string) => server.log(tgs, msg); return new LevelLogger(serverLog, tags); } - constructor(logger: ServerLog, tags: string[]) { + constructor(logger: ServerFacade['log'], tags: string[]) { this._logger = logger; this._tags = tags; diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js index 79a5f1a4f6f5f..267992d631a99 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js @@ -14,6 +14,7 @@ export const authorizedUserPreRoutingFactory = function authorizedUserPreRouting const config = server.config(); return async function authorizedUserPreRouting(request) { + console.log('how are you'); const xpackInfo = server.plugins.xpack_main.info; if (!xpackInfo || !xpackInfo.isAvailable()) { diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index 1dcb271c134f1..8ef8cea97628e 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -9,6 +9,7 @@ import { RequestFacade } from '../../../types'; export function makeRequestFacade(request: RequestFacade): RequestFacade { return { headers: request.headers, + auth: request.auth, // for getUser params: request.params, payload: request.payload, query: request.query, diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 47d088bb249f0..fcebd5b9e036e 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -80,6 +80,7 @@ export interface ServerFacade { newPlatform: Legacy.Server['newPlatform']; plugins: { elasticsearch: LegacyPlugins['elasticsearch']; + security: LegacyPlugins['security']; xpack_main: XPackMainPlugin & { status?: any; }; @@ -101,6 +102,7 @@ export type EnqueueJobFn = ( export interface RequestFacade { getBasePath: Legacy.Request['getBasePath']; getSavedObjectsClient: Legacy.Request['getSavedObjectsClient']; + auth: Legacy.Request['auth']; headers: Legacy.Request['headers']; params: Legacy.Request['params']; payload: JobParamPostPayload | GenerateExportTypePayload; From 62dc40866f0aba465266771b5fe858d2fb12be69 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 17:35:07 -0700 Subject: [PATCH 06/25] import sorting --- x-pack/legacy/plugins/reporting/index.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 19b8f09aed4fa..900b3a6bcebcf 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -16,10 +16,10 @@ import { getExportTypesRegistry, runValidations, } from './server/lib'; -import { config as reportingConfig } from './config'; import { createBrowserDriverFactory } from './server/browsers'; import { registerReportingUsageCollector } from './server/usage'; import { ReportingConfigOptions, ReportingPluginSpecOptions, ServerFacade } from './types.d'; +import { config as reportingConfig } from './config'; import { logConfiguration } from './log_configuration'; import { makeServerFacade } from './make_server_facade'; @@ -73,7 +73,6 @@ export const reporting = (kibana: any) => { async init(server: ServerFacade) { const serverFacade = makeServerFacade(server); - const exportTypesRegistry = getExportTypesRegistry(); let isCollectorReady = false; From 78a2ea15b377825aace6d94d5cc73ef26301cb74 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 17:36:50 -0700 Subject: [PATCH 07/25] originalServer --- x-pack/legacy/plugins/reporting/index.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 900b3a6bcebcf..bbb6051682e44 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -71,27 +71,27 @@ export const reporting = (kibana: any) => { }, }, - async init(server: ServerFacade) { - const serverFacade = makeServerFacade(server); + async init(originalServer: ServerFacade) { + const server = makeServerFacade(originalServer); const exportTypesRegistry = getExportTypesRegistry(); let isCollectorReady = false; // Register a function with server to manage the collection of usage stats - const { usageCollection } = serverFacade.newPlatform.setup.plugins; + const { usageCollection } = server.newPlatform.setup.plugins; registerReportingUsageCollector( usageCollection, - serverFacade, + server, () => isCollectorReady, exportTypesRegistry ); - const logger = LevelLogger.createForServer(serverFacade, [PLUGIN_ID]); - const browserDriverFactory = await createBrowserDriverFactory(serverFacade); + const logger = LevelLogger.createForServer(server, [PLUGIN_ID]); + const browserDriverFactory = await createBrowserDriverFactory(server); - logConfiguration(serverFacade, logger); - runValidations(serverFacade, logger, browserDriverFactory); + logConfiguration(server, logger); + runValidations(server, logger, browserDriverFactory); - const { xpack_main: xpackMainPlugin } = serverFacade.plugins; + const { xpack_main: xpackMainPlugin } = server.plugins; mirrorPluginStatus(xpackMainPlugin, this); const checkLicense = checkLicenseFactory(exportTypesRegistry); (xpackMainPlugin as any).status.once('green', () => { @@ -104,7 +104,7 @@ export const reporting = (kibana: any) => { isCollectorReady = true; // Reporting routes - registerRoutes(serverFacade, exportTypesRegistry, browserDriverFactory, logger); + registerRoutes(server, exportTypesRegistry, browserDriverFactory, logger); }, deprecations({ unused }: any) { From 3e71f572319858497df77d84dc6000100ab785fc Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 17:38:52 -0700 Subject: [PATCH 08/25] reduce loc change --- .../plugins/reporting/server/routes/jobs.ts | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts index d039845380165..a88b59431a4ce 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts @@ -42,15 +42,15 @@ export function registerJobInfoRoutes( method: 'GET', options: getRouteConfig(), handler: (originalRequest: RequestFacade) => { - const requestFacade = makeRequestFacade(originalRequest); - const { page: queryPage, size: querySize, ids: queryIds } = requestFacade.query; + const request = makeRequestFacade(originalRequest); + const { page: queryPage, size: querySize, ids: queryIds } = request.query; const page = parseInt(queryPage, 10) || 0; const size = Math.min(100, parseInt(querySize, 10) || 10); const jobIds = queryIds ? queryIds.split(',') : null; const results = jobsQuery.list( - requestFacade.pre.management.jobTypes, - requestFacade.pre.user, + request.pre.management.jobTypes, + request.pre.user, page, size, jobIds @@ -65,11 +65,8 @@ export function registerJobInfoRoutes( method: 'GET', options: getRouteConfig(), handler: (originalRequest: RequestFacade) => { - const requestFacade = makeRequestFacade(originalRequest); - const results = jobsQuery.count( - requestFacade.pre.management.jobTypes, - requestFacade.pre.user - ); + const request = makeRequestFacade(originalRequest); + const results = jobsQuery.count(request.pre.management.jobTypes, request.pre.user); return results; }, }); @@ -80,17 +77,17 @@ export function registerJobInfoRoutes( method: 'GET', options: getRouteConfig(), handler: (originalRequest: RequestFacade) => { - const requestFacade = makeRequestFacade(originalRequest); - const { docId } = requestFacade.params; + const request = makeRequestFacade(originalRequest); + const { docId } = request.params; - return jobsQuery.get(requestFacade.pre.user, docId, { includeContent: true }).then( + return jobsQuery.get(request.pre.user, docId, { includeContent: true }).then( ({ _source: job }: JobSource): JobDocOutput => { if (!job) { throw boom.notFound(); } const { jobtype: jobType } = job; - if (!requestFacade.pre.management.jobTypes.includes(jobType)) { + if (!request.pre.management.jobTypes.includes(jobType)) { throw boom.unauthorized(`Sorry, you are not authorized to download ${jobType} reports`); } @@ -106,18 +103,18 @@ export function registerJobInfoRoutes( method: 'GET', options: getRouteConfig(), handler: (originalRequest: RequestFacade) => { - const requestFacade = makeRequestFacade(originalRequest); - const { docId } = requestFacade.params; + const request = makeRequestFacade(originalRequest); + const { docId } = request.params; return jobsQuery - .get(requestFacade.pre.user, docId) + .get(request.pre.user, docId) .then(({ _source: job }: JobSource): JobSource['_source'] => { if (!job) { throw boom.notFound(); } const { jobtype: jobType, payload } = job; - if (!requestFacade.pre.management.jobTypes.includes(jobType)) { + if (!request.pre.management.jobTypes.includes(jobType)) { throw boom.unauthorized(`Sorry, you are not authorized to view ${jobType} info`); } From 956ae1721706f16f020ec78a972efb7ea82a97e7 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Mon, 6 Jan 2020 17:39:28 -0700 Subject: [PATCH 09/25] remove consolelog --- .../reporting/server/routes/lib/authorized_user_pre_routing.js | 1 - 1 file changed, 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js index 267992d631a99..79a5f1a4f6f5f 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.js @@ -14,7 +14,6 @@ export const authorizedUserPreRoutingFactory = function authorizedUserPreRouting const config = server.config(); return async function authorizedUserPreRouting(request) { - console.log('how are you'); const xpackInfo = server.plugins.xpack_main.info; if (!xpackInfo || !xpackInfo.isAvailable()) { From e4761ffa7e42f3a9b5882958cfe56526dc7dbb04 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 7 Jan 2020 10:14:44 -0700 Subject: [PATCH 10/25] hacks to fix tests --- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 3 ++- .../reporting/server/routes/lib/make_request_facade.ts | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index e7957a85b4947..edb1d0a31b654 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Request } from 'hapi'; import { RequestFacade, ServerFacade } from '../../types'; export function getUserFactory(server: ServerFacade) { @@ -13,7 +14,7 @@ export function getUserFactory(server: ServerFacade) { } try { - return await server.plugins.security.getUser(request); + return await server.plugins.security.getUser((request as unknown) as Request); } catch (err) { server.log(['reporting', 'getUser', 'debug'], err); return null; diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index 8ef8cea97628e..b27cf5e77d88b 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -7,7 +7,12 @@ import { RequestFacade } from '../../../types'; export function makeRequestFacade(request: RequestFacade): RequestFacade { + // This condition is for unit tests + const getSavedObjectsClient = request.getSavedObjectsClient + ? request.getSavedObjectsClient.bind(request) + : request.getSavedObjectsClient; return { + getSavedObjectsClient, headers: request.headers, auth: request.auth, // for getUser params: request.params, @@ -15,7 +20,6 @@ export function makeRequestFacade(request: RequestFacade): RequestFacade { query: request.query, pre: request.pre, getBasePath: request.getBasePath, - getSavedObjectsClient: request.getSavedObjectsClient.bind(request), route: request.route, }; } From 44b714ce4afb865ee891cc59f6aa8445f0484adf Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 7 Jan 2020 13:58:52 -0700 Subject: [PATCH 11/25] ServerFacade in index --- x-pack/legacy/plugins/reporting/index.ts | 55 +++++++++++++++---- .../plugins/reporting/make_server_facade.ts | 24 -------- x-pack/legacy/plugins/reporting/types.d.ts | 23 +------- 3 files changed, 47 insertions(+), 55 deletions(-) delete mode 100644 x-pack/legacy/plugins/reporting/make_server_facade.ts diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index bbb6051682e44..7f0eb81e2ae72 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -6,6 +6,8 @@ import { resolve } from 'path'; import { i18n } from '@kbn/i18n'; +import { Legacy } from 'kibana'; +import { XPackMainPlugin } from '../xpack_main/server/xpack_main'; import { PLUGIN_ID, UI_SETTINGS_CUSTOM_PDF_LOGO } from './common/constants'; // @ts-ignore untyped module defintition import { mirrorPluginStatus } from '../../server/lib/mirror_plugin_status'; @@ -18,15 +20,33 @@ import { } from './server/lib'; import { createBrowserDriverFactory } from './server/browsers'; import { registerReportingUsageCollector } from './server/usage'; -import { ReportingConfigOptions, ReportingPluginSpecOptions, ServerFacade } from './types.d'; +import { ReportingConfigOptions, ReportingPluginSpecOptions } from './types.d'; import { config as reportingConfig } from './config'; import { logConfiguration } from './log_configuration'; -import { makeServerFacade } from './make_server_facade'; const kbToBase64Length = (kb: number) => { return Math.floor((kb * 1024 * 8) / 6); }; +type LegacyPlugins = Legacy.Server['plugins']; + +export interface ServerFacade { + config: Legacy.Server['config']; + info: Legacy.Server['info']; + log: Legacy.Server['log']; + newPlatform: Legacy.Server['newPlatform']; + plugins: { + elasticsearch: LegacyPlugins['elasticsearch']; + security: LegacyPlugins['security']; + xpack_main: XPackMainPlugin & { + status?: any; + }; + }; + route: Legacy.Server['route']; + savedObjects: Legacy.Server['savedObjects']; + uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; +} + export const reporting = (kibana: any) => { return new kibana.Plugin({ id: PLUGIN_ID, @@ -71,8 +91,21 @@ export const reporting = (kibana: any) => { }, }, - async init(originalServer: ServerFacade) { - const server = makeServerFacade(originalServer); + async init(server: Legacy.Server) { + const serverFacade: ServerFacade = { + config: server.config, + info: server.info, + route: server.route.bind(server), + newPlatform: server.newPlatform, + plugins: { + elasticsearch: server.plugins.elasticsearch, + xpack_main: server.plugins.xpack_main, + security: server.plugins.security, + }, + savedObjects: server.savedObjects, + uiSettingsServiceFactory: server.uiSettingsServiceFactory, + log: server.log.bind(server), + }; const exportTypesRegistry = getExportTypesRegistry(); let isCollectorReady = false; @@ -80,18 +113,18 @@ export const reporting = (kibana: any) => { const { usageCollection } = server.newPlatform.setup.plugins; registerReportingUsageCollector( usageCollection, - server, + serverFacade, () => isCollectorReady, exportTypesRegistry ); - const logger = LevelLogger.createForServer(server, [PLUGIN_ID]); - const browserDriverFactory = await createBrowserDriverFactory(server); + const logger = LevelLogger.createForServer(serverFacade, [PLUGIN_ID]); + const browserDriverFactory = await createBrowserDriverFactory(serverFacade); - logConfiguration(server, logger); - runValidations(server, logger, browserDriverFactory); + logConfiguration(serverFacade, logger); + runValidations(serverFacade, logger, browserDriverFactory); - const { xpack_main: xpackMainPlugin } = server.plugins; + const { xpack_main: xpackMainPlugin } = serverFacade.plugins; mirrorPluginStatus(xpackMainPlugin, this); const checkLicense = checkLicenseFactory(exportTypesRegistry); (xpackMainPlugin as any).status.once('green', () => { @@ -104,7 +137,7 @@ export const reporting = (kibana: any) => { isCollectorReady = true; // Reporting routes - registerRoutes(server, exportTypesRegistry, browserDriverFactory, logger); + registerRoutes(serverFacade, exportTypesRegistry, browserDriverFactory, logger); }, deprecations({ unused }: any) { diff --git a/x-pack/legacy/plugins/reporting/make_server_facade.ts b/x-pack/legacy/plugins/reporting/make_server_facade.ts deleted file mode 100644 index 0c951c8076752..0000000000000 --- a/x-pack/legacy/plugins/reporting/make_server_facade.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { ServerFacade } from './types'; - -export function makeServerFacade(server: ServerFacade): ServerFacade { - return { - config: server.config, - info: server.info, - route: server.route.bind(server), - newPlatform: server.newPlatform, - plugins: { - elasticsearch: server.plugins.elasticsearch, - xpack_main: server.plugins.xpack_main, - security: server.plugins.security, - }, - savedObjects: server.savedObjects, - uiSettingsServiceFactory: server.uiSettingsServiceFactory, - log: server.log.bind(server), - }; -} diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index fcebd5b9e036e..a870358259ff1 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -7,7 +7,6 @@ import { ResponseObject } from 'hapi'; import { EventEmitter } from 'events'; import { Legacy } from 'kibana'; -import { XPackMainPlugin } from '../xpack_main/server/xpack_main'; import { ElasticsearchPlugin, CallCluster, @@ -16,6 +15,7 @@ import { CancellationToken } from './common/cancellation_token'; import { LevelLogger } from './server/lib/level_logger'; import { HeadlessChromiumDriverFactory } from './server/browsers/chromium/driver_factory'; import { BrowserType } from './server/browsers/types'; +import { ServerFacade } from './index'; export type ReportingPlugin = object; // For Plugin contract @@ -71,25 +71,6 @@ interface GenerateExportTypePayload { export type ReportingPluginSpecOptions = Legacy.PluginSpecOptions; -type LegacyPlugins = Legacy.Server['plugins']; - -export interface ServerFacade { - config: Legacy.Server['config']; - info: Legacy.Server['info']; - log: Legacy.Server['log']; - newPlatform: Legacy.Server['newPlatform']; - plugins: { - elasticsearch: LegacyPlugins['elasticsearch']; - security: LegacyPlugins['security']; - xpack_main: XPackMainPlugin & { - status?: any; - }; - }; - route: Legacy.Server['route']; - savedObjects: Legacy.Server['savedObjects']; - uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; -} - export type EnqueueJobFn = ( parentLogger: LevelLogger, exportTypeId: string, @@ -352,3 +333,5 @@ export interface AbsoluteURLFactoryOptions { hostname: string; port: string | number; } + +export { ServerFacade }; From 4e7e44871e6b707ab880f75ad4b03d10b09f0e98 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 7 Jan 2020 14:10:48 -0700 Subject: [PATCH 12/25] Cosmetic --- x-pack/legacy/plugins/reporting/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 7f0eb81e2ae72..ee7135be7a110 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -63,7 +63,7 @@ export const reporting = (kibana: any) => { embeddableActions: ['plugins/reporting/panel_actions/get_csv_panel_action'], home: ['plugins/reporting/register_feature'], managementSections: ['plugins/reporting/views/management'], - injectDefaultVars(server: ServerFacade, options?: ReportingConfigOptions) { + injectDefaultVars(server: Legacy.Server, options?: ReportingConfigOptions) { const config = server.config(); return { reportingPollConfig: options ? options.poll : {}, From 71bd4a5b21532aec2a1fd3604af71bb724c3c9ef Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 7 Jan 2020 14:49:08 -0700 Subject: [PATCH 13/25] remove field from serverfacade --- x-pack/legacy/plugins/reporting/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index ee7135be7a110..d98c1942c61e6 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -34,7 +34,6 @@ export interface ServerFacade { config: Legacy.Server['config']; info: Legacy.Server['info']; log: Legacy.Server['log']; - newPlatform: Legacy.Server['newPlatform']; plugins: { elasticsearch: LegacyPlugins['elasticsearch']; security: LegacyPlugins['security']; @@ -96,7 +95,6 @@ export const reporting = (kibana: any) => { config: server.config, info: server.info, route: server.route.bind(server), - newPlatform: server.newPlatform, plugins: { elasticsearch: server.plugins.elasticsearch, xpack_main: server.plugins.xpack_main, From ae8d134ba4f9a9d5eda968d4abeb11f5e9539a42 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Wed, 8 Jan 2020 14:48:59 -0700 Subject: [PATCH 14/25] add raw to the request --- .../server/routes/generate_from_jobparams.ts | 5 +++-- .../routes/generate_from_savedobject.ts | 5 +++-- .../server/routes/lib/make_request_facade.ts | 18 ++++++++++++----- x-pack/legacy/plugins/reporting/types.d.ts | 20 ++++++++++++------- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts index 0066399ebe758..3e1ee3831e721 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts @@ -4,11 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Legacy } from 'kibana'; import boom from 'boom'; import Joi from 'joi'; import rison from 'rison-node'; import { API_BASE_URL } from '../../common/constants'; -import { ServerFacade, RequestFacade, ReportingResponseToolkit } from '../../types'; +import { ServerFacade, ReportingResponseToolkit } from '../../types'; import { getRouteConfigFactoryReportingPre, GetRouteConfigFactoryFn, @@ -55,7 +56,7 @@ export function registerGenerateFromJobParams( path: `${BASE_GENERATE}/{exportType}`, method: 'POST', options: getRouteConfig(), - handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { const request = makeRequestFacade(originalRequest); let jobParamsRison: string | null; diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts index c87d22a716ea4..e4ec45b59eb09 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Legacy } from 'kibana'; import { get } from 'lodash'; import { API_BASE_GENERATE_V1, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../common/constants'; -import { ServerFacade, RequestFacade, ReportingResponseToolkit } from '../../types'; +import { ServerFacade, ReportingResponseToolkit } from '../../types'; import { HandlerErrorFunction, HandlerFunction, QueuedJobPayload } from './types'; import { getRouteOptionsCsv } from './lib/route_config_factories'; import { makeRequestFacade } from './lib/make_request_facade'; @@ -32,7 +33,7 @@ export function registerGenerateCsvFromSavedObject( path: `${API_BASE_GENERATE_V1}/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { const request = makeRequestFacade(originalRequest); /* * 1. Build `jobParams` object: job data that execution will need to reference in various parts of the lifecycle diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index b27cf5e77d88b..4d7056f85d209 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -4,9 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestFacade } from '../../../types'; +import { RequestQuery } from 'hapi'; +import { Legacy } from 'kibana'; +import { + RequestFacade, + ReportingRequestPayload, + ReportingRequestPre, + ReportingRequestQuery, +} from '../../../types'; -export function makeRequestFacade(request: RequestFacade): RequestFacade { +export function makeRequestFacade(request: Legacy.Request): RequestFacade { // This condition is for unit tests const getSavedObjectsClient = request.getSavedObjectsClient ? request.getSavedObjectsClient.bind(request) @@ -16,10 +23,11 @@ export function makeRequestFacade(request: RequestFacade): RequestFacade { headers: request.headers, auth: request.auth, // for getUser params: request.params, - payload: request.payload, - query: request.query, - pre: request.pre, + payload: (request.payload as object) as ReportingRequestPayload, + query: ((request.query as RequestQuery) as object) as ReportingRequestQuery, + pre: (request.pre as Record) as ReportingRequestPre, getBasePath: request.getBasePath, route: request.route, + raw: request.raw, }; } diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index a870358259ff1..6ae61171189c8 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -80,6 +80,16 @@ export type EnqueueJobFn = ( request: RequestFacade ) => Promise; +export type ReportingRequestPayload = GenerateExportTypePayload | JobParamPostPayload; +export type ReportingRequestQuery = ListQuery | GenerateQuery; // FIXME weird + +export interface ReportingRequestPre { + management: { + jobTypes: any; + }; + user: any; +} + export interface RequestFacade { getBasePath: Legacy.Request['getBasePath']; getSavedObjectsClient: Legacy.Request['getSavedObjectsClient']; @@ -87,14 +97,10 @@ export interface RequestFacade { headers: Legacy.Request['headers']; params: Legacy.Request['params']; payload: JobParamPostPayload | GenerateExportTypePayload; - query: ListQuery & GenerateQuery; + query: ReportingRequestQuery; route: Legacy.Request['route']; - pre: { - management: { - jobTypes: any; - }; - user: any; - }; + pre: ReportingRequestPre; + raw: Legacy.Request['raw']; } export type ResponseFacade = ResponseObject & { From 81afb2884d3eb3192c761826ff8ceb52c235914e Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Wed, 8 Jan 2020 15:25:31 -0700 Subject: [PATCH 15/25] fix types --- .../server/routes/generate_from_jobparams.ts | 2 +- .../server/routes/generate_from_savedobject.ts | 8 ++++---- .../routes/generate_from_savedobject_immediate.ts | 4 ++-- .../plugins/reporting/server/routes/generation.ts | 4 ++-- .../plugins/reporting/server/routes/jobs.ts | 15 ++++++++------- .../plugins/reporting/server/routes/types.d.ts | 3 ++- x-pack/legacy/plugins/reporting/types.d.ts | 4 ++-- 7 files changed, 21 insertions(+), 19 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts index 3e1ee3831e721..95cd4c0317561 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts @@ -83,7 +83,7 @@ export function registerGenerateFromJobParams( if (!jobParams) { throw new Error('missing jobParams!'); } - response = await handler(exportType, jobParams, request, h); + response = await handler(exportType, jobParams, originalRequest, h); } catch (err) { throw boom.badRequest(`invalid rison: ${jobParamsRison}`); } diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts index e4ec45b59eb09..649c5704ed7e5 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts @@ -34,17 +34,17 @@ export function registerGenerateCsvFromSavedObject( method: 'POST', options: routeOptions, handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { - const request = makeRequestFacade(originalRequest); + const requestFacade = makeRequestFacade(originalRequest); + /* * 1. Build `jobParams` object: job data that execution will need to reference in various parts of the lifecycle * 2. Pass the jobParams and other common params to `handleRoute`, a shared function to enqueue the job with the params * 3. Ensure that details for a queued job were returned */ - let result: QueuedJobPayload; try { - const jobParams = getJobParamsFromRequest(request, { isImmediate: false }); - result = await handleRoute(CSV_FROM_SAVEDOBJECT_JOB_TYPE, jobParams, request, h); + const jobParams = getJobParamsFromRequest(requestFacade, { isImmediate: false }); + result = await handleRoute(CSV_FROM_SAVEDOBJECT_JOB_TYPE, jobParams, originalRequest, h); // pass the original request because the handler will make the request facade on its own } catch (err) { throw handleRouteError(CSV_FROM_SAVEDOBJECT_JOB_TYPE, err); } diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts index a7ec4d69c55bc..aae6ae42ae8bc 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Legacy } from 'kibana'; import { API_BASE_GENERATE_V1 } from '../../common/constants'; import { createJobFactory, executeJobFactory } from '../../export_types/csv_from_savedobject'; import { ServerFacade, - RequestFacade, ResponseFacade, HeadlessChromiumDriverFactory, ReportingResponseToolkit, @@ -44,7 +44,7 @@ export function registerGenerateCsvFromSavedObjectImmediate( path: `${API_BASE_GENERATE_V1}/immediate/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { const request = makeRequestFacade(originalRequest); const logger = parentLogger.clone(['savedobject-csv']); const jobParams = getJobParamsFromRequest(request, { isImmediate: true }); diff --git a/x-pack/legacy/plugins/reporting/server/routes/generation.ts b/x-pack/legacy/plugins/reporting/server/routes/generation.ts index 2a3a87e69aa49..1d61933fa0ed3 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generation.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generation.ts @@ -5,12 +5,12 @@ */ import boom from 'boom'; +import { Legacy } from 'kibana'; import { API_BASE_URL } from '../../common/constants'; import { ServerFacade, ExportTypesRegistry, HeadlessChromiumDriverFactory, - RequestFacade, ReportingResponseToolkit, Logger, } from '../../types'; @@ -40,7 +40,7 @@ export function registerJobGenerationRoutes( async function handler( exportTypeId: string, jobParams: object, - originalRequest: RequestFacade, + originalRequest: Legacy.Request, h: ReportingResponseToolkit ) { const request = makeRequestFacade(originalRequest); diff --git a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts index a88b59431a4ce..788080f47c34b 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts @@ -4,16 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Legacy } from 'kibana'; import boom from 'boom'; import { API_BASE_URL } from '../../common/constants'; import { ServerFacade, ExportTypesRegistry, Logger, - RequestFacade, ReportingResponseToolkit, JobDocOutput, JobSource, + ListQuery, } from '../../types'; // @ts-ignore import { jobsQueryFactory } from '../lib/jobs_query'; @@ -41,9 +42,9 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/list`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: RequestFacade) => { + handler: (originalRequest: Legacy.Request) => { const request = makeRequestFacade(originalRequest); - const { page: queryPage, size: querySize, ids: queryIds } = request.query; + const { page: queryPage, size: querySize, ids: queryIds } = request.query as ListQuery; const page = parseInt(queryPage, 10) || 0; const size = Math.min(100, parseInt(querySize, 10) || 10); const jobIds = queryIds ? queryIds.split(',') : null; @@ -64,7 +65,7 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/count`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: RequestFacade) => { + handler: (originalRequest: Legacy.Request) => { const request = makeRequestFacade(originalRequest); const results = jobsQuery.count(request.pre.management.jobTypes, request.pre.user); return results; @@ -76,7 +77,7 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/output/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: RequestFacade) => { + handler: (originalRequest: Legacy.Request) => { const request = makeRequestFacade(originalRequest); const { docId } = request.params; @@ -102,7 +103,7 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/info/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: RequestFacade) => { + handler: (originalRequest: Legacy.Request) => { const request = makeRequestFacade(originalRequest); const { docId } = request.params; @@ -135,7 +136,7 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/download/{docId}`, method: 'GET', options: getRouteConfigDownload(), - handler: async (originalRequest: RequestFacade, h: ReportingResponseToolkit) => { + handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { const request = makeRequestFacade(originalRequest); const { docId } = request.params; diff --git a/x-pack/legacy/plugins/reporting/server/routes/types.d.ts b/x-pack/legacy/plugins/reporting/server/routes/types.d.ts index b50d443ec00b9..f3660a22cbac1 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/types.d.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/types.d.ts @@ -4,12 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Legacy } from 'kibana'; import { RequestFacade, ReportingResponseToolkit, JobDocPayload } from '../../types'; export type HandlerFunction = ( exportType: string, jobParams: object, - request: RequestFacade, + request: Legacy.Request, h: ReportingResponseToolkit ) => any; diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 6ae61171189c8..0d9a21692f8fc 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -53,7 +53,7 @@ export interface NetworkPolicy { rules: NetworkPolicyRule[]; } -interface ListQuery { +export interface ListQuery { page: string; size: string; ids?: string; // optional field forbids us from extending RequestQuery @@ -81,7 +81,7 @@ export type EnqueueJobFn = ( ) => Promise; export type ReportingRequestPayload = GenerateExportTypePayload | JobParamPostPayload; -export type ReportingRequestQuery = ListQuery | GenerateQuery; // FIXME weird +export type ReportingRequestQuery = ListQuery | GenerateQuery; export interface ReportingRequestPre { management: { From a6e830afa9644e535fc860a9fd4ccae31cdbef75 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Wed, 8 Jan 2020 21:26:46 -0700 Subject: [PATCH 16/25] add fieldFormatServiceFactory to legacy --- .../plugins/reporting/export_types/csv/server/execute_job.ts | 1 - x-pack/legacy/plugins/reporting/index.ts | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts index fef45f5a5eae8..ae603d93245a3 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts @@ -86,7 +86,6 @@ export const executeJobFactory: ExecuteJobFactory { - // @ts-ignore fieldFormatServiceFactory' does not exist on type 'ServerFacade TODO const fieldFormats = await server.fieldFormatServiceFactory(uiConfig); return fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); })(), diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index d98c1942c61e6..81ac31c23c980 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -7,6 +7,7 @@ import { resolve } from 'path'; import { i18n } from '@kbn/i18n'; import { Legacy } from 'kibana'; +import { IUiSettingsClient } from 'src/core/server'; import { XPackMainPlugin } from '../xpack_main/server/xpack_main'; import { PLUGIN_ID, UI_SETTINGS_CUSTOM_PDF_LOGO } from './common/constants'; // @ts-ignore untyped module defintition @@ -44,6 +45,7 @@ export interface ServerFacade { route: Legacy.Server['route']; savedObjects: Legacy.Server['savedObjects']; uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; + fieldFormatServiceFactory: (uiConfig: IUiSettingsClient) => unknown; } export const reporting = (kibana: any) => { @@ -102,6 +104,8 @@ export const reporting = (kibana: any) => { }, savedObjects: server.savedObjects, uiSettingsServiceFactory: server.uiSettingsServiceFactory, + // @ts-ignore Property 'fieldFormatServiceFactory' does not exist on type 'Server'. + fieldFormatServiceFactory: server.fieldFormatServiceFactory, log: server.log.bind(server), }; const exportTypesRegistry = getExportTypesRegistry(); From 80e0fccc749b692011f54377008de855b9c8f053 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 14 Jan 2020 09:25:10 -0700 Subject: [PATCH 17/25] Pass the complete request object to sec plugin --- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 3 +-- .../plugins/reporting/server/routes/lib/make_request_facade.ts | 3 +-- x-pack/legacy/plugins/reporting/types.d.ts | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index edb1d0a31b654..f9b1a912da49a 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Request } from 'hapi'; import { RequestFacade, ServerFacade } from '../../types'; export function getUserFactory(server: ServerFacade) { @@ -14,7 +13,7 @@ export function getUserFactory(server: ServerFacade) { } try { - return await server.plugins.security.getUser((request as unknown) as Request); + return await server.plugins.security.getUser(request.getRawRequest()); } catch (err) { server.log(['reporting', 'getUser', 'debug'], err); return null; diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index 4d7056f85d209..666ec22339895 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -21,13 +21,12 @@ export function makeRequestFacade(request: Legacy.Request): RequestFacade { return { getSavedObjectsClient, headers: request.headers, - auth: request.auth, // for getUser params: request.params, payload: (request.payload as object) as ReportingRequestPayload, query: ((request.query as RequestQuery) as object) as ReportingRequestQuery, pre: (request.pre as Record) as ReportingRequestPre, getBasePath: request.getBasePath, route: request.route, - raw: request.raw, + getRawRequest: () => request, // for security plugin dependency }; } diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 0d9a21692f8fc..589f0088a88d1 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -93,14 +93,13 @@ export interface ReportingRequestPre { export interface RequestFacade { getBasePath: Legacy.Request['getBasePath']; getSavedObjectsClient: Legacy.Request['getSavedObjectsClient']; - auth: Legacy.Request['auth']; headers: Legacy.Request['headers']; params: Legacy.Request['params']; payload: JobParamPostPayload | GenerateExportTypePayload; query: ReportingRequestQuery; route: Legacy.Request['route']; pre: ReportingRequestPre; - raw: Legacy.Request['raw']; + getRawRequest: () => Legacy.Request; } export type ResponseFacade = ResponseObject & { From 17b3b102aab7c7d93f851ed895725d578e995f83 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 14 Jan 2020 13:58:58 -0700 Subject: [PATCH 18/25] Fix test --- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index f9b1a912da49a..f39db45ea1d71 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -13,7 +13,8 @@ export function getUserFactory(server: ServerFacade) { } try { - return await server.plugins.security.getUser(request.getRawRequest()); + const workingRequest = request ? request.getRawRequest : request; // for unit tests + return await server.plugins.security.getUser(workingRequest); } catch (err) { server.log(['reporting', 'getUser', 'debug'], err); return null; From f7609d117275a628639dfe2b41c5b2060eb1ce12 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 14 Jan 2020 14:00:45 -0700 Subject: [PATCH 19/25] fix test 2 --- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index f39db45ea1d71..7c2fa6989942c 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -13,7 +13,7 @@ export function getUserFactory(server: ServerFacade) { } try { - const workingRequest = request ? request.getRawRequest : request; // for unit tests + const workingRequest = request ? request.getRawRequest() : request; // for unit tests return await server.plugins.security.getUser(workingRequest); } catch (err) { server.log(['reporting', 'getUser', 'debug'], err); From cb40fa3896b4f5e598325750509330c907dac186 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 14 Jan 2020 14:44:07 -0700 Subject: [PATCH 20/25] getUser takes a legacy request --- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 10 +++++----- .../reporting/server/routes/lib/make_request_facade.ts | 1 - x-pack/legacy/plugins/reporting/types.d.ts | 1 - 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index 7c2fa6989942c..e55c47e98e980 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -4,19 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestFacade, ServerFacade } from '../../types'; +import { Legacy } from 'kibana'; +import { ServerFacade } from '../../types'; export function getUserFactory(server: ServerFacade) { - return async (request: RequestFacade) => { + return async (request: Legacy.Request) => { if (!server.plugins.security) { return null; } try { - const workingRequest = request ? request.getRawRequest() : request; // for unit tests - return await server.plugins.security.getUser(workingRequest); + return await server.plugins.security.getUser(request); } catch (err) { - server.log(['reporting', 'getUser', 'debug'], err); + server.log(['reporting', 'getUser', 'error'], err); return null; } }; diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index 666ec22339895..33ae67f1ab489 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -27,6 +27,5 @@ export function makeRequestFacade(request: Legacy.Request): RequestFacade { pre: (request.pre as Record) as ReportingRequestPre, getBasePath: request.getBasePath, route: request.route, - getRawRequest: () => request, // for security plugin dependency }; } diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 589f0088a88d1..42558762c0439 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -99,7 +99,6 @@ export interface RequestFacade { query: ReportingRequestQuery; route: Legacy.Request['route']; pre: ReportingRequestPre; - getRawRequest: () => Legacy.Request; } export type ResponseFacade = ResponseObject & { From 15ab24b93b7eb5b47783bbbd331a7617e9a586a9 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 14 Jan 2020 15:01:44 -0700 Subject: [PATCH 21/25] add unit test for new lib --- .../routes/lib/make_request_facade.test.ts | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts new file mode 100644 index 0000000000000..66257302a9dfa --- /dev/null +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Legacy } from 'kibana'; +import { makeRequestFacade } from './make_request_facade'; + +test('makeRequestFacade', () => { + const originalRequest = ({ + getBasePath: () => 'basebase', + params: { + param1: 123, + }, + payload: { + payload1: 123, + }, + headers: { + user: 123, + }, + } as unknown) as Legacy.Request; + + expect(makeRequestFacade(originalRequest)).toMatchInlineSnapshot(` + Object { + "getBasePath": [Function], + "getSavedObjectsClient": undefined, + "headers": Object { + "user": 123, + }, + "params": Object { + "param1": 123, + }, + "payload": Object { + "payload1": 123, + }, + "pre": undefined, + "query": undefined, + "route": undefined, + } + `); +}); From ddf8fac27de1e49c8b5f05b3294639d0a080e874 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Wed, 15 Jan 2020 14:55:52 -0700 Subject: [PATCH 22/25] add getRawRequest to pass to saved objects method --- .../csv_from_savedobject/server/lib/generate_csv_search.ts | 2 +- x-pack/legacy/plugins/reporting/server/lib/get_user.ts | 3 +++ .../plugins/reporting/server/routes/lib/make_request_facade.ts | 1 + x-pack/legacy/plugins/reporting/types.d.ts | 1 + 4 files changed, 6 insertions(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts b/x-pack/legacy/plugins/reporting/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts index 7e12adefca38d..d39d2bbf08c9f 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts @@ -57,7 +57,7 @@ export async function generateCsvSearch( jobParams: JobParamsDiscoverCsv ): Promise { const { savedObjects, uiSettingsServiceFactory } = server; - const savedObjectsClient = savedObjects.getScopedSavedObjectsClient(req); + const savedObjectsClient = savedObjects.getScopedSavedObjectsClient(req.getRawRequest()); const { indexPatternSavedObjectId, timerange } = searchPanel; const savedSearchObjectAttr = searchPanel.attributes as SavedSearchObjectAttributes; const { indexPatternSavedObject } = await getDataSource( diff --git a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts index e55c47e98e980..e2921de795012 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/get_user.ts @@ -8,6 +8,9 @@ import { Legacy } from 'kibana'; import { ServerFacade } from '../../types'; export function getUserFactory(server: ServerFacade) { + /* + * Legacy.Request because this is called from routing middleware + */ return async (request: Legacy.Request) => { if (!server.plugins.security) { return null; diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts index 33ae67f1ab489..fb8a2dbbff17b 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.ts @@ -27,5 +27,6 @@ export function makeRequestFacade(request: Legacy.Request): RequestFacade { pre: (request.pre as Record) as ReportingRequestPre, getBasePath: request.getBasePath, route: request.route, + getRawRequest: () => request, }; } diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 42558762c0439..589f0088a88d1 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -99,6 +99,7 @@ export interface RequestFacade { query: ReportingRequestQuery; route: Legacy.Request['route']; pre: ReportingRequestPre; + getRawRequest: () => Legacy.Request; } export type ResponseFacade = ResponseObject & { From b4dcefb1989da9f1f4636dd2212ab638efaf5540 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Wed, 15 Jan 2020 21:07:20 -0700 Subject: [PATCH 23/25] update test snapshot --- .../routes/lib/make_request_facade.test.ts | 76 ++++++++++++------- 1 file changed, 48 insertions(+), 28 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts index 66257302a9dfa..c062400f41f8b 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts @@ -7,36 +7,56 @@ import { Legacy } from 'kibana'; import { makeRequestFacade } from './make_request_facade'; -test('makeRequestFacade', () => { - const originalRequest = ({ - getBasePath: () => 'basebase', - params: { - param1: 123, - }, - payload: { - payload1: 123, - }, - headers: { - user: 123, - }, - } as unknown) as Legacy.Request; +describe('makeRequestFacade', () => { + test('creates a default object', () => { + const originalRequest = ({ + getBasePath: () => 'basebase', + params: { + param1: 123, + }, + payload: { + payload1: 123, + }, + headers: { + user: 123, + }, + } as unknown) as Legacy.Request; - expect(makeRequestFacade(originalRequest)).toMatchInlineSnapshot(` - Object { - "getBasePath": [Function], - "getSavedObjectsClient": undefined, - "headers": Object { - "user": 123, + expect(makeRequestFacade(originalRequest)).toMatchInlineSnapshot(` + Object { + "getBasePath": [Function], + "getRawRequest": [Function], + "getSavedObjectsClient": undefined, + "headers": Object { + "user": 123, + }, + "params": Object { + "param1": 123, + }, + "payload": Object { + "payload1": 123, + }, + "pre": undefined, + "query": undefined, + "route": undefined, + } + `); + }); + + test('getRawRequest', () => { + const originalRequest = ({ + getBasePath: () => 'basebase', + params: { + param1: 123, }, - "params": Object { - "param1": 123, + payload: { + payload1: 123, }, - "payload": Object { - "payload1": 123, + headers: { + user: 123, }, - "pre": undefined, - "query": undefined, - "route": undefined, - } - `); + } as unknown) as Legacy.Request; + + expect(makeRequestFacade(originalRequest).getRawRequest()).toBe(originalRequest); + }); }); From 25e30dad5ec1196acdd482d98a8fc628e7818519 Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Thu, 16 Jan 2020 13:34:08 -0700 Subject: [PATCH 24/25] leave a TODO comment for type import --- x-pack/legacy/plugins/reporting/types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 589f0088a88d1..fd2ca424f4db7 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -87,7 +87,7 @@ export interface ReportingRequestPre { management: { jobTypes: any; }; - user: any; + user: any; // TODO import AuthenticatedUser from security/server } export interface RequestFacade { From 5378584f2c3a29ece4b6306b2fbb182da789293b Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Thu, 16 Jan 2020 13:37:26 -0700 Subject: [PATCH 25/25] variable rename for legacy id --- .../server/routes/generate_from_jobparams.ts | 6 +++--- .../routes/generate_from_savedobject.ts | 6 +++--- .../generate_from_savedobject_immediate.ts | 4 ++-- .../reporting/server/routes/generation.ts | 4 ++-- .../plugins/reporting/server/routes/jobs.ts | 20 +++++++++---------- .../routes/lib/make_request_facade.test.ts | 8 ++++---- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts index 95cd4c0317561..c9225dfee6978 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts @@ -56,8 +56,8 @@ export function registerGenerateFromJobParams( path: `${BASE_GENERATE}/{exportType}`, method: 'POST', options: getRouteConfig(), - handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { - const request = makeRequestFacade(originalRequest); + handler: async (legacyRequest: Legacy.Request, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(legacyRequest); let jobParamsRison: string | null; if (request.payload) { @@ -83,7 +83,7 @@ export function registerGenerateFromJobParams( if (!jobParams) { throw new Error('missing jobParams!'); } - response = await handler(exportType, jobParams, originalRequest, h); + response = await handler(exportType, jobParams, legacyRequest, h); } catch (err) { throw boom.badRequest(`invalid rison: ${jobParamsRison}`); } diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts index 649c5704ed7e5..2c509136b1b44 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject.ts @@ -33,8 +33,8 @@ export function registerGenerateCsvFromSavedObject( path: `${API_BASE_GENERATE_V1}/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { - const requestFacade = makeRequestFacade(originalRequest); + handler: async (legacyRequest: Legacy.Request, h: ReportingResponseToolkit) => { + const requestFacade = makeRequestFacade(legacyRequest); /* * 1. Build `jobParams` object: job data that execution will need to reference in various parts of the lifecycle @@ -44,7 +44,7 @@ export function registerGenerateCsvFromSavedObject( let result: QueuedJobPayload; try { const jobParams = getJobParamsFromRequest(requestFacade, { isImmediate: false }); - result = await handleRoute(CSV_FROM_SAVEDOBJECT_JOB_TYPE, jobParams, originalRequest, h); // pass the original request because the handler will make the request facade on its own + result = await handleRoute(CSV_FROM_SAVEDOBJECT_JOB_TYPE, jobParams, legacyRequest, h); // pass the original request because the handler will make the request facade on its own } catch (err) { throw handleRouteError(CSV_FROM_SAVEDOBJECT_JOB_TYPE, err); } diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts index aae6ae42ae8bc..8d1c84664cbe9 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts @@ -44,8 +44,8 @@ export function registerGenerateCsvFromSavedObjectImmediate( path: `${API_BASE_GENERATE_V1}/immediate/csv/saved-object/{savedObjectType}:{savedObjectId}`, method: 'POST', options: routeOptions, - handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { - const request = makeRequestFacade(originalRequest); + handler: async (legacyRequest: Legacy.Request, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(legacyRequest); const logger = parentLogger.clone(['savedobject-csv']); const jobParams = getJobParamsFromRequest(request, { isImmediate: true }); diff --git a/x-pack/legacy/plugins/reporting/server/routes/generation.ts b/x-pack/legacy/plugins/reporting/server/routes/generation.ts index 1d61933fa0ed3..21af54ddf11e3 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generation.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generation.ts @@ -40,10 +40,10 @@ export function registerJobGenerationRoutes( async function handler( exportTypeId: string, jobParams: object, - originalRequest: Legacy.Request, + legacyRequest: Legacy.Request, h: ReportingResponseToolkit ) { - const request = makeRequestFacade(originalRequest); + const request = makeRequestFacade(legacyRequest); const user = request.pre.user; const headers = request.headers; diff --git a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts index 788080f47c34b..a0be15d60f316 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/jobs.ts @@ -42,8 +42,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/list`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: Legacy.Request) => { - const request = makeRequestFacade(originalRequest); + handler: (legacyRequest: Legacy.Request) => { + const request = makeRequestFacade(legacyRequest); const { page: queryPage, size: querySize, ids: queryIds } = request.query as ListQuery; const page = parseInt(queryPage, 10) || 0; const size = Math.min(100, parseInt(querySize, 10) || 10); @@ -65,8 +65,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/count`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: Legacy.Request) => { - const request = makeRequestFacade(originalRequest); + handler: (legacyRequest: Legacy.Request) => { + const request = makeRequestFacade(legacyRequest); const results = jobsQuery.count(request.pre.management.jobTypes, request.pre.user); return results; }, @@ -77,8 +77,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/output/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: Legacy.Request) => { - const request = makeRequestFacade(originalRequest); + handler: (legacyRequest: Legacy.Request) => { + const request = makeRequestFacade(legacyRequest); const { docId } = request.params; return jobsQuery.get(request.pre.user, docId, { includeContent: true }).then( @@ -103,8 +103,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/info/{docId}`, method: 'GET', options: getRouteConfig(), - handler: (originalRequest: Legacy.Request) => { - const request = makeRequestFacade(originalRequest); + handler: (legacyRequest: Legacy.Request) => { + const request = makeRequestFacade(legacyRequest); const { docId } = request.params; return jobsQuery @@ -136,8 +136,8 @@ export function registerJobInfoRoutes( path: `${MAIN_ENTRY}/download/{docId}`, method: 'GET', options: getRouteConfigDownload(), - handler: async (originalRequest: Legacy.Request, h: ReportingResponseToolkit) => { - const request = makeRequestFacade(originalRequest); + handler: async (legacyRequest: Legacy.Request, h: ReportingResponseToolkit) => { + const request = makeRequestFacade(legacyRequest); const { docId } = request.params; let response = await jobResponseHandler( diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts index c062400f41f8b..8cdb7b4c018d7 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/make_request_facade.test.ts @@ -9,7 +9,7 @@ import { makeRequestFacade } from './make_request_facade'; describe('makeRequestFacade', () => { test('creates a default object', () => { - const originalRequest = ({ + const legacyRequest = ({ getBasePath: () => 'basebase', params: { param1: 123, @@ -22,7 +22,7 @@ describe('makeRequestFacade', () => { }, } as unknown) as Legacy.Request; - expect(makeRequestFacade(originalRequest)).toMatchInlineSnapshot(` + expect(makeRequestFacade(legacyRequest)).toMatchInlineSnapshot(` Object { "getBasePath": [Function], "getRawRequest": [Function], @@ -44,7 +44,7 @@ describe('makeRequestFacade', () => { }); test('getRawRequest', () => { - const originalRequest = ({ + const legacyRequest = ({ getBasePath: () => 'basebase', params: { param1: 123, @@ -57,6 +57,6 @@ describe('makeRequestFacade', () => { }, } as unknown) as Legacy.Request; - expect(makeRequestFacade(originalRequest).getRawRequest()).toBe(originalRequest); + expect(makeRequestFacade(legacyRequest).getRawRequest()).toBe(legacyRequest); }); });